repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
satr/yz-webshop | src/io/github/satr/yzwebshop/helpers/DispatchHelper.java | 1543 | package io.github.satr.yzwebshop.helpers;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DispatchHelper {
public static void dispatchWebInf(HttpServletRequest request, HttpServletResponse response, String pageName) throws ServletException, IOException {
dispatch(request, response, String.format("/WEB-INF/%s", pageName));
}
public static void dispatch(HttpServletRequest request, HttpServletResponse response, String pageUrl) throws ServletException, IOException {
request.getRequestDispatcher(pageUrl).forward(request, response);
}
public static void dispatchError(HttpServletRequest request, HttpServletResponse response, List<String> errors) throws ServletException, IOException {
Env.setRequestAttr(request, Env.RequestAttr.ERRORS, errors);
dispatchWebInf(request, response, "Error.jsp");
}
public static void dispatchError(HttpServletRequest request, HttpServletResponse response, String format, Object... args) throws ServletException, IOException {
ArrayList<String> errors = new ArrayList<>();
errors.add(String.format(format, args));
dispatchError(request, response, errors);
}
public static void dispatchHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
dispatch(request, response, "/");
}
}
| mit |
ivard/Java-OCA-OCPP--CLONE- | ocpp-v1_6/src/main/java/eu/chargetime/ocpp/SOAPMessageInfo.java | 551 | package eu.chargetime.ocpp;
import javax.xml.soap.SOAPMessage;
import java.net.InetSocketAddress;
/**
* Created by emil on 21.05.2017.
*/
public class SOAPMessageInfo {
private final InetSocketAddress address;
private final SOAPMessage message;
public SOAPMessageInfo(InetSocketAddress address, SOAPMessage message) {
this.address = address;
this.message = message;
}
public InetSocketAddress getAddress() {
return address;
}
public SOAPMessage getMessage() {
return message;
}
}
| mit |
nestorrente/jitl-core | src/main/java/com/nestorrente/jitl/template/NoOpTemplateEngine.java | 393 | package com.nestorrente.jitl.template;
import java.util.Map;
public class NoOpTemplateEngine implements TemplateEngine {
private static final TemplateEngine INSTANCE = new NoOpTemplateEngine();
public static TemplateEngine getInstance() {
return INSTANCE;
}
@Override
public String render(String templateContents, Map<String, Object> parameters) {
return templateContents;
}
}
| mit |
johannesnormannjensen/ConnectFour | src/connectfour/domain/johannes/Game.java | 191 | package connectfour.domain.johannes;
public class Game
{
public static void newGame()
{
Client.sendIt("NEW GAME");
}
public static void endGame()
{
Client.sendIt("END GAME");
}
}
| mit |
Azure/azure-sdk-for-java | sdk/customerinsights/azure-resourcemanager-customerinsights/src/main/java/com/azure/resourcemanager/customerinsights/fluent/OperationsClient.java | 1744 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.customerinsights.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.resourcemanager.customerinsights.fluent.models.OperationInner;
/** An instance of this class provides access to all the operations defined in OperationsClient. */
public interface OperationsClient {
/**
* Lists all of the available Customer Insights REST API operations.
*
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return result of the request to list Customer Insights operations.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<OperationInner> list();
/**
* Lists all of the available Customer Insights REST API operations.
*
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return result of the request to list Customer Insights operations.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<OperationInner> list(Context context);
}
| mit |
8th-mile/android-publicity | app/src/main/java/com/a8thmile/rvce/a8thmile/ui/Activities/SubEventActivity.java | 5531 | package com.a8thmile.rvce.a8thmile.ui.Activities;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.a8thmile.rvce.a8thmile.R;
import com.a8thmile.rvce.a8thmile.events.register.RegisterView;
import com.a8thmile.rvce.a8thmile.models.EventFields;
import com.a8thmile.rvce.a8thmile.models.EventResponse;
import com.a8thmile.rvce.a8thmile.models.MyEventResponse;
import com.a8thmile.rvce.a8thmile.ui.RowItem;
import com.a8thmile.rvce.a8thmile.ui.Adapters.SubEventAdapter;
import com.daprlabs.aaron.swipedeck.SwipeDeck;
import java.util.ArrayList;
import java.util.List;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class SubEventActivity extends AppCompatActivity implements RegisterView {
private List<RowItem> rowItems;
private static Integer[] images={
R.drawable.proshow1,
R.drawable.proshow2,
R.drawable.proshow3,
R.drawable.proshow3
};
private List<EventFields> eventFields;
private List<EventFields> copyEventFields;
private String token;
private SwipeDeck cardStack;
private String id;
private ProgressBar spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_event);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Exo2-Bold.otf")
.setFontAttrId(R.attr.fontPath)
.build()
);
copyEventFields=new ArrayList<EventFields>();
spinner=(ProgressBar)findViewById(R.id.progressBar);
spinner.setVisibility(View.GONE);
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/Exo2-Bold.otf");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xFF702F64));
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.subevent_title_bar, null);
TextView title=((TextView)v.findViewById(R.id.title));
title.setText(getIntent().getStringExtra("category"));
title.setTypeface(face);
getSupportActionBar().setCustomView(v);
getSupportActionBar().setElevation(0);
eventFields=getIntent().getExtras().getParcelableArrayList("subevents");
for(int i=0;i<eventFields.size();i++)
{
copyEventFields.add(i,eventFields.get(i));
}
id=getIntent().getStringExtra("user_id");
token=getIntent().getStringExtra("token");
// getSupportActionBar().setTitle(getIntent().getStringExtra("category"));
cardStack = (SwipeDeck) findViewById(R.id.swipe_deck);
SubEventAdapter adapter = new SubEventAdapter(this, R.layout.event_card, eventFields,token,id,spinner);
// lv.setAdapter(adapter);
cardStack.setAdapter(adapter);
cardStack.bringToFront();
cardStack.setCallback(new SwipeDeck.SwipeDeckCallback() {
@Override
public void cardSwipedLeft(long stableId) {
/* for (int i = 0; i < times.length; i++) {
RowItem item = new RowItem(images[i], times[i], descriptions[i]);
rowItems.add(item);
}*/
for(int i=0;i<copyEventFields.size();i++)
{
eventFields.add(copyEventFields.get(i));
}
synchronized (cardStack){
cardStack.notify();
}
}
@Override
public void cardSwipedRight(long stableId) {
/* for (int i = 0; i < times.length; i++) {
RowItem item = new RowItem(images[i], times[i], descriptions[i]);
rowItems.add(item);
}*/
for(int i=0;i<copyEventFields.size();i++)
{
eventFields.add(copyEventFields.get(i));
}
synchronized (cardStack){
cardStack.notify();
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void registered(String message) {
spinner.setVisibility(View.GONE);
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
@Override
public void RegisterFailed(String message) {
spinner.setVisibility(View.GONE);
Toast.makeText(this,"Failed. "+message,Toast.LENGTH_LONG).show();
}
@Override
public void wishListGot(EventResponse eventResponse) {
//Irrelevant to this activity
}
@Override
public void MyEventListGot(MyEventResponse eventResponse) {
}
}
| mit |
lobobrowser/Cobra | src/main/java/org/cobraparser/html/BrowserFrame.java | 2495 | /*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
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 St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Jan 29, 2006
*/
package org.cobraparser.html;
import java.awt.Component;
import java.net.URL;
import org.eclipse.jdt.annotation.NonNull;
import org.w3c.dom.Document;
/**
* The <code>BrowserFrame</code> interface represents a browser frame. A simple
* implementation of this interface is provided in
* {@link org.cobraparser.html.test.SimpleBrowserFrame}.
*/
public interface BrowserFrame {
/**
* Gets the component that renders the frame. This can be a
* {@link org.cobraparser.html.gui.HtmlPanel}.
*/
public Component getComponent();
/**
* Loads a URL in the frame.
*/
public void loadURL(@NonNull URL url);
/**
* Gets the content document.
*/
public Document getContentDocument();
/**
* Sets the content document.
*/
public void setContentDocument(Document d);
/**
* Gets the {@link HtmlRendererContext} of the frame.
*/
public HtmlRendererContext getHtmlRendererContext();
/**
* Sets the default margin insets of the browser frame.
*
* @param insets
* The margin insets.
*/
public void setDefaultMarginInsets(java.awt.Insets insets);
/**
* Sets the default horizontal overflow of the browser frame.
*
* @param overflowX
* See constants in {@link org.cobraparser.html.style.RenderState}.
*/
public void setDefaultOverflowX(int overflowX);
/**
* Sets the default vertical overflow of the browser frame.
*
* @param overflowY
* See constants in {@link org.cobraparser.html.style.RenderState}.
*/
public void setDefaultOverflowY(int overflowY);
}
| mit |
j574y923/MPOverviewer | src/mpoverviewer/data_layer/serialize/SMPToData.java | 231 | package mpoverviewer.data_layer.serialize;
import mpoverviewer.data_layer.data.Song;
/**
*
* @author J
*/
public class SMPToData {
public Song getSMPToData(String songContent) {
return null;
}
}
| mit |
aterai/java-swing-tips | SortTree/src/java/example/MainPanel.java | 10906 | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
DefaultMutableTreeNode root = TreeUtil.makeTreeRoot();
JTree tree = new JTree(new DefaultTreeModel(TreeUtil.makeTreeRoot()));
// JRadioButton sort0 = new JRadioButton("0: bubble sort");
JRadioButton sort1 = new JRadioButton("1: bubble sort");
JRadioButton sort2 = new JRadioButton("2: selection sort");
// JRadioButton sort3 = new JRadioButton("3: iterative merge sort"); // JDK 1.6.0
JRadioButton sort3 = new JRadioButton("3: TimSort"); // JDK 1.7.0
JRadioButton reset = new JRadioButton("reset");
JPanel box = new JPanel(new GridLayout(2, 2));
ActionListener listener = e -> {
JRadioButton check = (JRadioButton) e.getSource();
if (check.equals(reset)) {
tree.setModel(new DefaultTreeModel(root));
} else {
TreeUtil.COMPARE_COUNTER.set(0);
TreeUtil.SWAP_COUNTER.set(0);
DefaultMutableTreeNode r = TreeUtil.deepCopy(root, (DefaultMutableTreeNode) root.clone());
if (check.equals(sort1)) {
TreeUtil.sortTree1(r);
} else if (check.equals(sort2)) {
TreeUtil.sortTree2(r);
} else {
TreeUtil.sortTree3(r);
}
swapCounter(check.getText());
tree.setModel(new DefaultTreeModel(r));
}
TreeUtil.expandAll(tree);
};
ButtonGroup bg = new ButtonGroup();
Stream.of(reset, sort1, sort2, sort3).forEach(check -> {
box.add(check);
bg.add(check);
check.addActionListener(listener);
});
add(box, BorderLayout.SOUTH);
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder("Sort JTree"));
p.add(new JScrollPane(tree));
add(p);
TreeUtil.expandAll(tree);
setPreferredSize(new Dimension(320, 240));
}
private static void swapCounter(String title) {
if (TreeUtil.SWAP_COUNTER.get() == 0) {
int cc = TreeUtil.COMPARE_COUNTER.get();
System.out.format("%-24s - compare: %3d, swap: ---%n", title, cc);
} else {
int cc = TreeUtil.COMPARE_COUNTER.get();
int sc = TreeUtil.SWAP_COUNTER.get();
System.out.format("%-24s - compare: %3d, swap: %3d%n", title, cc, sc);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
final class TreeUtil {
public static final AtomicInteger COMPARE_COUNTER = new AtomicInteger();
public static final AtomicInteger SWAP_COUNTER = new AtomicInteger();
// // JDK 1.7.0
// TreeNodeComparator COMPARATOR = new TreeNodeComparator();
// class TreeNodeComparator implements Comparator<DefaultMutableTreeNode>, Serializable {
// private static final long serialVersionUID = 1L;
// @Override public int compare(DefaultMutableTreeNode n1, DefaultMutableTreeNode n2) {
// COMPARE_COUNTER.getAndIncrement();
// if (n1.isLeaf() && !n2.isLeaf()) {
// return 1;
// } else if (!n1.isLeaf() && n2.isLeaf()) {
// return -1;
// } else {
// String s1 = n1.getUserObject().toString();
// String s2 = n2.getUserObject().toString();
// return s1.compareToIgnoreCase(s2);
// }
// }
// }
// JDK 1.8.0
private static final Comparator<DefaultMutableTreeNode> COMPARATOR =
Comparator.comparing(DefaultMutableTreeNode::isLeaf)
.thenComparing(n -> n.getUserObject().toString());
private TreeUtil() {
/* Singleton */
}
// // https://community.oracle.com/thread/1355435 How to sort jTree Nodes
// public static void sortTree0(DefaultMutableTreeNode root) {
// for (int i = 0; i < root.getChildCount(); i++) {
// DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
// for (int j = 0; j < i; j++) {
// DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root.getChildAt(j);
// COMPARE_COUNTER.getAndIncrement();
// if (COMPARATOR.compare(node, prevNode) < 0) {
// root.insert(node, j);
// root.insert(prevNode, i);
// SWAP_COUNTER.getAndIncrement();
// i--; // add
// break;
// }
// }
// if (!node.isLeaf()) {
// sortTree0(node);
// }
// }
// }
public static void sortTree1(DefaultMutableTreeNode root) {
int n = root.getChildCount();
for (int i = 0; i < n - 1; i++) {
for (int j = n - 1; j > i; j--) {
DefaultMutableTreeNode curNode = (DefaultMutableTreeNode) root.getChildAt(j);
DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root.getChildAt(j - 1);
if (!prevNode.isLeaf()) {
sortTree1(prevNode);
}
if (COMPARATOR.compare(prevNode, curNode) > 0) {
SWAP_COUNTER.getAndIncrement();
root.insert(curNode, j - 1);
root.insert(prevNode, j);
}
}
}
}
private static void sort2(DefaultMutableTreeNode parent) {
int n = parent.getChildCount();
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (COMPARATOR.compare((DefaultMutableTreeNode) parent.getChildAt(min),
(DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
min = j;
}
}
if (i != min) {
SWAP_COUNTER.getAndIncrement();
MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
parent.insert(b, i);
parent.insert(a, min);
// MutableTreeNode node = (MutableTreeNode) parent.getChildAt(min);
// parent.insert(node, i);
// COMPARE_COUNTER++;
}
}
}
public static void sortTree2(DefaultMutableTreeNode parent) {
// Java 9: Collections.list(parent.preorderEnumeration()).stream()
Collections.list((Enumeration<?>) parent.preorderEnumeration()).stream()
.filter(DefaultMutableTreeNode.class::isInstance)
.map(DefaultMutableTreeNode.class::cast)
.filter(node -> !node.isLeaf())
.forEach(TreeUtil::sort2);
}
private static void sort3(DefaultMutableTreeNode parent) {
// @SuppressWarnings("unchecked")
// Enumeration<DefaultMutableTreeNode> e = parent.children();
// ArrayList<DefaultMutableTreeNode> children = Collections.list(e);
int n = parent.getChildCount();
List<DefaultMutableTreeNode> children = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
children.add((DefaultMutableTreeNode) parent.getChildAt(i));
}
children.sort(COMPARATOR);
parent.removeAllChildren();
children.forEach(parent::add);
}
public static void sortTree3(DefaultMutableTreeNode parent) {
// Java 9: Collections.list(parent.preorderEnumeration()).stream()
Collections.list((Enumeration<?>) parent.preorderEnumeration()).stream()
.filter(DefaultMutableTreeNode.class::isInstance)
.map(DefaultMutableTreeNode.class::cast)
.filter(node -> !node.isLeaf())
.forEach(TreeUtil::sort3);
}
public static DefaultMutableTreeNode deepCopy(MutableTreeNode src, DefaultMutableTreeNode tgt) {
// Java 9: Collections.list(src.children()).stream()
Collections.list((Enumeration<?>) src.children()).stream()
.filter(DefaultMutableTreeNode.class::isInstance)
.map(DefaultMutableTreeNode.class::cast)
.forEach(node -> {
DefaultMutableTreeNode clone = new DefaultMutableTreeNode(node.getUserObject());
tgt.add(clone);
if (!node.isLeaf()) {
deepCopy(node, clone);
}
});
// for (int i = 0; i < src.getChildCount(); i++) {
// DefaultMutableTreeNode node = (DefaultMutableTreeNode) src.getChildAt(i);
// DefaultMutableTreeNode clone = new DefaultMutableTreeNode(node.getUserObject());
// // DefaultMutableTreeNode clone = (DefaultMutableTreeNode) node.clone();
// tgt.add(clone);
// if (!node.isLeaf()) {
// deepCopyTree(node, clone);
// }
// }
return tgt;
}
public static DefaultMutableTreeNode makeTreeRoot() {
DefaultMutableTreeNode set1 = new DefaultMutableTreeNode("Set 001");
DefaultMutableTreeNode set4 = new DefaultMutableTreeNode("Set 004");
set1.add(new DefaultMutableTreeNode("3333333333333333"));
set1.add(new DefaultMutableTreeNode("111111111"));
set1.add(new DefaultMutableTreeNode("22222222222"));
set1.add(set4);
set1.add(new DefaultMutableTreeNode("222222"));
set1.add(new DefaultMutableTreeNode("222222222"));
DefaultMutableTreeNode set2 = new DefaultMutableTreeNode("Set 002");
set2.add(new DefaultMutableTreeNode("eee eee eee eee e"));
set2.add(new DefaultMutableTreeNode("bbb ccc aaa bbb"));
DefaultMutableTreeNode set3 = new DefaultMutableTreeNode("Set 003");
set3.add(new DefaultMutableTreeNode("zzz zz zz"));
set3.add(new DefaultMutableTreeNode("aaa aaa aaa aaa"));
set3.add(new DefaultMutableTreeNode("ccc ccc ccc"));
set4.add(new DefaultMutableTreeNode("22222222222"));
set4.add(new DefaultMutableTreeNode("eee eee eee ee ee"));
set4.add(new DefaultMutableTreeNode("bbb bbb bbb bbb"));
set4.add(new DefaultMutableTreeNode("zzz zz zz"));
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
root.add(new DefaultMutableTreeNode("xxx xxx xxx xx xx"));
root.add(set3);
root.add(new DefaultMutableTreeNode("eee eee eee ee ee"));
root.add(set1);
root.add(set2);
root.add(new DefaultMutableTreeNode("222222222222"));
root.add(new DefaultMutableTreeNode("bbb bbb bbb bbb"));
return root;
}
public static void expandAll(JTree tree) {
int row = 0;
while (row < tree.getRowCount()) {
tree.expandRow(row++);
}
}
}
| mit |
krHasan/Money-Manager | src/view/TransactionHistoryStage.java | 827 | package view;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class TransactionHistoryStage extends Application {
@Override
public void start(Stage TransactionHistoryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/view/TransactionHistory.fxml"));
Scene scene = new Scene(root,800,550);
// scene.getStylesheets().add(getClass().getResource("SignIn.css").toExternalForm());
TransactionHistoryStage.setScene(scene);
TransactionHistoryStage.setResizable(false);
TransactionHistoryStage.setTitle("Transaction History");
TransactionHistoryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
| mit |
DDoS/OnlineGame | src/main/java/ecse414/fall2015/group21/game/server/console/Console.java | 3248 | /*
* This file is part of Online Game, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2015 Group 21
*
* 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 ecse414.fall2015.group21.game.server.console;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Consumer;
/**
* Represents a console, which is a command line input and output.
*/
public class Console {
private final Map<String, Consumer<String[]>> executors = new HashMap<>();
private final InputStream input;
private final OutputStream output;
private final Runnable stopper;
private volatile Scanner scanner;
private volatile PrintStream printer;
private volatile boolean running = false;
public Console(InputStream input, OutputStream output, Runnable stopper) {
this.input = input;
this.output = output;
this.stopper = stopper;
executors.put("stop", this::executorStop);
}
public void start() {
scanner = new Scanner(input);
printer = output instanceof PrintStream ? (PrintStream) output : new PrintStream(output);
running = true;
new Thread(this::run).start();
}
private void run() {
while (running && scanner.hasNextLine()) {
final String[] command = scanner.nextLine().split(" ");
if (command[0].isEmpty()) {
continue;
}
final Consumer<String[]> executor = executors.get(command[0]);
if (executor == null) {
printer.println("Unknown command");
} else {
executor.accept(command);
}
}
scanner.close();
scanner = null;
printer.close();
printer = null;
}
public void stop() {
running = false;
try {
input.close();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
private void executorStop(String[] args) {
printer.println("Stopping...");
stopper.run();
}
}
| mit |
surli/spinefm | spinefm-eclipseplugins-root/spinefm-core/test/fr/unice/spinefm/utils/test/TestUtils.java | 3624 | package fr.unice.spinefm.utils.test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.junit.Test;
import fr.unice.spinefm.ActionModel.UserActionModel.UserActionModelFactory;
import fr.unice.spinefm.ActionModel.UserActionModel.UserCreateContext;
import fr.unice.spinefm.HistoryModel.HistoryModelFactory;
import fr.unice.spinefm.HistoryModel.Past;
import fr.unice.spinefm.ProcessModel.ContextManager;
import fr.unice.spinefm.ProcessModel.ProcessModelFactory;
import fr.unice.spinefm.ProcessModel.impl.ContextManagerImplDelegate;
import fr.unice.spinefm.fmengine.FMSpineFMAdapter;
import fr.unice.spinefm.fmengine.familiar.FMLSpineFMAdapter;
import fr.unice.spinefm.fmengine.familiar.FamiliarInterpreter;
import fr.unice.spinefm.utils.PersistModel;
import fr.unice.spinefm.utils.Utils;
public class TestUtils {
@Test
public void testMatchListWorksWhenFirstListIsIncludedInSecondOneWithSameOrder() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l1.add("bar");
l1.add("machin");
l2.add("toto");
l2.add("bar");
l2.add("machin");
l2.add("truc");
l2.add("bidule");
assertTrue(Utils.matchList(l1, l2));
}
@Test
public void testMatchListWorksWhenSecondListIsIncludedInFirstOneWithSameOrder() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l2.add("bar");
l2.add("machin");
l1.add("toto");
l1.add("bar");
l1.add("machin");
l1.add("truc");
l1.add("bidule");
assertTrue(Utils.matchList(l1, l2));
}
@Test
public void testMatchListWorksWhenFirstListIsIncludedInSecondOneWithNoOrder() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l1.add("truc");
l1.add("toto");
l1.add("bar");
l2.add("toto");
l2.add("bar");
l2.add("machin");
l2.add("truc");
l2.add("bidule");
assertTrue(Utils.matchList(l1, l2));
}
@Test
public void testMatchListWorksWhenSecondListIsIncludedInFirstOneWithNoOrder() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l1.add("truc");
l1.add("toto");
l1.add("bar");
l2.add("toto");
l2.add("bar");
l2.add("machin");
l2.add("truc");
l2.add("bidule");
assertTrue(Utils.matchList(l2, l1));
}
@Test
public void testMatchListFailsWhenAtListOneElementIsNotPresentInTheSecondList() {
List<String> l1 = new ArrayList<String>();
List<String> l2 = new ArrayList<String>();
l1.add("truc");
l1.add("foo");
l1.add("bar");
l2.add("toto");
l2.add("bar");
l2.add("machin");
l2.add("truc");
l2.add("bidule");
assertFalse(Utils.matchList(l2, l1));
}
@Test
public void contextManagerPersistencyWorks() throws IOException {
ContextManager cm = ProcessModelFactory.eINSTANCE.createContextManager();
Past p = HistoryModelFactory.eINSTANCE.createPast();
cm.setPast(p);
UserCreateContext ucc = UserActionModelFactory.eINSTANCE.createUserCreateContext();
ucc.initManualAction(cm);
FMSpineFMAdapter fma = new FMLSpineFMAdapter(FamiliarInterpreter.getInstance());
cm.setFma(fma);
PersistModel.saveModel("/tmp", "testPersistency.xml", cm);
assertTrue(cm instanceof ContextManagerImplDelegate);
}
}
| mit |
shaunmahony/seqcode | src/edu/psu/compbio/seqcode/gse/utils/probability/boundaries/PValuator.java | 3932 | /*
* Created on Feb 24, 2006
*/
package edu.psu.compbio.seqcode.gse.utils.probability.boundaries;
import java.util.*;
import edu.psu.compbio.seqcode.gse.utils.*;
import edu.psu.compbio.seqcode.gse.utils.numeric.Numerical;
import edu.psu.compbio.seqcode.gse.utils.probability.*;
/**
* @author tdanford
*/
public interface PValuator {
public PValueResult logPValue(BoundaryDataset ds);
public static class MannWhitney implements PValuator {
private int[] argArray;
private MannWhitneyEquation eq;
public MannWhitney() {
argArray = new int[3];
eq = new MannWhitneyEquation();
}
/* (non-Javadoc)
* @see edu.mit.csail.psrg.tdanford.boundary.pvalues.PValuator#logPValue(edu.mit.csail.psrg.tdanford.boundary.pvalues.BoundaryDataset)
*/
public PValueResult logPValue(BoundaryDataset ds) {
int n = 0, m = 0, u = 0;
int dir = ds.getBoundaryDirection();
String dsRep = null;
if(dir == 1) {
n = ds.getNumNegative();
m = ds.getNumPositive();
dsRep = ds.createStringRep(1);
} else {
n = ds.getNumPositive();
m = ds.getNumNegative();
dsRep = ds.createStringRep(0);
}
//u = MannWhitneyEquation.calculateUFromT(m, n, dsRep);
u = MannWhitneyEquation.calculateU(dsRep);
double pv = eq.getLowerPValue(m, n, u);
System.out.println("[" + m + "," + n + "," + u + "] --> " + pv);
double logPV = Math.log(pv);
PValueResult pvr =
new PValueResult(ds.toString(), ds.getError(), dir, logPV);
return pvr;
}
}
public static class KolmogorovSmirnov implements PValuator {
public KolmogorovSmirnov() {
}
/* (non-Javadoc)
* @see edu.mit.csail.psrg.tdanford.boundary.pvalues.PValuator#logPValue(edu.mit.csail.psrg.tdanford.boundary.pvalues.BoundaryDataset)
*/
public PValueResult logPValue(BoundaryDataset ds) {
int N = ds.size();
int pos = ds.getNumPositive();
int errors = ds.getError();
double[] posa = ds.getPositiveArray();
double[] nega = ds.getNegativeArray();
Pair<Double,Double> ks = Numerical.kstwo(posa, nega);
double logPValue = Math.log(ks.getLast());
PValueResult pvr =
new PValueResult(ds.toString(), ds.getError(), ds.getBoundaryDirection(), logPValue);
return pvr;
}
}
public static class Spearman implements PValuator {
public Spearman() {
}
/* (non-Javadoc)
* @see edu.mit.csail.psrg.tdanford.boundary.pvalues.PValuator#logPValue(edu.mit.csail.psrg.tdanford.boundary.pvalues.BoundaryDataset)
*/
public PValueResult logPValue(BoundaryDataset ds) {
int N = ds.size();
int pos = ds.getNumPositive();
int errors = ds.getError();
double[] posa = ds.getPositiveArray();
double[] nega = ds.getNegativeArray();
Numerical.SpearmanResult res = Numerical.spear(posa, nega);
double logPValue = Math.log(res.getProbRS());
int dir = res.getRS() >= 0.0 ? 1 : -1;
PValueResult pvr =
new PValueResult(ds.toString(), ds.getError(), dir, logPValue);
return pvr;
}
}
}
| mit |
jeremyghilain/JGH | OOprog/src/eu/epfc/cours3449/Geometry/Testcercle.java | 409 | package eu.epfc.cours3449.Geometry;
import java.util.*;
public class Testcercle {
public static void main(String[] args) {
Cercle c1=new Cercle(5,"blanc");
Cercle c2=new Cercle(3,"bleu");
System.out.println(c1.getArea());
System.out.println(Cercle.nbInstances); //On utilise la classe plutot que l'objet car c'est Static
}
}
| mit |
SeetiTel/Android | app/src/main/java/com/yoloswag/alex/seetitel/MyArrayAdapter.java | 1786 | package com.yoloswag.alex.seetitel;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by Alex on 5/2/15.
*/
public class MyArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private final String[] descriptions;
private final String[] dataType;
public MyArrayAdapter(Context context, String[] values, String[] descriptions, String[] dataType) {
super(context, R.layout.row_layout, values);
this.context = context;
this.values = values;
this.descriptions = descriptions;
this.dataType = dataType;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row_layout, parent, false);
TextView title = (TextView) rowView.findViewById(R.id.label);
TextView description = (TextView) rowView.findViewById(R.id.des);
ImageView iv = (ImageView) rowView.findViewById(R.id.icon);
title.setText(values[position]);
description.setText(descriptions[position]);
if(dataType[position].equals("text")) {
iv.setImageResource(R.drawable.noun_text);
}
else if(dataType[position].equals("image")) {
iv.setImageResource(R.drawable.noun_image);
}
else if (dataType[position].equals("audio")) {
iv.setImageResource(R.drawable.noun_audio);
}
return rowView;
}
}
| mit |
RodrigoQuesadaDev/XGen4J | xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/instantiation/errorWithNoDescriptionAreAbstract/ExceptionInfo.java | 983 | package com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract;
import com.rodrigodev.xgen4j.test.instantiation.errorWithNoDescriptionAreAbstract.RootException.ExceptionType;
import java.util.Optional;
/**
* Autogenerated by XGen4J on January 1, 0001.
*/
public class ExceptionInfo {
final private Class<? extends RootException> clazz;
final private Optional<ExceptionType> type;
private ExceptionInfo(Optional<ExceptionType> type, Class<? extends RootException> clazz) {
this.type = type;
this.clazz = clazz;
}
public ExceptionInfo(Class<? extends RootException> clazz) {
this(Optional.<ExceptionType>empty(), clazz);
}
public ExceptionInfo(ExceptionType type, Class<? extends RootException> clazz) {
this(Optional.of(type), clazz);
}
public Class<? extends RootException> clazz() {
return clazz;
}
public Optional<ExceptionType> type() {
return type;
}
}
| mit |
dowobeha/thrax | src/edu/jhu/thrax/util/UnknownGrammarTypeException.java | 472 | package edu.jhu.thrax.util;
/**
* This exception is thrown when the "grammar" option provided by the user is
* not known by Thrax.
*/
@SuppressWarnings("serial")
public class UnknownGrammarTypeException extends InvalidConfigurationException {
private String type;
public UnknownGrammarTypeException(String t)
{
type = t;
}
public String getMessage()
{
return String.format("Unknown grammar type provided: %s", type);
}
}
| mit |
migulorama/feup-sdis-2014 | src/pt/up/fe/sdis/proj1/gui/FileBackupDialog.java | 5872 | package pt.up.fe.sdis.proj1.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import pt.up.fe.sdis.proj1.BackupSystem;
import pt.up.fe.sdis.proj1.gui.utils.GuiUtils;
import net.miginfocom.swing.MigLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.awt.Cursor;
public class FileBackupDialog extends JDialog {
private static final long serialVersionUID = 1L;
private final JPanel contentPanel = new JPanel();
private JTextField backupFilePath_txt;
private JSpinner replicationDegree_spn;
private boolean _succeed = false;
/**
* Create the dialog.
*/
public FileBackupDialog(JFrame frame, final BackupSystem backupSystem) {
setResizable(false);
setModal(true);
setBounds(100, 100, 426, 143);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(new MigLayout("", "[20px][86px][47px][94px][31px]", "[20px][]"));
{
JLabel lblFile = new JLabel("File:");
contentPanel.add(lblFile, "cell 0 0,alignx left,aligny center");
}
{
backupFilePath_txt = new JTextField();
backupFilePath_txt.setEditable(false);
String userHome = System.getProperty("user.home");
if (userHome != null)
backupFilePath_txt.setText(userHome);
contentPanel.add(backupFilePath_txt, "cell 1 0 3 1,growx,aligny top");
backupFilePath_txt.setColumns(10);
}
{
JLabel lblbrowse = new JLabel("<html><u>Browse...</u></html>");
lblbrowse.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblbrowse.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
File defaultDir = new File(backupFilePath_txt.getText());
if (!defaultDir.exists())
defaultDir = defaultDir.getParentFile();
JFileChooser fileChooser = new JFileChooser(defaultDir);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = fileChooser.showOpenDialog(FileBackupDialog.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
backupFilePath_txt.setText(fileChooser.getSelectedFile().getAbsolutePath());
}
}
});
lblbrowse.setForeground(Color.BLUE);
contentPanel.add(lblbrowse, "cell 4 0,alignx left,aligny center");
}
{
JLabel lblReplicationDegree = new JLabel("Replication Degree:");
contentPanel.add(lblReplicationDegree, "cell 0 1,alignx left,aligny center");
}
{
replicationDegree_spn = new JSpinner();
int rd = backupSystem.getDefaultReplicationDegree();
if (rd < 1 || rd > 9) rd = 1;
replicationDegree_spn.setModel(new SpinnerNumberModel(rd, 1, 9, 1));
contentPanel.add(replicationDegree_spn, "cell 1 1,growx,aligny top");
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
File f = new File(backupFilePath_txt.getText());
_succeed = f.exists() && f.isFile();
if (!_succeed) {
JOptionPane.showMessageDialog(FileBackupDialog.this,
"Invalid file selected.",
"Error!",
JOptionPane.ERROR_MESSAGE);
} else
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
_succeed = false;
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
GuiUtils.setSystemLookAndFeel();
pack();
setLocation((int)frame.getBounds().getCenterX() - this.getWidth() / 2,
(int)frame.getBounds().getCenterY() - this.getHeight() / 2);
}
}
public boolean succeed() {
return _succeed;
}
public String getBackupFilePath() {
return backupFilePath_txt.getText();
}
public Integer getBackupReplicationDegree() {
return (Integer)replicationDegree_spn.getValue();
}
}
| mit |
servicosgovbr/editor-de-servicos | src/test/java/br/gov/servicos/editor/fixtures/RepositorioCartasBuilder.java | 3372 | package br.gov.servicos.editor.fixtures;
import br.gov.servicos.editor.conteudo.TipoPagina;
import br.gov.servicos.editor.utils.EscritorDeArquivos;
import lombok.experimental.FieldDefaults;
import org.eclipse.jgit.api.Git;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import static br.gov.servicos.editor.conteudo.TipoPagina.*;
import static br.gov.servicos.editor.utils.Unchecked.Supplier.uncheckedSupplier;
import static java.util.Arrays.asList;
import static lombok.AccessLevel.PRIVATE;
@FieldDefaults(makeFinal = true, level = PRIVATE)
public class RepositorioCartasBuilder {
Path localRepositorio;
Map<Path, String> paginas;
public RepositorioCartasBuilder(Path localRepositorio) {
this.localRepositorio = localRepositorio;
paginas = new HashMap<>();
}
public RepositorioCartasBuilder touchCarta(String id) {
return carta(id, "");
}
public RepositorioCartasBuilder carta(String id, String conteudo) {
return pagina(SERVICO, id, conteudo);
}
public RepositorioCartasBuilder touchOrgao(String id) {
return orgao(id, "");
}
public RepositorioCartasBuilder orgao(String id, String conteudo) {
return pagina(ORGAO, id, conteudo);
}
public RepositorioCartasBuilder touchPaginaTematica(String id) {
return paginaTematica(id, "");
}
public RepositorioCartasBuilder paginaTematica(String id, String conteudo) {
return pagina(PAGINA_TEMATICA, id, conteudo);
}
public boolean buildSemGit() {
return criarEstruturaRepositorioCartas()
&& criarPaginas();
}
public boolean build() {
return buildSemGit() && commitPush();
}
private boolean commitPush() {
try {
Git git = Git.open(localRepositorio.toFile());
git.add().addFilepattern(".").call();
git.commit()
.setAuthor("Teste", "teste.automatizado@gmail.com")
.setMessage("setup de testes")
.call();
git.push().setPushAll().call();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private boolean criarPaginas() {
EscritorDeArquivos escritor = new EscritorDeArquivos();
paginas.entrySet()
.stream()
.forEach(entry -> escritor.escrever(localRepositorio.resolve(entry.getKey()), entry.getValue()));
return true;
}
private RepositorioCartasBuilder pagina(TipoPagina tipo, String id, String conteudo) {
Path p = Paths.get(tipo.getCaminhoPasta().toString(), id + '.' + tipo.getExtensao());
paginas.put(p, conteudo);
return this;
}
private boolean criarEstruturaRepositorioCartas() {
return asList(values())
.stream()
.map(t -> localRepositorio.resolve(t.getCaminhoPasta()))
.map(Path::toFile)
.map(f -> {
//noinspection ResultOfMethodCallIgnored
f.mkdirs();
return uncheckedSupplier(() -> f.toPath().resolve("dummy").toFile().createNewFile());
})
.allMatch(Supplier::get);
}
}
| mit |
opentdc/test-solution | src/java/test/org/opentdc/addressbooks/ContactAddressTest.java | 12111 | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 Arbalo AG
*
* 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 test.org.opentdc.addressbooks;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.cxf.jaxrs.client.WebClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opentdc.addressbooks.AddressModel;
import org.opentdc.addressbooks.ContactModel;
import org.opentdc.service.ServiceUtil;
/**
* Testing addresses of contacts.
* @author Bruno Kaiser
*
*/
public class ContactAddressTest extends AbstractAddressTestClient {
private static final String CN = "ContactAddressTest";
private static ContactModel contact = null;
@Before
public void initializeTests() {
super.initializeTests(CN);
contact = ContactTest.post(wc, adb.getId(), new ContactModel(CN + "1", CN + "2"), Status.OK);
}
@After
public void cleanupTest() {
super.cleanupTest();
}
/********************************** address attributes tests *********************************/
@Test
public void testEmptyConstructor() {
super.testEmptyConstructor();
}
@Test
public void testId() {
super.testId();
}
@Test
public void testAddressType() {
super.testAddressType();
}
@Test
public void testAttributeType() {
super.testAttributeType();
}
@Test
public void testMsgType() {
super.testMsgType();
}
@Test
public void testValue() {
super.testValue();
}
@Test
public void testStreet() {
super.testStreet();
}
@Test
public void testPostalCode() {
super.testPostalCode();
}
@Test
public void testCity() {
super.testCity();
}
@Test
public void testCountry() {
super.testCountry();
}
@Test
public void testCreatedBy() {
super.testCreatedBy();
}
@Test
public void testCreatedAt() {
super.testCreatedAt();
}
@Test
public void testModifiedBy() {
super.testModifiedBy();
}
@Test
public void testModifiedAt() {
super.testModifiedAt();
}
/********************************* REST service tests *********************************/
// create: POST p "api/addressbooks/{abid}/contact/{cid}/address"
// read: GET "api/addressbooks/{abid}/contact/{cid}/address/{adrid}"
// update: PUT p "api/addressbooks/{abid}/contact/{cid}/address/{adrid}"
// delete: DELETE "api/addressbooks/{abid}/contact/{cid}/address/{ardid}"
@Test
public void testCreateReadDeleteWithEmptyConstructor() {
super.testCreateReadDeleteWithEmptyConstructor();
}
@Test
public void testCreateReadDelete() {
super.testCreateReadDelete();
}
@Test
public void testClientSideId() {
super.testClientSideId();
}
@Test
public void testDuplicateId() {
super.testDuplicateId();
}
@Test
public void testList() {
super.testList();
}
@Test
public void testCreate() {
super.testCreate();
}
@Test
public void testCreateDouble() {
super.testCreateDouble();
}
@Test
public void testRead() {
super.testRead();
}
@Test
public void testMultiRead() {
super.testMultiRead();
}
@Test
public void testUpdate() {
super.testUpdate();
}
@Test
public void testAddressTypePhone() {
super.testAddressTypePhone();
}
@Test
public void testAddressTypeEmail() {
super.testAddressTypeEmail();
}
@Test
public void testAddressTypeWeb() {
super.testAddressTypeWeb();
}
@Test
public void testAddressTypeMessaging() {
super.testAddressTypeMessaging();
}
@Test
public void testAddressTypePostal() {
super.testAddressTypePostal();
}
@Test
public void testDelete() {
super.testDelete();
}
@Test
public void testDoubleDelete() {
super.testDoubleDelete();
}
@Test
public void testModifications() {
super.testModifications();
}
/********************************** helper methods *********************************/
/* (non-Javadoc)
* @see test.org.opentdc.addressbooks.AbstractAddressTest#list(java.lang.String, javax.ws.rs.core.Response.Status)
*/
@Override
protected List<AddressModel> list(
String query,
Status expectedStatus) {
return list(wc, adb.getId(), contact.getId(), query, 0, Integer.MAX_VALUE, expectedStatus);
}
/**
* Retrieve a list of AddressModel from AddressbooksService by executing a HTTP GET request.
* @param webClient the WebClient for the AddressbooksService
* @param aid the id of the addressbook
* @param cid the id of the contact
* @param query the URL query to use
* @param position the position to start a batch with
* @param size the size of a batch
* @param expectedStatus the expected HTTP status to test on
* @return a List of AddressModel objects in JSON format
*/
public static List<AddressModel> list(
WebClient webClient,
String aid,
String cid,
String query,
int position,
int size,
Status expectedStatus) {
webClient.resetQuery();
webClient.replacePath("/").path(aid).path(ServiceUtil.CONTACT_PATH_EL).path(cid).path(ServiceUtil.ADDRESS_PATH_EL);
Response _response = executeListQuery(webClient, query, position, size);
List<AddressModel> _texts = null;
if (expectedStatus != null) {
assertEquals("list() should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
if (_response.getStatus() == Status.OK.getStatusCode()) {
_texts = new ArrayList<AddressModel>(webClient.getCollection(AddressModel.class));
System.out.println("list(webClient, " + aid + ", " + cid + ", " + query + ", " + position + ", " + size + ", " + expectedStatus.toString() +
") ->" + _texts.size() + " objects");
}
else {
System.out.println("list(webClient, " + aid + ", " + cid + ", "+ query + ", " + position + ", " + size + ", " + expectedStatus.toString() +
") -> Status: " + _response.getStatus());
}
return _texts;
}
/* (non-Javadoc)
* @see test.org.opentdc.addressbooks.AbstractAddressTest#post(org.opentdc.addressbooks.AddressModel, javax.ws.rs.core.Response.Status)
*/
@Override
protected AddressModel post(
AddressModel model,
Status expectedStatus) {
return post(wc, adb.getId(), contact.getId(), model, expectedStatus);
}
/**
* Create a new AddressModel on the server by executing a HTTP POST request.
* @param webClient the WebClient representing the AddressbooksService
* @param aid the id of the addressbook
* @param cid the id of the contact
* @param model the AddressModel data to create on the server
* @param exceptedStatus the expected HTTP status to test on
* @return the created AddressModel
*/
public static AddressModel post(
WebClient webClient,
String aid,
String cid,
AddressModel model,
Status expectedStatus) {
Response _response = webClient.replacePath("/").path(aid).path(ServiceUtil.CONTACT_PATH_EL).path(cid).path(ServiceUtil.ADDRESS_PATH_EL).post(model);
if (expectedStatus != null) {
assertEquals("POST should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
if (_response.getStatus() == Status.OK.getStatusCode()) {
return _response.readEntity(AddressModel.class);
} else {
return null;
}
}
/* (non-Javadoc)
* @see test.org.opentdc.addressbooks.AbstractAddressTest#get(java.lang.String, javax.ws.rs.core.Response.Status)
*/
@Override
protected AddressModel get(
String adrId,
Status expectedStatus) {
return get(wc, adb.getId(), contact.getId(), adrId, expectedStatus);
}
/**
* Read the AddressModel with id from AddressbooksService by executing a HTTP GET method.
* @param webClient the web client representing the AddressbooksService
* @param aid the id of the addressbook
* @param cid the id of the contact
* @param adrId the id of the AddressModel to retrieve
* @param expectedStatus the expected HTTP status to test on
* @return the retrieved AddressModel object in JSON format
*/
public static AddressModel get(
WebClient webClient,
String aid,
String cid,
String adrId,
Status expectedStatus) {
Response _response = webClient.replacePath("/").path(aid).path(ServiceUtil.CONTACT_PATH_EL).path(cid).path(ServiceUtil.ADDRESS_PATH_EL).path(adrId).get();
if (expectedStatus != null) {
assertEquals("GET should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
if (_response.getStatus() == Status.OK.getStatusCode()) {
return _response.readEntity(AddressModel.class);
} else {
return null;
}
}
/* (non-Javadoc)
* @see test.org.opentdc.addressbooks.AbstractAddressTest#put(org.opentdc.addressbooks.AddressModel, javax.ws.rs.core.Response.Status)
*/
@Override
protected AddressModel put(
AddressModel model,
Status expectedStatus) {
return put(wc, adb.getId(), contact.getId(), model, expectedStatus);
}
/**
* Update a AddressModel on the AddressbooksService by executing a HTTP PUT method.
* @param webClient the web client representing the AddressbooksService
* @param aid the id of the addressbook
* @param cid the id of the contact
* @param model the new AddressModel data
* @param expectedStatus the expected HTTP status to test on
* @return the updated AddressModel object in JSON format
*/
public static AddressModel put(
WebClient webClient,
String aid,
String cid,
AddressModel model,
Status expectedStatus) {
webClient.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
Response _response = webClient.replacePath("/").path(aid).path(ServiceUtil.CONTACT_PATH_EL).path(cid).path(ServiceUtil.ADDRESS_PATH_EL).path(model.getId()).put(model);
if (expectedStatus != null) {
assertEquals("PUT should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
if (_response.getStatus() == Status.OK.getStatusCode()) {
return _response.readEntity(AddressModel.class);
} else {
return null;
}
}
/* (non-Javadoc)
* @see test.org.opentdc.addressbooks.AbstractAddressTest#delete(java.lang.String, javax.ws.rs.core.Response.Status)
*/
@Override
protected void delete(String id, Status expectedStatus) {
delete(wc, adb.getId(), contact.getId(), id, expectedStatus);
}
/**
* Delete the AddressModel with id on the AddressbooksService by executing a HTTP DELETE method.
* @param webClient the WebClient representing the AddressbooksService
* @param aid the id of the addressbook
* @param cid the id of the contact
* @param adrId the id of the AddressModel object to delete
* @param expectedStatus the expected HTTP status to test on
*/
public static void delete(
WebClient webClient,
String aid,
String cid,
String adrId,
Status expectedStatus) {
Response _response = webClient.replacePath("/").path(aid).path(ServiceUtil.CONTACT_PATH_EL).path(cid).path(ServiceUtil.ADDRESS_PATH_EL).path(adrId).delete();
if (expectedStatus != null) {
assertEquals("DELETE should return with correct status", expectedStatus.getStatusCode(), _response.getStatus());
}
}
}
| mit |
tempodb/tempodb-java | src/test/java/com/tempodb/CreateSeriesTest.java | 2816 | package com.tempodb;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.HashSet;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.junit.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.mockito.ArgumentCaptor;
public class CreateSeriesTest {
private static final String json = "{\"id\":\"id1\",\"key\":\"key1\",\"name\":\"name1\",\"tags\":[],\"attributes\":{}}";
private static final String body = "{\"key\":\"key1\",\"name\":\"name1\",\"tags\":[],\"attributes\":{}}";
private static final Series series = new Series("key1", "name1", new HashSet<String>(), new HashMap<String, String>());
private static final Series series1 = new Series("key1", "name1", new HashSet<String>(), new HashMap<String, String>());
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
@Test
public void smokeTest() throws IOException {
HttpResponse response = Util.getResponse(200, json);
Client client = Util.getClient(response);
Result<Series> result = client.createSeries(series);
assertEquals(series1, result.getValue());
}
@Test
public void testMethod() throws IOException {
HttpResponse response = Util.getResponse(200, json);
HttpClient mockClient = Util.getMockHttpClient(response);
Client client = Util.getClient(mockClient);
Result<Series> result = client.createSeries(series);
HttpRequest request = Util.captureRequest(mockClient);
assertEquals("POST", request.getRequestLine().getMethod());
}
@Test
public void testUri() throws IOException, URISyntaxException {
HttpResponse response = Util.getResponse(200, json);
HttpClient mockClient = Util.getMockHttpClient(response);
Client client = Util.getClient(mockClient);
Result<Series> result = client.createSeries(series);
HttpRequest request = Util.captureRequest(mockClient);
URI uri = new URI(request.getRequestLine().getUri());
assertEquals("/v1/series/", uri.getPath());
}
@Test
public void testBody() throws IOException {
HttpResponse response = Util.getResponse(200, json);
HttpClient mockClient = Util.getMockHttpClient(response);
Client client = Util.getClient(mockClient);
Result<Series> result = client.createSeries(series);
ArgumentCaptor<HttpPost> argument = ArgumentCaptor.forClass(HttpPost.class);
verify(mockClient).execute(any(HttpHost.class), argument.capture(), any(HttpContext.class));
assertEquals(body, EntityUtils.toString(argument.getValue().getEntity(), DEFAULT_CHARSET));
}
}
| mit |
villeteam/ville-standardutils | src/main/java/fi/utu/ville/standardutils/ui/VilleTextField.java | 560 | package fi.utu.ville.standardutils.ui;
import com.vaadin.data.Property;
import com.vaadin.ui.TextField;
@SuppressWarnings({ "rawtypes", "serial" })
public class VilleTextField extends TextField {
public VilleTextField(String caption) {
super(caption);
}
public VilleTextField(String caption, Property dataSource) {
super(caption, dataSource);
}
public VilleTextField(String caption, String value) {
super(caption, value);
}
public VilleTextField() {
super();
}
public VilleTextField(Property dataSource) {
super(dataSource);
}
}
| mit |
queckezz/bbb-resources | 120/addressbook/src/ch/bbbaden/m120/la3075/addressbook/PersonViewController.java | 1722 | /*
* 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 ch.bbbaden.m120.la3075.addressbook;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* @author fabia
*/
public class PersonViewController implements Initializable {
@FXML
private TextField firstNameInput;
@FXML
private TextField lastNameInput;
@FXML
private TextField plzInput;
private Person person;
private boolean committed;
private Stage stage;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void setStage(Stage stage) {
this.stage = stage;
}
public boolean isCommitted() {
return committed;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
firstNameInput.setText(person.getFirstName());
lastNameInput.setText(person.getLastName());
plzInput.setText(Integer.toString(person.getPlz()));
}
// called when the `ok` button is beeing clicked
@FXML
private void onOk(ActionEvent event) {
this.committed = true;
person.setFirstName(firstNameInput.getText());
person.setLastName(lastNameInput.getText());
person.setPlz(Integer.valueOf(plzInput.getText()));
stage.close();
}
@FXML
private void onCancel(ActionEvent event) {
this.committed = false;
stage.close();
}
}
| mit |
LeeYelim/wholeba_android | src/com/banana/banana/mission/scratch/MissionCardScratchActivity.java | 9067 | package com.banana.banana.mission.scratch;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.banana.banana.PropertyManager;
import com.banana.banana.R;
import com.banana.banana.love.NetworkManager;
import com.banana.banana.love.NetworkManager.OnResultListener;
import com.banana.banana.mission.BananaItemResponse;
import com.banana.banana.mission.MissionActivity;
import com.banana.banana.mission.MissionResult;
import com.winsontan520.WScratchView;
public class MissionCardScratchActivity extends ActionBarActivity {
private WScratchView scratchView;
private TextView percentageView;
private float mPercentage;
Button btn_ok,btn_chance,btn_ok2, btn_out, btn_cancel;
LinearLayout sView, hView;
ImageView lottoView;
int item_no,mlist_no,theme_no, chipCount, age;
String themeName, mission_name, mlist_regdate;
ImageView themeView;
TextView text_ThemeView,text_missionName, chip_countView;
private static final int[] ITEM_COIN_COUNT = { 1, 1, 2, 2, 2, 2, 2, 3};
private int resIds[] = {R.id.item1, R.id.item2, R.id.item3, R.id.item4, R.id.item5, R.id.item6, R.id.item7, R.id.item8};
TextView[] items = new TextView[resIds.length];
int selectedIndex = -1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission_card_scratch);
for (int i = 0; i < resIds.length;i++) {
items[i] = (TextView)findViewById(resIds[i]);
items[i].setTag((Integer)i);
}
Intent intent=getIntent();
mlist_no=intent.getIntExtra("mlist_no", 0);
mission_name=intent.getStringExtra("mission_name");
mlist_regdate=intent.getStringExtra("mlist_regdate");
theme_no=intent.getIntExtra("theme_no", 0);
item_no=-1;
themeView=(ImageView)findViewById(R.id.imageView1);
chip_countView=(TextView)findViewById(R.id.chip_count);
text_missionName=(TextView)findViewById(R.id.text_missionName);
text_missionName.setText(mission_name);
chipCount = PropertyManager.getInstance().getChipCount();
chip_countView.setText(""+chipCount+"개로 교환할 수 있는 아이템");
text_ThemeView=(TextView)findViewById(R.id.text_themeName);
sView=(LinearLayout)findViewById(R.id.scratchView);
btn_ok=(Button)findViewById(R.id.btn_ok);
btn_chance=(Button)findViewById(R.id.btn_chance);
btn_ok2=(Button)findViewById(R.id.btn_ok2);
scratchView = (WScratchView) findViewById(R.id.scratch_view);
hView=(LinearLayout)findViewById(R.id.itemView);
btn_cancel = (Button)findViewById(R.id.btn_cancel);
scratchView.setScratchable(true);
scratchView.setRevealSize(50);
scratchView.setAntiAlias(true);
scratchView.setScratchDrawable(getResources().getDrawable(R.drawable.mission_lotto_scratch));
scratchView.setBackgroundClickable(true);
lottoView=(ImageView)findViewById(R.id.imageView2);
setTheme();
item_no=2;
// add callback for update scratch percentage
scratchView.setOnScratchCallback(new WScratchView.OnScratchCallback() {
public void onScratch(float percentage) {
updatePercentage(percentage);
}
public void onDetach(boolean fingerDetach) {
if(mPercentage > 10){
scratchView.setScratchAll(true);
updatePercentage(100);
btn_ok.setVisibility(View.VISIBLE);
btn_chance.setVisibility(View.VISIBLE);
}
}
});
scratchView.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(MissionCardScratchActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
updatePercentage(0f);
btn_chance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text_ThemeView.setVisibility(View.GONE);
sView.setVisibility(View.GONE);//scratch view remove
hView.setVisibility(View.VISIBLE);
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btn_ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NetworkManager.getInstnace().confirmMission(MissionCardScratchActivity.this, mlist_no, new OnResultListener<MissionResult>() {
@Override
public void onSuccess(MissionResult result) {
if(result.success==1){
Toast.makeText(MissionCardScratchActivity.this, "미션 확인 완료", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MissionCardScratchActivity.this,MissionActivity.class);
finish();
startActivity(intent);
}
}
@Override
public void onFail(int code) {
// TODO Auto-generated method stub
}
});
}
});
btn_ok2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(item_no!=-1){
NetworkManager.getInstnace().confirmMission(MissionCardScratchActivity.this, mlist_no, new OnResultListener<MissionResult>() {
@Override
public void onSuccess(MissionResult result) {
if(result.success==1){
if(item_no!=9){
mission_name="";
}
Date today = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(today);
String item_usedate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(cal.getTime());
NetworkManager.getInstnace().useItem(MissionCardScratchActivity.this, item_usedate, selectedIndex+1 , mlist_no,mission_name, new OnResultListener<BananaItemResponse>() {
@Override
public void onSuccess(BananaItemResponse result) {
if(result.success==1){
Toast.makeText(MissionCardScratchActivity.this, "아이템 사용 완료", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MissionCardScratchActivity.this,MissionActivity.class);
finish();
startActivity(intent);
}
}
@Override
public void onFail(int code) {
if(code == 0) {
Toast.makeText(MissionCardScratchActivity.this, "아이템 사용 실패!", Toast.LENGTH_SHORT).show();
} else if (code == 1) {
Toast.makeText(MissionCardScratchActivity.this, "리워드 갯수 부족!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
@Override
public void onFail(int code) {
}
});
}
}
});
btn_out = (Button)findViewById(R.id.btn_out);
btn_out.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//*-----칩 갯수에 따라 아이템 색 변화-----*//
for (int i = 0; i < items.length; i++) {
if (chipCount >= ITEM_COIN_COUNT[i] ) {
items[i].setBackgroundResource(R.drawable.item_checked_selector);
} else {
items[i].setBackgroundResource(R.drawable.mission_item_select_bananachip_gray);
}
}
for (int i = 0; i < items.length; i++) {
items[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int index = (Integer)v.getTag();
if (chipCount >= ITEM_COIN_COUNT[index]) {
if (selectedIndex != -1) {
if (selectedIndex == index) {
items[index].setSelected(false);
selectedIndex = -1;
return;
} else {
items[selectedIndex].setSelected(false);
selectedIndex = -1;
}
}
items[index].setSelected(true);
selectedIndex = index;
}
}
});
}
}
public void setTheme()
{
if(theme_no==1)//악마
{ themeView.setImageResource(R.drawable.mission_devil_icon);
text_ThemeView.setText("악마미션");
}else if(theme_no==2){//처음
themeView.setImageResource(R.drawable.mission_fist_icon);
text_ThemeView.setText("처음미션");
}else if(theme_no==3){//섹시
themeView.setImageResource(R.drawable.mission_sexy_icon);
text_ThemeView.setText("섹시미션");
}else if(theme_no==4){//애교
themeView.setImageResource(R.drawable.mission_cute_icon);
text_ThemeView.setText("애교미션");
}else if(theme_no==5){//천사
themeView.setImageResource(R.drawable.mission_angel_icon);
text_ThemeView.setText("천사미션");
}
}
protected void updatePercentage(float percentage) {
mPercentage = percentage;
String percentage2decimal = String.format("%.2f", percentage) + " %";
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mission_card_scratch, menu);
return true;
}
}
| mit |
OfficeDev/O365-Android-ArtCurator | app/src/main/java/com/microsoft/artcurator/net/resolver/ServiceInfoLookup.java | 1904 | /*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See full license at the bottom of this file.
*/
package com.microsoft.artcurator.net.resolver;
import com.microsoft.discoveryservices.ServiceInfo;
import java.util.HashMap;
/**
* A container for instances of {@link ServiceInfo} - Services are retrievable by their capability
* name
*/
public class ServiceInfoLookup extends HashMap<String, ServiceInfo> {
public ServiceInfo getOutlookServiceInfo() {
return get("Mail");
}
}
// *********************************************************
//
// O365-Android-ArtCurator https://github.com/OfficeDev/O365-Android-ArtCurator
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ********************************************************* | mit |
dzlatkov/Fundamental-Level | Java Fundamentals/Java Collections Basics/LongestIncreasingSequence.java | 1446 | import java.util.ArrayList;
import java.util.Scanner;
public class LongestIncreasingSequence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] inputText = scanner.nextLine().split("\\s+");
ArrayList<String> maxList = new ArrayList<>();
ArrayList<String> currentList = new ArrayList<>();
for (int i = 0; i < inputText.length-1; i++) {
if(Integer.parseInt(inputText[i])<Integer.parseInt(inputText[i+1])){
currentList.add(inputText[i]);
if(i==inputText.length-2){
currentList.add(inputText[i+1]);
if (maxList.size() < currentList.size()) {
maxList = currentList;
}
System.out.println(String.join(" ", currentList));
}
}else {
currentList.add(inputText[i]);
if (maxList.size() < currentList.size()) {
maxList = new ArrayList<String>(currentList);
}
System.out.println(String.join(" ", currentList));
currentList.clear();
if (i == inputText.length-2){
System.out.println(inputText[i+1]);
}
}
}
System.out.println("Longest: " + String.join(" ",maxList));
}
}
| mit |
noranazmy/TLA2TeXConverter | src/tlc2/tool/Simulator.java | 13845 | // Copyright (c) 2003 Compaq Corporation. All rights reserved.
// Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved.
// Last modified on Mon 30 Apr 2007 at 15:29:56 PST by lamport
// modified on Thu Jan 10 11:22:26 PST 2002 by yuanyu
package tlc2.tool;
import java.io.PrintWriter;
import tla2sany.modanalyzer.SpecObj;
import tla2sany.semantic.SemanticNode;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.output.StatePrinter;
import tlc2.tool.liveness.LiveCheck1;
import tlc2.tool.liveness.LiveException;
import tlc2.util.ObjLongTable;
import tlc2.util.RandomGenerator;
import util.FileUtil;
import util.FilenameToStream;
public class Simulator implements Cancelable
{
/* Constructors */
/**
* SZ Feb 20, 2009: added the possibility to pass the SpecObject, this is compatibility constructor
* @deprecated use {@link Simulator#Simulator(String, String, String, boolean, int, long, RandomGenerator, long, boolean, FilenameToStream, SpecObj)} instead
* and pass the <code>null</code> as SpecObj
*/
public Simulator(String specFile, String configFile, String traceFile, boolean deadlock, int traceDepth,
long traceNum, RandomGenerator rng, long seed, boolean preprocess, FilenameToStream resolver)
{
this(specFile, configFile, traceFile, deadlock, traceDepth, traceNum, rng, seed, preprocess, resolver, null);
}
// SZ Feb 20, 2009: added the possibility to pass the SpecObject
public Simulator(String specFile, String configFile, String traceFile,
boolean deadlock, int traceDepth, long traceNum,
RandomGenerator rng, long seed, boolean preprocess, FilenameToStream resolver, SpecObj specObj) {
int lastSep = specFile.lastIndexOf(FileUtil.separatorChar);
String specDir = (lastSep == -1) ? "" : specFile.substring(0, lastSep+1);
specFile = specFile.substring(lastSep+1);
// SZ Feb 24, 2009: setup the user directory
// SZ Mar 5, 2009: removed it again because of the bug in simulator
// ToolIO.setUserDir(specDir);
this.tool = new Tool(specDir, specFile, configFile, resolver);
this.tool.init(preprocess, specObj); // parse and process the spec
this.checkDeadlock = deadlock;
this.checkLiveness = !this.tool.livenessIsTrue();
this.actions = this.tool.getActions();
this.invariants = this.tool.getInvariants();
this.impliedActions = this.tool.getImpliedActions();
this.numOfGenStates = 0;
if (traceDepth != -1) {
this.stateTrace = new TLCState[traceDepth];
// this.actionTrace = new Action[traceDepth]; // SZ: never read locally
this.traceDepth = traceDepth;
}
else {
this.stateTrace = new TLCState[0];
// this.actionTrace = new Action[0]; // SZ: never read locally
this.traceDepth = Long.MAX_VALUE;
}
this.traceFile = traceFile;
this.traceNum = traceNum;
this.rng = rng;
this.seed = seed;
this.aril = 0;
this.astCounts = new ObjLongTable(10);
// Initialization for liveness checking
if (this.checkLiveness) {
LiveCheck1.initSim(this.tool);
}
}
/* Fields */
private Tool tool;
private Action[] actions; // the sub actions
private Action[] invariants; // the invariants to be checked
private Action[] impliedActions; // the implied-actions to be checked
private boolean checkDeadlock; // check deadlock?
private boolean checkLiveness; // check liveness?
private long numOfGenStates;
private TLCState[] stateTrace;
// private Action[] actionTrace; // SZ: never read locally
private String traceFile;
private long traceDepth;
private long traceNum;
private RandomGenerator rng;
private long seed;
private long aril;
private ObjLongTable astCounts;
private boolean isCancelled; // SZ Feb 24, 2009: cancellation added
/*
* This method does simulation on a TLA+ spec. Its argument specifies
* the main module of the TLA+ spec.
*/
public void simulate() throws Exception {
StateVec theInitStates = null;
TLCState curState = null;
if (isCancelled)
{
return;
}
// Compute the initial states:
try {
theInitStates = this.tool.getInitStates();
this.numOfGenStates = theInitStates.size();
for (int i = 0; i < theInitStates.size(); i++) {
curState = theInitStates.elementAt(i);
if (this.tool.isGoodState(curState)) {
for (int j = 0; j < this.invariants.length; j++) {
if (!this.tool.isValid(this.invariants[j], curState)) {
// We get here because of invariant violation:
MP.printError(EC.TLC_INVARIANT_VIOLATED_INITIAL, new String[]{this.tool.getInvNames()[j], curState.toString()});
return;
}
}
}
else {
MP.printError(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_INITIAL, curState.toString());
return;
}
}
}
catch (Exception e) {
// Assert.printStack(e);
if (curState != null)
{
MP.printError(EC.TLC_INITIAL_STATE,
new String[] { (e.getMessage()==null)?e.toString():e.getMessage(), curState.toString() });
} else
{
MP.printError(EC.GENERAL, e); // LL changed call 7 April 2012
}
this.printSummary();
return;
}
if (this.numOfGenStates == 0) {
MP.printError(EC.TLC_NO_STATES_SATISFYING_INIT);
return;
}
theInitStates.deepNormalize();
// Start progress report thread:
ProgressReport report = new ProgressReport();
report.start();
// Start simulating:
int traceIdx = 0;
int idx = 0;
try {
for (int traceCnt = 1; traceCnt <= this.traceNum; traceCnt++) {
traceIdx = 0;
this.aril = rng.getAril();
curState = this.randomState(theInitStates);
boolean inConstraints = this.tool.isInModel(curState);
while (traceIdx < this.traceDepth) {
if (traceIdx < this.stateTrace.length) {
this.stateTrace[traceIdx] = curState;
traceIdx++;
}
if (!inConstraints) break;
StateVec nextStates = this.randomNextStates(curState);
if (nextStates == null) {
if (this.checkDeadlock) {
// We get here because of deadlock:
this.printBehavior(EC.TLC_DEADLOCK_REACHED, null, curState, traceIdx);
if (!TLCGlobals.continuation) { return; }
}
break;
}
for (int i = 0; i < nextStates.size(); i++) {
this.numOfGenStates++;
TLCState state = nextStates.elementAt(i);
if (TLCGlobals.coverageInterval >= 0) {
((TLCStateMutSource)state).addCounts(this.astCounts);
}
if (!this.tool.isGoodState(state)) {
this.printBehavior(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_NEXT, null, state, traceIdx);
return;
}
else {
try {
for (idx = 0; idx < this.invariants.length; idx++) {
if (!this.tool.isValid(this.invariants[idx], state)) {
// We get here because of invariant violation:
this.printBehavior(EC.TLC_INVARIANT_VIOLATED_BEHAVIOR, new String[]{this.tool.getInvNames()[idx]}, state, traceIdx);
if (!TLCGlobals.continuation) { return; }
}
}
}
catch (Exception e) {
// Assert.printStack(e);
this.printBehavior(EC.TLC_INVARIANT_EVALUATION_FAILED, new String[]{this.tool.getInvNames()[idx], e.getMessage()}, state, traceIdx);
return;
}
try {
for (idx = 0; idx < this.impliedActions.length; idx++) {
if (!this.tool.isValid(this.impliedActions[idx], curState, state)) {
// We get here because of implied-action violation:
this.printBehavior(EC.TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR, new String[]{this.tool.getImpliedActNames()[idx]}, state, traceIdx);
if (!TLCGlobals.continuation) { return; }
}
}
}
catch (Exception e) {
// Assert.printStack(e);
this.printBehavior(EC.TLC_ACTION_PROPERTY_EVALUATION_FAILED, new String[]{this.tool.getImpliedActNames()[idx], e.getMessage()}, state, traceIdx);
return;
}
}
}
TLCState s1 = this.randomState(nextStates);
inConstraints = (this.tool.isInModel(s1) &&
this.tool.isInActions(curState, s1));
curState = s1;
}
// Check if the current trace satisfies liveness properties.
if (this.checkLiveness) {
LiveCheck1.checkTrace(stateTrace, traceIdx);
}
// Write the trace out if desired. The trace is printed in the
// format of TLA module, so that it can be read by TLC again.
if (this.traceFile != null)
{
String fileName = this.traceFile + traceCnt;
// TODO is it ok here?
PrintWriter pw = new PrintWriter(FileUtil.newBFOS(fileName));
pw.println("---------------- MODULE " + fileName + " -----------------");
for (idx = 0; idx < traceIdx; idx++) {
pw.println("STATE_" + (idx+1) + " == ");
pw.println(this.stateTrace[idx] + "\n");
}
pw.println("=================================================");
pw.close();
}
}
}
catch (Throwable e) {
// Assert.printStack(e);
if (e instanceof LiveException)
{
this.printSummary();
} else {
// LL modified error message on 7 April 2012
this.printBehavior(EC.GENERAL,
new String[]{MP.ECGeneralMsg("", e)}, curState, traceIdx);
}
}
}
/**
* Prints out the simulation behavior, in case of an error.
* (unless we're at maximum depth, in which case don't!)
*/
public final void printBehavior(int errorCode, String[] parameters, TLCState state, int traceIdx)
{
MP.printError(errorCode, parameters);
if (this.traceDepth == Long.MAX_VALUE)
{
MP.printMessage(EC.TLC_ERROR_STATE);
StatePrinter.printState(state);
} else {
MP.printError(EC.TLC_BEHAVIOR_UP_TO_THIS_POINT);
TLCState lastState = null;
for (int i = 0; i < traceIdx; i++)
{
StatePrinter.printState(this.stateTrace[i], lastState, i+1);
lastState = this.stateTrace[i];
}
StatePrinter.printState(state, null, traceIdx+1);
}
this.printSummary();
}
/**
* This method returns a state that is randomly chosen from the set
* of states. It returns null if the set of states is empty.
*/
public final TLCState randomState(StateVec states) throws EvalException {
int len = states.size();
if (len > 0) {
int index = (int)Math.floor(this.rng.nextDouble() * len);
return states.elementAt(index);
}
return null;
}
/* (non-Javadoc)
* @see tlc2.tool.Cancelable#setCancelFlag(boolean)
*/
public void setCancelFlag(boolean flag)
{
this.isCancelled = flag;
}
/**
* This method returns the set of next states generated by a randomly
* chosen action. It returns null if there is no possible next state.
*/
public final StateVec randomNextStates(TLCState state) {
int len = this.actions.length;
int index = (int)Math.floor(this.rng.nextDouble() * len);
int p = this.rng.nextPrime();
for (int i = 0; i < len; i++) {
StateVec pstates = this.tool.getNextStates(this.actions[index], state);
if (!pstates.empty()) {
return pstates;
}
index = (index + p) % len;
}
return null;
}
/**
* Prints the summary
*/
public final void printSummary()
{
this.reportCoverage();
/*
* This allows the toolbox to easily display the last set
* of state space statistics by putting them in the same
* form as all other progress statistics.
*/
if (TLCGlobals.tool)
{
MP.printMessage(EC.TLC_PROGRESS_SIMU, String.valueOf(this.numOfGenStates));
}
MP.printMessage(EC.TLC_STATS_SIMU, new String[]{String.valueOf(this.numOfGenStates), String.valueOf(this.seed), String.valueOf(this.aril)});
}
/**
* Reports coverage
*/
public final void reportCoverage()
{
if (TLCGlobals.coverageInterval >= 0)
{
MP.printMessage(EC.TLC_COVERAGE_START);
ObjLongTable counts = this.tool.getPrimedLocs();
ObjLongTable.Enumerator keys = this.astCounts.keys();
Object key;
while ((key = keys.nextElement()) != null)
{
String loc = ((SemanticNode)key).getLocation().toString();
counts.add(loc, astCounts.get(key));
}
Object[] skeys = counts.sortStringKeys();
for (int i = 0; i < skeys.length; i++) {
long val = counts.get(skeys[i]);
MP.printMessage(EC.TLC_COVERAGE_VALUE, new String[]{skeys[i].toString(), String.valueOf(val)});
}
MP.printMessage(EC.TLC_COVERAGE_END);
}
}
/**
* Reports progress information
*/
final class ProgressReport extends Thread
{
public void run()
{
int count = TLCGlobals.coverageInterval/TLCGlobals.progressInterval;
try {
while (true)
{
synchronized(this)
{
this.wait(TLCGlobals.progressInterval);
}
MP.printMessage(EC.TLC_PROGRESS_SIMU, String.valueOf(numOfGenStates));
if (count > 1)
{
count--;
} else
{
reportCoverage();
count = TLCGlobals.coverageInterval/TLCGlobals.progressInterval;
}
}
}
catch (Exception e)
{
// SZ Jul 10, 2009: changed from error to bug
MP.printTLCBug(EC.TLC_REPORTER_DIED, null);
}
}
}
}
| mit |
rubenlagus/TelegramApi | src/main/java/org/telegram/bot/handlers/interfaces/IDifferencesHandler.java | 1084 | package org.telegram.bot.handlers.interfaces;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.telegram.api.updates.TLUpdatesState;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Differences handler interface
* @date 22 of March of 2016
*/
public interface IDifferencesHandler {
/**
* Load differences from server
*/
void getDifferences();
/**
* Modify updates state
* @param state New updates state
* @param isGettingDifferent true if differences are being loaded, false otherwise
*/
void updateStateModification(@NotNull TLUpdatesState state, boolean isGettingDifferent);
/**
* Load differences from server
*/
void getChannelDifferences(int chatId, long accessHash);
/**
* Modify updates state
* @param state New updates state
* @param isGettingDifferent true if differences are being loaded, false otherwise
*/
void updateChannelStateModification(int chatId, @Nullable Long accessHash, int pts, boolean isGettingDifferent);
}
| mit |
Achterhoeker/XChange | xchange-openexchangerates/src/main/java/com/xeiam/xchange/oer/service/polling/OERMarketDataService.java | 2465 | package com.xeiam.xchange.oer.service.polling;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.xeiam.xchange.ExchangeException;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.NotAvailableFromExchangeException;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trades;
import com.xeiam.xchange.oer.OERAdapters;
import com.xeiam.xchange.oer.dto.marketdata.OERRates;
import com.xeiam.xchange.service.polling.PollingMarketDataService;
/**
* @author timmolter
*/
public class OERMarketDataService extends OERMarketDataServiceRaw implements PollingMarketDataService {
/**
* Constructor
*
* @param exchangeSpecification The {@link ExchangeSpecification}
*/
public OERMarketDataService(ExchangeSpecification exchangeSpecification) {
super(exchangeSpecification);
}
@Override
public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {
OERRates rates = getOERTicker();
// Use reflection to get at data.
Method method = null;
try {
method = OERRates.class.getMethod("get" + currencyPair.baseSymbol, null);
} catch (SecurityException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
} catch (NoSuchMethodException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
}
Double exchangeRate = null;
try {
exchangeRate = (Double) method.invoke(rates, null);
} catch (IllegalArgumentException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
} catch (IllegalAccessException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
} catch (InvocationTargetException e) {
throw new ExchangeException("Problem getting exchange rate!", e);
}
// Adapt to XChange DTOs
return OERAdapters.adaptTicker(currencyPair, exchangeRate, cachedOERTickers.getTimestamp() * 1000L);
}
@Override
public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {
throw new NotAvailableFromExchangeException();
}
@Override
public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {
throw new NotAvailableFromExchangeException();
}
}
| mit |
coding4people/mosquito-report-api | src/test/java/com/coding4people/mosquitoreport/api/WithService.java | 804 | package com.coding4people.mosquitoreport.api;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Before;
import org.mockito.MockitoAnnotations;
abstract public class WithService implements BaseTest {
@Before
public void initialize() {
MockitoAnnotations.initMocks(this);
}
protected ResourceConfig configure() {
return new Config().configureFramework().register(new MockBinder(this));
}
protected <T> T getService(Class<T> clazz) {
return new ApplicationHandler(configure().register(new GenericBinder<T>() {
public Class<T> getType() {
return clazz;
}
})).getServiceLocator().getService(clazz);
}
}
| mit |
Sundays211/VirtueRS3 | src/main/java/org/virtue/game/entity/combat/impl/range/RangeAttackEvent.java | 2488 | package org.virtue.game.entity.combat.impl.range;
import org.virtue.Constants;
import org.virtue.game.World;
import org.virtue.game.entity.Entity;
import org.virtue.game.entity.combat.AttackEvent;
import org.virtue.game.entity.combat.AttackInfo;
import org.virtue.game.entity.combat.impl.AttackHandler;
import org.virtue.game.entity.combat.impl.FollowingType;
import org.virtue.game.entity.combat.impl.ImpactInfo;
import org.virtue.game.entity.player.Player;
import org.virtue.game.entity.player.inv.Item;
import org.virtue.game.map.GroundItem;
import org.virtue.game.map.square.MapSquare;
/**
* Handles range attack events.
* @author Emperor
*
*/
public class RangeAttackEvent extends AttackEvent {
/**
* The range attack handler.
*/
public static final AttackHandler HANDLER = new RangeAttackHandler();
/**
* Constructs a new {@code RangeAttackEvent} {@code Object}.
*/
public RangeAttackEvent() {
this(FollowingType.RANGE, HANDLER);
}
/**
* Constructs a new {@code RangeAttackEvent} {@code Object}.
* @param follower The following handler.
* @param handler The attack handler.
*/
public RangeAttackEvent(FollowingType follower, AttackHandler handler) {
super(follower, handler);
}
@Override
public boolean start(Entity entity, Entity lock, AttackInfo info) {
// TODO Auto-generated method stub
return true;
}
@Override
public void impact(Entity entity, AttackInfo info, ImpactInfo impact) {
if (entity instanceof Player) {
sendArrowDrop(entity, info, impact);
//impact.getVictim().getRegion().addItem(GroundItem.create(892, 1, impact.getVictim().getCurrentTile(), player));
}
}
@Override
public AttackEvent instantiate() {
return new RangeAttackEvent();
}
public static void sendArrowDrop(Entity entity, AttackInfo info, ImpactInfo impact) {
Player player = (Player) entity;
Item ammo = player.getEquipment().getWorn(13);
MapSquare region = World.getInstance().getRegions().getRegionByID(impact.getVictim().getCurrentTile().getRegionID());
if (region != null && region.isLoaded()) {
if(ammo == null) {
return;
}
int oldAmt = 0;
GroundItem oldItem = region.removeItem(impact.getVictim().getCurrentTile(), ammo.getId());
if (oldItem != null) {
oldAmt = oldItem.getAmount();
}
GroundItem groundItem = new GroundItem(ammo.getId(), oldAmt + 1, impact.getVictim().getCurrentTile());
groundItem.setSpawnTime(Constants.ITEM_REMOVAL_DELAY);
region.addItem(groundItem);
}
}
} | mit |
gems-uff/oceano | core/src/test/resources/maven-3-trunk/maven-embedder/src/main/java/org/apache/maven/cli/logging/Slf4jLogger.java | 3196 | package org.apache.maven.cli.logging;
/*
* 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.
*/
import org.codehaus.plexus.logging.Logger;
/**
* Adapt an SLF4J logger to a Plexus logger, ignoring Plexus logger API parts that are not classical and
* probably not really used.
*
* @author Jason van Zyl
*/
public class Slf4jLogger
implements Logger
{
private org.slf4j.Logger logger;
public Slf4jLogger( org.slf4j.Logger logger )
{
this.logger = logger;
}
public void debug( String message )
{
logger.debug( message );
}
public void debug( String message, Throwable throwable )
{
logger.debug( message, throwable );
}
public boolean isDebugEnabled()
{
return logger.isDebugEnabled();
}
public void info( String message )
{
logger.info( message );
}
public void info( String message, Throwable throwable )
{
logger.info( message, throwable );
}
public boolean isInfoEnabled()
{
return logger.isInfoEnabled();
}
public void warn( String message )
{
logger.warn( message );
}
public void warn( String message, Throwable throwable )
{
logger.warn( message, throwable );
}
public boolean isWarnEnabled()
{
return logger.isWarnEnabled();
}
public void error( String message )
{
logger.error( message );
}
public void error( String message, Throwable throwable )
{
logger.error( message, throwable );
}
public boolean isErrorEnabled()
{
return logger.isErrorEnabled();
}
public void fatalError( String message )
{
logger.error( message );
}
public void fatalError( String message, Throwable throwable )
{
logger.error( message, throwable );
}
public boolean isFatalErrorEnabled()
{
return logger.isErrorEnabled();
}
/**
* <b>Warning</b>: ignored (always return <code>0</code>).
*/
public int getThreshold()
{
return 0;
}
/**
* <b>Warning</b>: ignored.
*/
public void setThreshold( int threshold )
{
}
/**
* <b>Warning</b>: ignored (always return <code>0</code>).
*/
public Logger getChildLogger( String name )
{
return null;
}
public String getName()
{
return logger.getName();
}
}
| mit |
ERJIALI/gbdbas | src/main/java/com/paypal/api/payments/PayoutBatchHeader.java | 3669 | package com.paypal.api.payments;
import java.util.List;
import com.paypal.base.rest.PayPalModel;
public class PayoutBatchHeader extends PayPalModel {
/**
* An ID for the batch payout. Generated by PayPal. 30 characters max.
*/
private String payoutBatchId;
/**
* Generated batch status.
*/
private String batchStatus;
/**
* The time the batch entered processing.
*/
private String timeCreated;
/**
* The time that processing for the batch was completed.
*/
private String timeCompleted;
/**
* The original batch header as provided by the payment sender.
*/
private PayoutSenderBatchHeader senderBatchHeader;
/**
* Total amount, in U.S. dollars, requested for the applicable payouts.
*/
private Currency amount;
/**
* Total estimate in U.S. dollars for the applicable payouts fees.
*/
private Currency fees;
/**
*
*/
private Error errors;
/**
*
*/
private List<Links> links;
/**
* Default Constructor
*/
public PayoutBatchHeader() {
}
/**
* Parameterized Constructor
*/
public PayoutBatchHeader(String payoutBatchId, String batchStatus, String timeCreated, PayoutSenderBatchHeader senderBatchHeader, Currency amount, Currency fees) {
this.payoutBatchId = payoutBatchId;
this.batchStatus = batchStatus;
this.timeCreated = timeCreated;
this.senderBatchHeader = senderBatchHeader;
this.amount = amount;
this.fees = fees;
}
/**
* Setter for payoutBatchId
*/
public PayoutBatchHeader setPayoutBatchId(String payoutBatchId) {
this.payoutBatchId = payoutBatchId;
return this;
}
/**
* Getter for payoutBatchId
*/
public String getPayoutBatchId() {
return this.payoutBatchId;
}
/**
* Setter for batchStatus
*/
public PayoutBatchHeader setBatchStatus(String batchStatus) {
this.batchStatus = batchStatus;
return this;
}
/**
* Getter for batchStatus
*/
public String getBatchStatus() {
return this.batchStatus;
}
/**
* Setter for timeCreated
*/
public PayoutBatchHeader setTimeCreated(String timeCreated) {
this.timeCreated = timeCreated;
return this;
}
/**
* Getter for timeCreated
*/
public String getTimeCreated() {
return this.timeCreated;
}
/**
* Setter for timeCompleted
*/
public PayoutBatchHeader setTimeCompleted(String timeCompleted) {
this.timeCompleted = timeCompleted;
return this;
}
/**
* Getter for timeCompleted
*/
public String getTimeCompleted() {
return this.timeCompleted;
}
/**
* Setter for senderBatchHeader
*/
public PayoutBatchHeader setSenderBatchHeader(PayoutSenderBatchHeader senderBatchHeader) {
this.senderBatchHeader = senderBatchHeader;
return this;
}
/**
* Getter for senderBatchHeader
*/
public PayoutSenderBatchHeader getSenderBatchHeader() {
return this.senderBatchHeader;
}
/**
* Setter for amount
*/
public PayoutBatchHeader setAmount(Currency amount) {
this.amount = amount;
return this;
}
/**
* Getter for amount
*/
public Currency getAmount() {
return this.amount;
}
/**
* Setter for fees
*/
public PayoutBatchHeader setFees(Currency fees) {
this.fees = fees;
return this;
}
/**
* Getter for fees
*/
public Currency getFees() {
return this.fees;
}
/**
* Setter for errors
*/
public PayoutBatchHeader setErrors(Error errors) {
this.errors = errors;
return this;
}
/**
* Getter for errors
*/
public Error getErrors() {
return this.errors;
}
/**
* Setter for links
*/
public PayoutBatchHeader setLinks(List<Links> links) {
this.links = links;
return this;
}
/**
* Getter for links
*/
public List<Links> getLinks() {
return this.links;
}
}
| mit |
eity0323/aimanager | lib.photopick/src/main/java/uk/co/senab/photoview/gestures/CupcakeGestureDetector.java | 4983 | /*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* 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 uk.co.senab.photoview.gestures;
import android.content.Context;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
public class CupcakeGestureDetector implements GestureDetector {
protected OnGestureListener mListener;
private static final String LOG_TAG = "CupcakeGestureDetector";
float mLastTouchX;
float mLastTouchY;
final float mTouchSlop;
final float mMinimumVelocity;
@Override
public void setOnGestureListener(OnGestureListener listener) {
this.mListener = listener;
}
public CupcakeGestureDetector(Context context) {
final ViewConfiguration configuration = ViewConfiguration
.get(context);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mTouchSlop = configuration.getScaledTouchSlop();
}
private VelocityTracker mVelocityTracker;
private boolean mIsDragging;
float getActiveX(MotionEvent ev) {
return ev.getX();
}
float getActiveY(MotionEvent ev) {
return ev.getY();
}
public boolean isScaling() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
mVelocityTracker = VelocityTracker.obtain();
if (null != mVelocityTracker) {
mVelocityTracker.addMovement(ev);
} else {
Log.i(LOG_TAG, "Velocity tracker is null");
}
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
mIsDragging = false;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = getActiveX(ev);
final float y = getActiveY(ev);
final float dx = x - mLastTouchX, dy = y - mLastTouchY;
if (!mIsDragging) {
// Use Pythagoras to see if drag length is larger than
// touch slop
mIsDragging = Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
// mIsDragging = FloatMath.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
}
if (mIsDragging) {
mListener.onDrag(dx, dy);
mLastTouchX = x;
mLastTouchY = y;
if (null != mVelocityTracker) {
mVelocityTracker.addMovement(ev);
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
case MotionEvent.ACTION_UP: {
if (mIsDragging) {
if (null != mVelocityTracker) {
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
// Compute velocity within the last 1000ms
mVelocityTracker.addMovement(ev);
mVelocityTracker.computeCurrentVelocity(1000);
final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker
.getYVelocity();
// If the velocity is greater than minVelocity, call
// listener
if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) {
mListener.onFling(mLastTouchX, mLastTouchY, -vX,
-vY);
}
}
}
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
}
return true;
}
}
| mit |
pDiller/JiraAlerts | src/test/java/io/reflectoring/jiraalerts/dashboard/device/DeviceDetailsTableTest.java | 922 | package io.reflectoring.jiraalerts.dashboard.device;
import org.apache.wicket.markup.Markup;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import io.reflectoring.jiraalerts.application.testsetup.TestApplication;
@RunWith(MockitoJUnitRunner.class)
public class DeviceDetailsTableTest {
private static final long USER_ID = 4711;
@Mock
private DeviceService deviceServiceMock;
private WicketTester wicketTester;
@Before
public void setUp() throws Exception {
wicketTester = new WicketTester(new TestApplication(this));
wicketTester.startComponentInPage(new DeviceDetailsTable("table", USER_ID), Markup.of("<table wicket:id=table></table>"));
}
@Test
public void rendersSuccessfull() throws Exception {
wicketTester.assertNoErrorMessage();
}
}
| mit |
PSeminarKryptographie/MonkeyCrypt | src/crypt/Alpha_Bin.java | 317 | /**
*
*/
package crypt;
/**
* @author caterina
*
*/
public class Alpha_Bin extends Spielsprache{
@Override
public String encrypt(String text) {
// TODO Auto-generated method stub
return null;
}
@Override
public String decrypt(String text) {
// TODO Auto-generated method stub
return null;
}
}
| mit |
jacksarick/My-Code | Compiled/Java/DoodleJump/src/main/gamePanel.java | 1085 | package main;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
public class gamePanel extends JPanel implements KeyListener{
private int playerX = 10;
private int playerY = 10;
private float velocityX = 0;
private float velocityY = 0;
//default constructor
public gamePanel() {
this.setSize(800,600);
this.setVisible(true);
this.addKeyListener(this);
this.setFocusable(true);
}
@Override
public void paint(Graphics g){
playerX += velocityX;
playerY += velocityY;
velocityX *= .9;
velocityY += .09;
g.fillOval(playerX, playerY, 30, 30);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch(key){
case 37:
velocityX -= 1;
break;
case 39:
velocityX += 1;
break;
case 40:
velocityY -= 9;
break;
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
| mit |
flurdy/socialbeancrowd | src/main/java/com/flurdy/socialbeancrowd/model/RelativeTimeFormatter.java | 166 | package com.flurdy.socialbeancrowd.model;
import org.joda.time.DateTime;
public interface RelativeTimeFormatter {
public String format(DateTime timestamp);
}
| mit |
plumer/codana | tomcat_files/6.0.0/DynamicAttributes.java | 2019 | /*
* Copyright 2004 The Apache Software Foundation
*
* 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 javax.servlet.jsp.tagext;
import javax.servlet.jsp.JspException;
/**
* For a tag to declare that it accepts dynamic attributes, it must implement
* this interface. The entry for the tag in the Tag Library Descriptor must
* also be configured to indicate dynamic attributes are accepted.
* <br>
* For any attribute that is not declared in the Tag Library Descriptor for
* this tag, instead of getting an error at translation time, the
* <code>setDynamicAttribute()</code> method is called, with the name and
* value of the attribute. It is the responsibility of the tag to
* remember the names and values of the dynamic attributes.
*
* @since 2.0
*/
public interface DynamicAttributes {
/**
* Called when a tag declared to accept dynamic attributes is passed
* an attribute that is not declared in the Tag Library Descriptor.
*
* @param uri the namespace of the attribute, or null if in the default
* namespace.
* @param localName the name of the attribute being set.
* @param value the value of the attribute
* @throws JspException if the tag handler wishes to
* signal that it does not accept the given attribute. The
* container must not call doStartTag() or doTag() for this tag.
*/
public void setDynamicAttribute(
String uri, String localName, Object value )
throws JspException;
}
| mit |
notanuser/0chparser | src/com/nulchan/parsers/IParser.java | 710 | package com.nulchan.parsers;
import org.jsoup.nodes.Element;
import com.nulchan.exceptions.ParseException;
import com.nulchan.objects.PostEntity;
/**
* Предоставляет интерфейс для обработки сообщений.
*/
public interface IParser<T extends PostEntity> {
/**
* Преобразует передаваемый элемент {@link Element} в сообщение
* {@link PostEntity}.
*
* @param element
* элемент для парсинга.
* @return сообщение.
* @throws ParseException
* вызывается при ошибке парсинга.
*/
T parse(final Element element) throws ParseException;
}
| mit |
tbuschto/rap-punchy | bundles/com.eclipsesource.rap.punchy.ece13/src/com/eclipsesource/rap/punchy/ece13/Person.java | 1719 | /*******************************************************************************
* Copyright (c) 2013 EclipseSource 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:
* EclipseSource - initial API and implementation
******************************************************************************/
package com.eclipsesource.rap.punchy.ece13;
import org.eclipse.swt.graphics.Image;
public class Person {
private final String firstName;
private final String lastName;
private final Image image;
private final Person[] children;
private final String phone;
private final String mail;
public Person( String firstName, String lastName, Image image ) {
this( firstName, lastName, image, null, null, null );
}
public Person( String firstName, String lastName, Image image, String phone, String mail ) {
this( firstName, lastName, image, phone, mail, null );
}
public Person( String firstName, String lastName, Image image, String phone, String mail, Person[] children ) {
this.firstName = firstName;
this.lastName = lastName;
this.image = image;
this.phone = phone;
this.mail = mail;
this.children = children;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Image getImage() {
return image;
}
public String getPhone() {
return phone;
}
public String getMail() {
return mail;
}
public Person[] getChildren() {
return children;
}
}
| mit |
akapps/rest-toolkit | src/test/java/org/akapps/rest/integration/JsonIntegrationTest.java | 6681 | package org.akapps.rest.integration;
import org.akapps.rest.RestToolkitException;
import org.akapps.rest.annotation.AnnotationRest;
import org.akapps.rest.annotation.Server;
import org.akapps.rest.client.builder.PUT;
import org.akapps.rest.client.mime.JSon;
import org.akapps.rest.context.TestContext;
import org.akapps.rest.test.utils.RequestServlet;
import org.akapps.rest.test.utils.TestUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for JSon-based cases.
*
* @author Antoine Kapps
*/
public class JsonIntegrationTest {
@Server(resourceBase = "src/test/webapp-alternate-dir", webXml = "request-spy.xml")
private static TestContext context;
@BeforeClass
public static void initContext() {
AnnotationRest.initContext(JsonIntegrationTest.class);
}
@AfterClass
public static void closeContext() {
AnnotationRest.closeContext(JsonIntegrationTest.class);
}
@Test
public void testUse() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.use("{ foo: 'bar', bool: true, array: [1, 2, '3'] }")).sendAndWait();
final RequestServlet.RequestLog log = RequestServlet.requestLogForId(requestId);
assertThat(log.getContent()).as("Content received").isEqualTo("{ \"foo\": \"bar\", \"bool\": true, \"array\": [1, 2, \"3\"] }");
assertThat(log.getHeader("Content-Type")).as("Header [Content-Type]").isEqualTo("application/json;charset=UTF-8");
assertThat(log.getHeader("Content-Length")).as("Header [Content-Length]").isEqualTo("52");
}
/**
* Test the usage of a different charset for encoding data
*/
@Test
public void testUse_Charset() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.use("{ firstName: 'Jérôme', lastName: 'Lau' }", "ISO-8859-1")).sendAndWait();
final RequestServlet.RequestLog log = RequestServlet.requestLogForId(requestId);
assertThat(log.getContent()).as("Content received").isEqualTo("{ \"firstName\": \"Jérôme\", \"lastName\": \"Lau\" }");
assertThat(log.getContentEncoding()).as("Received encoding info").isEqualToIgnoringCase("ISO-8859-1");
assertThat(log.getHeader("Content-Type")).as("Header [Content-Type]").isEqualTo("application/json;charset=ISO-8859-1");
assertThat(log.getHeader("Content-Length")).as("Header [Content-Length]").isEqualTo("44");
}
/**
* Test that we can escape the JSON rewriter, for example to send bad-formatted content to the server.
*/
@Test
public void testUse_EscapeString() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.use("!{ foo: 'bar', format = wrong }")).sendAndWait();
assertThat(RequestServlet.requestLogForId(requestId).getContent()).as("Content received").isEqualTo("{ foo: 'bar', format = wrong }");
}
/**
* Test what happens if the given String is no correct JSON - and it is not escaped: Exception thrown !
*/
@Test(expected = RestToolkitException.class)
public void testUse_JsonParseException() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.use("<no json>")).sendAndWait();
}
/**
* Test {@link JSon#file(String)} - reading the JSON body from a file in classpath
*/
@Test
public void testFile_Classpath() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.file("classpath:/filereader-test/test.json")).sendAndWait();
assertThat(RequestServlet.requestLogForId(requestId).getContent()).as("Content received")
.isEqualTo("{ \"name\" : \"test.json\", \"size\" : 86, \"charset-test\": \"léouç\", \"multiline\" : true }");
}
/**
* Test {@link JSon#file(String)} - from classpath : if the file does not exist we wrap the exception in a {@code RestToolkitException}
*/
@Test(expected = RestToolkitException.class)
public void testFile_Classpath_FileNotFound() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.file("classpath:/foobar.json")).sendAndWait();
}
/**
* Test {@link JSon#file(String)} - reading the JSON body from an outer file
*/
@Test
public void testFile_Absolute() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId)
.body(JSon.file("src/test/test-files/json-integration.json")).sendAndWait();
assertThat(RequestServlet.requestLogForId(requestId).getContent()).as("Content received")
.isEqualTo("{ \"foo\" : \"bar\", \"arr\": [1, 2, { \"is\" : \"Object\" } ] }");
}
/**
* Test {@link JSon#property(String, String)} - reading the JSON body from a property file and the property key
*/
@Test
public void testProperty() {
String requestId = TestUtils.generateMethodName() + "#first";
PUT.target(context).param(RequestServlet.PARAM_ID, requestId)
.body(JSon.property("classpath:/integration/json-integration.properties", "json.first")).sendAndWait();
assertThat(RequestServlet.requestLogForId(requestId).getContent()).as("Content received").isEqualTo("{ \"foo\" : \"bar\", \"value\" : 1 }");
requestId = TestUtils.generateMethodName() + "#second";
PUT.target(context).param(RequestServlet.PARAM_ID, requestId)
.body(JSon.property("classpath:/integration/json-integration.properties", "json.other")).sendAndWait();
assertThat(RequestServlet.requestLogForId(requestId).getContent()).as("Content received").isEqualTo("{ \"firstName\" : \"Geralt\", \"prefession\" : \"Witcher\" }");
}
/**
* Test {@link JSon#property(String, String)} - FileNotFound wrapped into a {@code RestToolkitException}
*/
@Test(expected = RestToolkitException.class)
public void testProperty_FileNotFound() {
final String requestId = TestUtils.generateMethodName();
PUT.target(context).param(RequestServlet.PARAM_ID, requestId).body(JSon.property("classpath:/foobar.properties", "json.first")).sendAndWait();
}
}
| mit |
mrm1st3r/fh-newsboard | src/main/java/de/fhbielefeld/newsboard/model/access/AccessRole.java | 389 | package de.fhbielefeld.newsboard.model.access;
import de.fhbielefeld.newsboard.model.ValueObject;
/**
* An Access Role grants access to specific parts of the application.
*/
public class AccessRole implements ValueObject {
private final String role;
public AccessRole(String role) {
this.role = role;
}
public String getRole() {
return role;
}
}
| mit |
mcxtzhang/TJ-notes | src/com/mcxtzhang/algorithm/leetcode/array/Test448.java | 2188 | package com.mcxtzhang.algorithm.leetcode.array;
import java.util.LinkedList;
import java.util.List;
/**
* Intro:Find All Numbers Disappeared in an Array
* <p>
* Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
* <p>
* Find all the elements of [1, n] inclusive that do not appear in this array.
* <p>
* Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
* <p>
* Example:
* <p>
* Input:
* [4,3,2,7,8,2,3,1]
* <p>
* Output:
* [5,6]
* <p>
* <p>
* Author: zhangxutong
* E-mail: mcxtzhang@163.com
* Home Page: http://blog.csdn.net/zxt0601
* Created: 2017/10/13.
* History:
*/
public class Test448 {
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new LinkedList<>();
//解法1 用 on的空间
if(null == nums || nums.length <1) return result;
int len = nums.length;
int[] temp = new int[len];
for(int i=0;i<len;i++){
temp[nums[i]-1]=1;
}
for(int i=0;i<len;i++){
if(temp[i]!=1){
result.add((i+1));
}
}
return result;
}
}
class Solution2 {
public List<Integer> findDisappearedNumbers(int[] nums) {
List<Integer> result = new LinkedList<>();
//解法2 在原来的数组 将 元素放置在正确的位置上,再次遍历,如果位置不正确 就是空缺的
if(null == nums || nums.length <1) return result;
int len = nums.length;
for(int i=0;i<len;i++){
int val = nums[i];
while( nums[val-1] !=val ){
int temp = nums[val-1];
nums[val-1] = val;
val = temp;
}
}
for(int i=0;i<len;i++){
if(nums[i]!= i+1){
result.add(i+1);
}
}
return result;
}
}
}
| mit |
MrIbby/BalkonWeaponMod | src/main/java/ckathode/weaponmod/item/RangedCompFlintlock.java | 2932 | package ckathode.weaponmod.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import ckathode.weaponmod.ReloadHelper;
import ckathode.weaponmod.entity.projectile.EntityMusketBullet;
public class RangedCompFlintlock extends RangedComponent
{
public RangedCompFlintlock()
{
super(RangedSpecs.FLINTLOCK);
}
@Override
public void effectReloadDone(ItemStack itemstack, World world, EntityPlayer entityplayer)
{
entityplayer.swingItem();
world.playSoundAtEntity(entityplayer, "random.click", 1.0F, 1.0F / (weapon.getItemRand().nextFloat() * 0.4F + 0.8F));
}
@Override
public void fire(ItemStack itemstack, World world, EntityPlayer entityplayer, int i)
{
int j = getMaxItemUseDuration(itemstack) - i;
float f = j / 20F;
f = (f * f + f * 2F) / 3F;
if (f > 1F)
{
f = 1F;
}
f += 0.02F;
if (!world.isRemote)
{
EntityMusketBullet entitymusketbullet = new EntityMusketBullet(world, entityplayer, 4F / f);
applyProjectileEnchantments(entitymusketbullet, itemstack);
entitymusketbullet.setExtraDamage(entitymusketbullet.extraDamage - 10F);
world.spawnEntityInWorld(entitymusketbullet);
}
int damage = 1;
if (itemstack.getItemDamage() + damage <= itemstack.getMaxDamage())
{
setReloadState(itemstack, ReloadHelper.STATE_NONE);
}
itemstack.damageItem(damage, entityplayer);
postShootingEffects(itemstack, entityplayer, world);
}
@Override
public void effectPlayer(ItemStack itemstack, EntityPlayer entityplayer, World world)
{
float f = entityplayer.isSneaking() ? -0.05F : -0.1F;
double d = -MathHelper.sin((entityplayer.rotationYaw / 180F) * 3.141593F) * MathHelper.cos((0 / 180F) * 3.141593F) * f;
double d1 = MathHelper.cos((entityplayer.rotationYaw / 180F) * 3.141593F) * MathHelper.cos((0 / 180F) * 3.141593F) * f;
entityplayer.rotationPitch -= entityplayer.isSneaking() ? 7.5F : 15F;
entityplayer.addVelocity(d, 0, d1);
}
@Override
public void effectShoot(World world, double x, double y, double z, float yaw, float pitch)
{
world.playSoundEffect(x, y, z, "random.explode", 3F, 1F / (weapon.getItemRand().nextFloat() * 0.4F + 0.7F));
float particleX = -MathHelper.sin(((yaw + 23F) / 180F) * 3.141593F) * MathHelper.cos((pitch / 180F) * 3.141593F);
float particleY = -MathHelper.sin((pitch / 180F) * 3.141593F) + 1.6F;
float particleZ = MathHelper.cos(((yaw + 23F) / 180F) * 3.141593F) * MathHelper.cos((pitch / 180F) * 3.141593F);
for (int i = 0; i < 3; i++)
{
world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, x + particleX, y + particleY, z + particleZ, 0.0D, 0.0D, 0.0D);
}
world.spawnParticle(EnumParticleTypes.FLAME, x + particleX, y + particleY, z + particleZ, 0.0D, 0.0D, 0.0D);
}
@Override
public float getMaxZoom()
{
return 0.07f;
}
}
| mit |
AURIN/workbenchauth | src/main/java/au/aurin/org/io/DatasetAccessException.java | 826 | package au.aurin.org.io;
public class DatasetAccessException extends Exception {
private String userFriendlyMessage;
public DatasetAccessException() {
super();
}
public DatasetAccessException(final String message) {
super(message);
}
public DatasetAccessException(final String message,
final String userFriendlyMessage) {
super(message);
this.userFriendlyMessage = userFriendlyMessage;
}
public DatasetAccessException(final String message, final Throwable cause) {
super(message, cause);
}
public DatasetAccessException(final String message,
final String userFriendlyMessage, final Throwable cause) {
super(message, cause);
this.userFriendlyMessage = userFriendlyMessage;
}
public String getUserFriendlyMessage() {
return userFriendlyMessage;
}
}
| mit |
jaredlll08/ModTweaker | src/main/java/com/blamejared/compat/thermalexpansion/SawMill.java | 2671 | package com.blamejared.compat.thermalexpansion;
import cofh.thermalexpansion.util.managers.machine.SawmillManager;
import com.blamejared.ModTweaker;
import com.blamejared.mtlib.helpers.*;
import com.blamejared.mtlib.utils.BaseAction;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.annotations.*;
import crafttweaker.api.item.IItemStack;
import net.minecraft.item.ItemStack;
import stanhebben.zenscript.annotations.*;
@ZenClass("mods.thermalexpansion.Sawmill")
@ModOnly("thermalexpansion")
@ZenRegister
public class SawMill {
@ZenMethod
public static void addRecipe(IItemStack output, IItemStack input, int energy, @Optional IItemStack secondaryOutput, @Optional int secondaryChance) {
ModTweaker.LATE_ADDITIONS.add(new Add(InputHelper.toStack(output), InputHelper.toStack(input), energy, InputHelper.toStack(secondaryOutput), secondaryChance));
}
@ZenMethod
public static void removeRecipe(IItemStack input) {
ModTweaker.LATE_REMOVALS.add(new Remove(InputHelper.toStack(input)));
}
private static class Add extends BaseAction {
private ItemStack output, input, secondaryOutput;
private int energy, secondaryChance;
public Add(ItemStack output, ItemStack input, int energy, ItemStack secondaryOutput, int secondaryChance) {
super("Sawmill");
this.output = output;
this.input = input;
this.secondaryOutput = secondaryOutput;
this.energy = energy;
this.secondaryChance = secondaryChance;
if(!secondaryOutput.isEmpty() && secondaryChance <= 0) {
this.secondaryChance = 100;
}
}
@Override
public void apply() {
SawmillManager.addRecipe(energy, input, output, secondaryOutput, secondaryChance);
}
@Override
protected String getRecipeInfo() {
return LogHelper.getStackDescription(output);
}
}
private static class Remove extends BaseAction {
private ItemStack input;
public Remove(ItemStack input) {
super("Sawmill");
this.input = input;
}
@Override
public void apply() {
if(!SawmillManager.recipeExists(input)) {
CraftTweakerAPI.logError("No Sawmill recipe exists for: " + input);
return;
}
SawmillManager.removeRecipe(input);
}
@Override
protected String getRecipeInfo() {
return LogHelper.getStackDescription(input);
}
}
}
| mit |
bcroden/QuizDeck-Server | src/main/java/com/quizdeck/model/inputs/LabelUpdate.java | 334 | package com.quizdeck.model.inputs;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* Created by Cade on 2/23/2016.
*
* input object to add new labels to a quiz
*/
@Getter
@Setter
public class LabelUpdate {
private String userName;
private String quizTitle;
private List<String> labels;
}
| mit |
pivotal/sputnik | src/main/java/com/sputnik/persistence/User.java | 536 | package com.sputnik.persistence;
import javax.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private long id;
private String email;
private boolean admin;
public User(String email) {
this.email = email;
}
public User() {
}
public String getEmail() {
return email;
}
public long getId() {
return id;
}
public boolean getAdmin() {
return admin;
}
}
| mit |
drsirmrpresidentfathercharles/ls9-controller | src/tollertechnologies/ls9/Server.java | 1790 | package tollertechnologies.ls9;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import javax.sound.midi.MidiDevice.Info;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
public class Server {
static DatagramSocket socket;
static LS9 ls9;
static byte[] buffer;
static DatagramPacket packet;
public static void main(String[] args) {
System.out.println("Starting UDP reciever on port 3724...");
try {
socket = new DatagramSocket(3724);
} catch (SocketException e) {
System.out.println("Error creating socket. Please contact Charles Toller for assistance.");
System.exit(0);
}
System.out.println("MIDI Devices:");
Info[] info = MidiSystem.getMidiDeviceInfo();
for(int i = 0;i<info.length;i++) {
System.out.println(i+info[i].getName()+": "+info[i].getDescription());
}
String dev = System.console().readLine("Choose a device:");
try {
ls9 = new LS9(info[Integer.parseInt(dev)]);
} catch (NumberFormatException e) {
System.out.println("Type a number next time.");
System.exit(0);
} catch (MidiUnavailableException e) {
System.out.println("Somehow, you've managed to screw up the MIDI connection. Well done.");
System.exit(0);
}
try {
ls9.open();
} catch (NoLS9Exception e1) {
System.out.println("Wrong device.");
System.exit(0);
}
System.out.println("Ready for connections.");
while(true) {
buffer = new byte[65508];
packet = new DatagramPacket(buffer,buffer.length);
try {
socket.receive(packet);
} catch (IOException e) {
System.out.println("Something's gone wrong. Restart the application.");
}
Thread thread = new Thread(new Main(ls9,packet));
thread.start();
}
}
}
| mit |
AaricChen/qxcmp-framework | qxcmp-core/src/main/java/com/qxcmp/web/view/modules/dropdown/Dropdown.java | 1632 | package com.qxcmp.web.view.modules.dropdown;
import com.qxcmp.web.view.support.DropdownPointing;
import lombok.Getter;
import lombok.Setter;
/**
* 外表为按钮的下拉框
* <p>
* 用于在一般情况下使用
*
* @author Aaric
*/
@Getter
@Setter
public class Dropdown extends AbstractDropdown {
/**
* 是否为内敛显示
*/
private boolean inline;
/**
* 下拉框指向
*/
private DropdownPointing pointing = DropdownPointing.NONE;
/**
* 是否现在元素和下拉框之间的间距
*/
private boolean floating;
/**
* 下拉框菜单
*/
private DropdownMenu menu;
public Dropdown() {
}
public Dropdown(String text) {
super(text);
}
@Override
public String getFragmentName() {
return "dropdown";
}
@Override
public String getClassContent() {
final StringBuilder stringBuilder = new StringBuilder(super.getClassContent());
if (inline) {
stringBuilder.append(" inline");
}
if (floating) {
stringBuilder.append(" floating");
}
stringBuilder.append(pointing);
return stringBuilder.toString();
}
public Dropdown setMenu(DropdownMenu menu) {
this.menu = menu;
return this;
}
public Dropdown setInline() {
setInline(true);
return this;
}
public Dropdown setFloating() {
setFloating(true);
return this;
}
public Dropdown setPointing(DropdownPointing pointing) {
this.pointing = pointing;
return this;
}
}
| mit |
Alec-WAM/CrystalMod | src/main/java/alec_wam/CrystalMod/capability/PacketExtendedPlayerInvSync.java | 1937 | package alec_wam.CrystalMod.capability;
import alec_wam.CrystalMod.CrystalMod;
import alec_wam.CrystalMod.network.AbstractPacketThreadsafe;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.ByteBufUtils;
public class PacketExtendedPlayerInvSync extends AbstractPacketThreadsafe {
int playerId;
byte slot=0;
ItemStack stack;
public PacketExtendedPlayerInvSync(){}
public PacketExtendedPlayerInvSync(EntityPlayer player, int slot) {
ExtendedPlayer ePlayer = ExtendedPlayerProvider.getExtendedPlayer(player);
ExtendedPlayerInventory inv = ePlayer.getInventory();
this.slot = (byte) slot;
this.stack = inv.getStackInSlot(slot);
this.playerId = player.getEntityId();
inv.setChanged(slot, false);
}
@Override
public void fromBytes(ByteBuf buf) {
playerId = buf.readInt();
slot = buf.readByte();
stack = ByteBufUtils.readItemStack(buf);
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeInt(playerId);
buf.writeByte(slot);
ByteBufUtils.writeItemStack(buf, stack);
}
@Override
public void handleClientSafe(NetHandlerPlayClient netHandler) {
World world = CrystalMod.proxy.getClientWorld();
if(world !=null){
Entity entity = world.getEntityByID(playerId);
if(entity !=null && entity instanceof EntityPlayer){
EntityPlayer player = (EntityPlayer)entity;
ExtendedPlayer ePlayer = ExtendedPlayerProvider.getExtendedPlayer(player);
ExtendedPlayerInventory inv = ePlayer.getInventory();
inv.setStackInSlot(slot, stack);
}
}
}
@Override
public void handleServerSafe(NetHandlerPlayServer netHandler) {}
}
| mit |
robertzhang/JokeAndroidClient | commonlibs/src/main/java/cn/robertzhang/libraries/netstatus/NetStateReceiver.java | 4134 | package cn.robertzhang.libraries.netstatus;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import java.util.ArrayList;
import cn.robertzhang.libraries.utils.LogUtils;
import cn.robertzhang.libraries.utils.NetUtils;
/**
* Created by robertzhang on 16/1/20.
* email: robertzhangsh@gmail.com
*/
public class NetStateReceiver extends BroadcastReceiver{
public final static String CUSTOM_ANDROID_NET_CHANGE_ACTION = "com.custom.library.net.conn.CONNECTIVITY_CHANGE";
private final static String ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
private final static String TAG = NetStateReceiver.class.getSimpleName();
private static boolean isNetAvailable = false;
private static NetUtils.NetType mNetType;
private static ArrayList<NetChangeObserver> mNetChangeObservers = new ArrayList<NetChangeObserver>();
private static BroadcastReceiver mBroadcastReceiver;
private static BroadcastReceiver getReceiver() {
if (null == mBroadcastReceiver) {
synchronized (NetStateReceiver.class) {
if (null == mBroadcastReceiver) {
mBroadcastReceiver = new NetStateReceiver();
}
}
}
return mBroadcastReceiver;
}
@Override
public void onReceive(Context context, Intent intent) {
mBroadcastReceiver = NetStateReceiver.this;
if (intent.getAction().equalsIgnoreCase(ANDROID_NET_CHANGE_ACTION) || intent.getAction().equalsIgnoreCase(CUSTOM_ANDROID_NET_CHANGE_ACTION)) {
if (!NetUtils.isNetworkAvailable(context)) {
LogUtils.I(TAG, "<--- network disconnected --->");
isNetAvailable = false;
} else {
LogUtils.I(TAG, "<--- network connected --->");
isNetAvailable = true;
mNetType = NetUtils.getAPNType(context);
}
notifyObserver();
}
}
public static void registerNetworkStateReceiver(Context mContext) {
IntentFilter filter = new IntentFilter();
filter.addAction(CUSTOM_ANDROID_NET_CHANGE_ACTION);
filter.addAction(ANDROID_NET_CHANGE_ACTION);
mContext.getApplicationContext().registerReceiver(getReceiver(), filter);
}
public static void checkNetworkState(Context mContext) {
Intent intent = new Intent();
intent.setAction(CUSTOM_ANDROID_NET_CHANGE_ACTION);
mContext.sendBroadcast(intent);
}
public static void unRegisterNetworkStateReceiver(Context mContext) {
if (mBroadcastReceiver != null) {
try {
mContext.getApplicationContext().unregisterReceiver(mBroadcastReceiver);
} catch (Exception e) {
LogUtils.D(TAG, e.getMessage());
}
}
}
public static boolean isNetworkAvailable() {
return isNetAvailable;
}
public static NetUtils.NetType getAPNType() {
return mNetType;
}
private void notifyObserver() {
if (!mNetChangeObservers.isEmpty()) {
int size = mNetChangeObservers.size();
for (int i = 0; i < size; i++) {
NetChangeObserver observer = mNetChangeObservers.get(i);
if (observer != null) {
if (isNetworkAvailable()) {
observer.onNetConnected(mNetType);
} else {
observer.onNetDisConnect();
}
}
}
}
}
public static void registerObserver(NetChangeObserver observer) {
if (mNetChangeObservers == null) {
mNetChangeObservers = new ArrayList<NetChangeObserver>();
}
mNetChangeObservers.add(observer);
}
public static void removeRegisterObserver(NetChangeObserver observer) {
if (mNetChangeObservers != null) {
if (mNetChangeObservers.contains(observer)) {
mNetChangeObservers.remove(observer);
}
}
}
}
| mit |
bitmindco/bitmind-bdr | src/main/java/com/xmunch/bitmind/bdr/api/Microservice.java | 4003 | package com.xmunch.bitmind.bdr.api;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.UUID;
import javax.websocket.server.PathParam;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.blockcypher.context.BlockCypherContext;
import com.blockcypher.exception.BlockCypherException;
import com.blockcypher.model.address.Address;
import com.blockcypher.model.nulldata.NullData;
import com.blockcypher.model.transaction.summary.TransactionSummary;
import com.xmunch.bitmind.bdr.BitmindBdrUtils;
import com.xmunch.bitmind.bdr.BitmindBlockchainUtils;
@RestController
class MicroserviceJava extends BitmindBlockchainUtils {
private static final Logger logger = Logger.getLogger(MicroserviceJava.class);
private static final String BLOCKCHAIN_TRANSACTION_URL = "https://blockchain.info/tx/";
//TODO: Working in
@RequestMapping("/address/{name}")
public Address createAddress(@PathParam("name") String name) throws BlockCypherException {
Address address = blockCypherContext.getAddressService().createAddress();
logger.info(MessageFormat.format("Address {0} created for the organization "+name, address.getAddress()));
logger.info("Your wallet address is "+ address.getAddress());
logger.info("\n\nPublic key: "+address.getPublic());
logger.info("\n\nPrivate key: "+address.getPrivate());
return address;
}
//TODO: Working in
@RequestMapping("/address/{name}")
public String addInfoToTestnet(@PathParam("name") String name) throws BlockCypherException, UnsupportedEncodingException, NoSuchAlgorithmException {
BlockCypherContext context = new BlockCypherContext("v1", "btc", "test3", "YOURTOKEN");
String uuid = UUID.randomUUID().toString();
String organizationObject = "algo" + uuid;
byte[] bytesOfMessage = organizationObject.getBytes("UTF-8");
String digest1 = BitmindBdrUtils.createDigest(bytesOfMessage);
String digest2 = BitmindBdrUtils.createDigest(bytesOfMessage);
System.out.println("Obenetmos este digest: "+digest1 + " y "+ digest2);
NullData sentNullData = context.getTransactionService().sendNullData(new NullData(digest1, "string"));
System.out.println("Transaction hash of data UUID "+uuid+" embed: " + sentNullData.getHash());
System.out.println("Audit: https://www.blocktrail.com/tBTC/tx/" +sentNullData.getHash() );
//Y ahora otros metadatos
sentNullData = context.getTransactionService().sendNullData(new NullData("Bitmind.co Transactions Library Test1 bl", "string"));
System.out.println("Transaction hash of data UUID "+uuid+" embed: " + sentNullData.getHash());
System.out.println("Audit: https://www.blocktrail.com/tBTC/tx/" +sentNullData.getHash() );
return sentNullData.getHash();
}
//TODO: Working in
@RequestMapping("/check/{transactionAddress}")
public String checkTransactions(@PathParam("transacionAddress") String add) throws BlockCypherException{
Address address = blockCypherContext.getAddressService().getAddress("1JLg3M9H2xS4qbZEkRkvY8eeSDAVW1kho8"); //add
logger.info(MessageFormat.format("\nAddress {0} has the following transactions: ", address.getAddress()));
Collection<TransactionSummary> transactions = address.getTxrefs();
if(transactions != null && transactions.size() != 0){
for (TransactionSummary transaction : transactions) {
logger.info("\nHash:"+transaction.getTxHash());
logger.info("\nWay:"+ (transaction.isSpent() ? "Output" : "Input") );
logger.info("\nInspect:"+BLOCKCHAIN_TRANSACTION_URL+ transaction.getTxHash());
}
}
//TODO: Working in
return "...";
}
} | mit |
Blade-Annihilation/Blade-Annihilation | src/com/bladeannihilation/state/PauseState.java | 1183 | package com.bladeannihilation.state;
import java.awt.Color;
import java.awt.Graphics2D;
import com.bladeannihilation.keyboard.KeyBindings;
import com.bladeannihilation.main.GamePanel;
import com.bladeannihilation.main.Languages;
import com.bladeannihilation.main.Updatable;
public class PauseState implements Updatable {
//private GamePanel gp;
private Color black = new Color(0, 0, 0);
protected final float progressionMax = 25;
protected byte progression = 0;
public PauseState(GameStateManager gameStateManager) {
//this.gp = gp;
}
public void init() {
progression = 0;
}
@Override
public void draw(double time, Graphics2D g) {
if(progression < progressionMax) {
g.setColor(black);
g.fillRect(0, 0, GamePanel.WIDTH, (int)(GamePanel.HEIGHT*(((float)progression)/progressionMax)));
} else {
g.setColor(black);
g.fillRect(0, 0, GamePanel.WIDTH, GamePanel.HEIGHT);
}
g.setColor(Color.WHITE);
g.drawString(Languages.PAUSE, 5, 39);
}
@Override
public void update() {
if(progression < 100) {
progression++;
}
}
public void keyPressed(int keyCode) {
if(keyCode == KeyBindings.PAUSE) {
GamePanel.gameRunning = true;
}
}
}
| mit |
BujakiAttila/Sandbox | src/Sandbox/HelloWord/HelloWorld.java | 123 | package HelloWord;
public class HelloWorld {
public String getResult()
{
return "Hello World!";
}
}
| mit |
ezutil/dazzle | src/org/dazzle/utils/URLUtils.java | 5656 | package org.dazzle.utils;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import org.dazzle.common.exception.BaseException;
/**本软件为开源项目,最新项目发布于github,可提交您的代码到本开源软件,项目网址:<a href="https://github.com/ezutil/dazzle">https://github.com/ezutil/dazzle</a><br />
* 本软件内的大多数方法禁止Override,原因是作者提倡组合,而非继承,如果您确实需要用到继承,而又希望用本软件提供的方法名称与参数列表,建议您自行采用适配器设计模式,逐个用同名方法包裹本软件所提供的方法,这样您依然可以使用继承
* @see #get(Class, Map, String)
* @author hcqt@qq.com*/
public class URLUtils {
public static final String SCHEME_CLASSPATH = "classpath";
/**@author hcqt@qq.com*/
URLUtils(){ super(); };
/////////////
public static final URI resolveToURI(String uri) {
return resolve(uri);
}
/** @author hcqt@qq.com */
public static final URI resolveToURI(URI uri) {
return resolve(uri);
}
/** @author hcqt@qq.com */
public static final URI resolveToURI(final URL url) {
try {
return resolve(url.toURI());
} catch (URISyntaxException e) {
throw new org.dazzle.utils.URLUtils.URLException("URI_UTILS_RESOLVE_9nm3g", "URL“{0}”解析过程中发现语法错误,详情——{1}", e, url, e.getMessage());
}
}
/** @author hcqt@qq.com */
public static final URL resolveToURL(String uri) {
try {
return resolve(uri).toURL();
} catch (MalformedURLException e) {
throw new URLException("URI_UTILS_CONVERT_Om2Eh", "URL“{0}”解析过程中发现语法错误,详情——{1}", e, uri, e.getMessage());
}
}
/** @author hcqt@qq.com */
public static final URL resolveToURL(URL uri) {
return resolve(uri);
}
/** @author hcqt@qq.com */
public static final URL resolveToURL(URI uri) {
try {
return resolve(uri).toURL();
} catch (MalformedURLException e) {
throw new URLException("URI_UTILS_CONVERT_83jLm", "URL“{0}”解析过程中发现语法错误,详情——{1}", e, uri, e.getMessage());
}
}
/////////////
/**@see #resolve(URI)
* @author hcqt@qq.com */
public static final URL resolve(final URL url) {
try {
return resolveToURI(url).toURL();
} catch (MalformedURLException e) {
throw new URLException("URI_UTILS_CONVERT_8s3kW", "URL“{0}”解析过程中发现语法错误,详情——{1}", e, url, e.getMessage());
}
}
/**如果uri的协议头采用的是classpath,就把uri解析成绝对路径返回<br />
* 如果uri的协议头是其他则原样返回
* @author hcqt@qq.com */
public static final URI resolve(final URI uri) {
if(SCHEME_CLASSPATH.equalsIgnoreCase(uri.getScheme())) {
URL baseURL = NetUtils.class.getResource("/");
if(null == baseURL) {
throw new URLException("URI_UTILS_CLASSPATH_km3Ns", "无法获取程序的classpath路径");
}
URI baseURI;
try {
baseURI = baseURL.toURI();
} catch (URISyntaxException e) {
throw new URLException("URI_UTILS_CLASSPATH_i92nU", "解析URI“{0}”的时候,发现URI语法异常,详情——{1}", e, baseURL, e.getMessage());
}
String uriStr = uri.getSchemeSpecificPart();
for (int i = SU.indexOf(uriStr, "/", 1, true); i == 0; i = SU.indexOf(uriStr, "/", 1, true)) {
uriStr = SU.deletePrefix(uriStr, "/");
}
if(SU.subStringBefore(uriStr, "/") != null) {
String scheme = SU.subStringBefore(uriStr, "/");
if(scheme != null) {
scheme = scheme.trim();
if(scheme.endsWith(":")) {
throw new URLException("URI_UTILS_CLASSPATH_73jEm", "错误的classpath格式,不允许包含二级scheme“{0}”", scheme);
}
}
}
return baseURI.resolve(uriStr);
// return specialClasspathResolve(baseURI, uriStr);
}
return uri;
}
// private static final URI specialClasspathResolve(URI baseURI, String uri) {
// String scheme = SU.subStringBefore(uri, "/");
// if(scheme == null) {
// return baseURI.resolve(uri);
// }
// scheme = scheme.trim();
// if(!scheme.endsWith(":")) {// \ / : * ? " < > |
// return baseURI.resolve(uri);
// }
// return create("file:/"+uri);
// }
/**@see #create(String)
* @see #resolve(URI)
* @author hcqt@qq.com*/
public static final URI resolve(final String uri) {
return resolve(create(uri));
}
public static final URI create(
String scheme,
String userInfo,
String host,
int port,
String path,
String query,
String fragment) {
try {
return new URI(scheme, userInfo, host, port, path, query, fragment);
} catch (URISyntaxException e) {
throw new URLException("uri_utils_create_8L3MX", "创建URI失败,详情——{0}", e, e.getMessage());
}
}
/**JDK自带URI.create的升级,自动兼容空值以及转义“\”字符
* @see #resolve(URI)
* @author hcqt@qq.com */
public static final URI create(String uri) {
if(uri == null || uri.trim().isEmpty()) {
return null;
}
uri = uri.replace('\\', '/');
return URI.create(uri);
}
/** @author hcqt@qq.com */
public static class URLException extends BaseException {
private static final long serialVersionUID = -8507973954891579825L;
/** @author hcqt@qq.com */
public URLException() {
super();
}
/** @author hcqt@qq.com */
public URLException(String code, String message, Object... msgArg) {
super(code, message, msgArg);
}
/** @author hcqt@qq.com */
public URLException(String code, String message, Throwable cause, Object... msgArg) {
super(code, message, cause, msgArg);
}
}
}
| mit |
manuelp/diffing-refactoring | src/main/java/me/manuelp/diffingRefactoring/rendering/Renderable.java | 101 | package me.manuelp.diffingRefactoring.rendering;
public interface Renderable {
String render();
}
| mit |
MindscapeHQ/raygun4java | core/src/main/java/com/mindscapehq/raygun4java/core/messages/RaygunBreadcrumbMessage.java | 2211 | package com.mindscapehq.raygun4java.core.messages;
import java.util.Map;
import java.util.WeakHashMap;
public class RaygunBreadcrumbMessage {
private String message;
private String category;
private int level = RaygunBreadcrumbLevel.INFO.ordinal();
private String type = "Manual";
private Map<String, Object> customData = new WeakHashMap<String, Object>();
private Long timestamp = System.currentTimeMillis();
private String className;
private String methodName;
private Integer lineNumber;
public String getMessage() {
return message;
}
public RaygunBreadcrumbMessage withMessage(String message) {
this.message = message;
return this;
}
public String getCategory() {
return category;
}
public RaygunBreadcrumbMessage withCategory(String category) {
this.category = category;
return this;
}
public RaygunBreadcrumbLevel getLevel() {
return RaygunBreadcrumbLevel.values()[level];
}
public RaygunBreadcrumbMessage withLevel(RaygunBreadcrumbLevel level) {
this.level = level.ordinal();
return this;
}
public Map<String, Object> getCustomData() {
return customData;
}
public RaygunBreadcrumbMessage withCustomData(Map<String, Object> customData) {
this.customData = customData;
return this;
}
public Long getTimestamp() {
return timestamp;
}
public RaygunBreadcrumbMessage withTimestamp(Long timestamp) {
this.timestamp = timestamp;
return this;
}
public String getClassName() {
return className;
}
public RaygunBreadcrumbMessage withClassName(String className) {
this.className = className;
return this;
}
public String getMethodName() {
return methodName;
}
public RaygunBreadcrumbMessage withMethodName(String methodName) {
this.methodName = methodName;
return this;
}
public Integer getLineNumber() {
return lineNumber;
}
public RaygunBreadcrumbMessage withLineNumber(Integer lineNumber) {
this.lineNumber = lineNumber;
return this;
}
}
| mit |
AlexLandau/gdl-validation | src/main/java/net/alloyggp/griddle/validator/check/EmptyBodyCheck.java | 1633 | package net.alloyggp.griddle.validator.check;
import net.alloyggp.griddle.grammar.Function;
import net.alloyggp.griddle.grammar.GdlVisitor;
import net.alloyggp.griddle.grammar.Rule;
import net.alloyggp.griddle.grammar.Sentence;
import net.alloyggp.griddle.validator.AnalyzedGame;
public class EmptyBodyCheck implements Check {
public static final EmptyBodyCheck INSTANCE = new EmptyBodyCheck();
private EmptyBodyCheck() {
//Singleton
}
@Override
public void findProblems(AnalyzedGame game, final ProblemReporter reporter) {
game.visitAll(new GdlVisitor() {
@Override
public void visitSentence(Sentence sentence) {
if (sentence.getBodyNullable() != null && sentence.getBodyNullable().isEmpty()) {
reporter.report("Sentence with unnecessary parentheses; this may confuse some gamers.",
sentence.getPosition());
}
}
@Override
public void visitFunction(Function function) {
if (function.getBody().isEmpty()) {
reporter.report("Function with unnecessary parentheses; this may confuse some gamers.",
function.getPosition());
}
}
@Override
public void visitRule(Rule rule) {
if (rule.getConjuncts().isEmpty()) {
reporter.report("Rule with empty body; this can be written as a standalone sentence instead.",
rule.getPosition());
}
}
});
}
}
| mit |
lathspell/java_test | java_test_ee6_nbpfcrud/src/main/java/de/lathspell/java_test_ee6_nbpfcrud/jsf/admin/BookstoreFacade.java | 564 | package de.lathspell.java_test_ee6_nbpfcrud.jsf.admin;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import de.lathspell.java_test_ee6_nbpfcrud.model.Bookstore;
@Stateless
public class BookstoreFacade extends AbstractFacade<Bookstore> {
@PersistenceContext(unitName = "java_test_ee6_nbpfcrud_PU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public BookstoreFacade() {
super(Bookstore.class);
}
}
| cc0-1.0 |
MeasureAuthoringTool/clinical_quality_language | Src/java/cql-to-elm/src/main/java/org/cqframework/cql/cql2elm/Cql2ElmVisitor.java | 168088 | package org.cqframework.cql.cql2elm;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.misc.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.cqframework.cql.cql2elm.cqlModels.*;
import org.cqframework.cql.cql2elm.model.invocation.*;
import org.cqframework.cql.cql2elm.preprocessor.*;
import org.cqframework.cql.elm.tracking.*;
import org.cqframework.cql.gen.cqlBaseVisitor;
import org.cqframework.cql.gen.cqlLexer;
import org.cqframework.cql.gen.cqlParser;
import org.cqframework.cql.cql2elm.model.*;
import org.hl7.cql.model.*;
import org.hl7.cql_annotations.r1.Annotation;
import org.hl7.cql_annotations.r1.Narrative;
import org.hl7.elm.r1.*;
import org.hl7.elm.r1.Element;
import org.hl7.elm.r1.Interval;
import org.hl7.elm_modelinfo.r1.ModelInfo;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.List;
import java.util.jar.Pack200;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Cql2ElmVisitor extends cqlBaseVisitor {
private final ObjectFactory of = new ObjectFactory();
private final org.hl7.cql_annotations.r1.ObjectFactory af = new org.hl7.cql_annotations.r1.ObjectFactory();
private boolean annotate = false;
private boolean locate = false;
private boolean resultTypes = false;
private boolean dateRangeOptimization = false;
private boolean detailedErrors = false;
private boolean methodInvocation = true;
private TokenStream tokenStream;
private final LibraryBuilder libraryBuilder;
private final SystemMethodResolver systemMethodResolver;
Map<String, TrackBack> trackBackMap = new HashMap<>();
private LibraryInfo libraryInfo = null;
public void setLibraryInfo(LibraryInfo libraryInfo) {
if (libraryInfo == null) {
throw new IllegalArgumentException("libraryInfo is null");
}
this.libraryInfo = libraryInfo;
}
//Put them here for now, but eventually somewhere else?
private final Set<String> definedExpressionDefinitions = new HashSet<>();
private final Stack<ExpressionDefinitionInfo> forwards = new Stack<>();
private final Map<String, Set<Signature>> definedFunctionDefinitions = new HashMap<>();
private final Stack<FunctionDefinitionInfo> forwardFunctions = new Stack<>();
private final Stack<TimingOperatorContext> timingOperators = new Stack<>();
private Stack<Chunk> chunks = new Stack<>();
private String currentContext = "Patient"; // default context to patient
private int currentToken = -1;
private int nextLocalId = 1;
private final List<Retrieve> retrieves = new ArrayList<>();
private final List<Expression> expressions = new ArrayList<>();
private boolean implicitPatientCreated = false;
// For use in MAT Code. List of all of the model objects...
private List<CQLValueSetModelObject> cqlValueSetModelObjects = new ArrayList<>();
private List<CQLParameterModelObject> cqlParameterModelObjects = new ArrayList<>();
private List<CQLCodeModelObject> cqlCodeModelObjects = new ArrayList<>();
private List<CQLCodeSystemModelObject> cqlCodeSystemModelObjects = new ArrayList<>();
private List<CQLExpressionModelObject> cqlExpressionModelObjects = new ArrayList<>();
private List<CQLFunctionModelObject> cqlFunctionModelObjects = new ArrayList<>();
private List<CQLIncludeModelObject> cqlIncludeModelObjects = new ArrayList<>();
public Cql2ElmVisitor(LibraryBuilder libraryBuilder) {
super();
if (libraryBuilder == null) {
throw new IllegalArgumentException("libraryBuilder is null");
}
this.libraryBuilder = libraryBuilder;
this.systemMethodResolver = new SystemMethodResolver(this, libraryBuilder);
}
public void enableAnnotations() {
annotate = true;
}
public void disableAnnotations() {
annotate = false;
}
public void enableLocators() {
locate = true;
}
public void disableLocators() {
locate = false;
}
public void enableResultTypes() {
resultTypes = true;
}
public void disableResultTypes() {
resultTypes = false;
}
public void enableDateRangeOptimization() {
dateRangeOptimization = true;
}
public void disableDateRangeOptimization() {
dateRangeOptimization = false;
}
public boolean getDateRangeOptimization() {
return dateRangeOptimization;
}
public void enableDetailedErrors() {
detailedErrors = true;
}
public void disableDetailedErrors() {
detailedErrors = false;
}
public boolean isDetailedErrorsEnabled() {
return detailedErrors;
}
public void enableMethodInvocation() {
methodInvocation = true;
}
public void disableMethodInvocation() {
methodInvocation = false;
}
public TokenStream getTokenStream() {
return tokenStream;
}
public void setTokenStream(TokenStream value) {
tokenStream = value;
}
public List<Retrieve> getRetrieves() {
return retrieves;
}
public List<Expression> getExpressions() {
return expressions;
}
private int getNextLocalId() {
return nextLocalId++;
}
private void pushChunk(@NotNull ParseTree tree) {
org.antlr.v4.runtime.misc.Interval sourceInterval = tree.getSourceInterval();
Chunk chunk = new Chunk().withInterval(sourceInterval);
chunks.push(chunk);
}
private void popChunk(@NotNull ParseTree tree, Object o) {
Chunk chunk = chunks.pop();
if (o instanceof Element) {
Element element = (Element)o;
if (element.getLocalId() == null) {
element.setLocalId(Integer.toString(getNextLocalId()));
}
chunk.setElement(element);
if (element instanceof ExpressionDef && !(tree instanceof cqlParser.LibraryContext)) {
ExpressionDef expressionDef = (ExpressionDef)element;
if (expressionDef.getAnnotation().size() == 0) {
expressionDef.getAnnotation().add(buildAnnotation(chunk));
}
}
}
if (!chunks.isEmpty()) {
chunks.peek().addChunk(chunk);
}
}
private Annotation buildAnnotation(Chunk chunk) {
Annotation annotation = af.createAnnotation();
annotation.setS(buildNarrative(chunk));
return annotation;
}
private Narrative buildNarrative(Chunk chunk) {
Narrative narrative = af.createNarrative();
if (chunk.getElement() != null) {
narrative.setR(chunk.getElement().getLocalId());
}
if (chunk.hasChunks()) {
Narrative currentNarrative = null;
for (Chunk childChunk : chunk.getChunks()) {
Narrative chunkNarrative = buildNarrative(childChunk);
if (hasChunks(chunkNarrative)) {
if (currentNarrative != null) {
narrative.getContent().add(wrapNarrative(currentNarrative));
currentNarrative = null;
}
narrative.getContent().add(wrapNarrative(chunkNarrative));
}
else {
if (currentNarrative == null) {
currentNarrative = chunkNarrative;
}
else {
currentNarrative.getContent().addAll(chunkNarrative.getContent());
}
}
}
if (currentNarrative != null) {
narrative.getContent().add(wrapNarrative(currentNarrative));
}
}
else {
narrative.getContent().add(tokenStream.getText(chunk.getInterval()));
}
return narrative;
}
private boolean hasChunks(Narrative narrative) {
for (Serializable c : narrative.getContent()) {
if (!(c instanceof String)) {
return true;
}
}
return false;
}
private Serializable wrapNarrative(Narrative narrative) {
return new JAXBElement<>(
new QName("urn:hl7-org:cql-annotations:r1", "s"),
Narrative.class,
narrative);
}
@Override
public Object visit(@NotNull ParseTree tree) {
if (annotate) {
pushChunk(tree);
}
Object o = null;
try {
try {
o = super.visit(tree);
} catch (CqlTranslatorIncludeException e) {
libraryBuilder.recordParsingException(new CqlTranslatorException(e.getMessage(), getTrackBack(tree), e));
} catch (CqlTranslatorException e) {
libraryBuilder.recordParsingException(e);
} catch (Exception e) {
CqlTranslatorException ex = null;
if (e.getMessage() == null) {
ex = new CqlInternalException("Internal translator error.", getTrackBack(tree), e);
}
else {
ex = new CqlSemanticException(e.getMessage(), getTrackBack(tree), e);
}
Exception rootCause = libraryBuilder.determineRootCause();
if (rootCause == null) {
rootCause = ex;
libraryBuilder.recordParsingException(ex);
libraryBuilder.setRootCause(rootCause);
}
else {
if (detailedErrors) {
libraryBuilder.recordParsingException(ex);
}
}
o = of.createNull();
}
if (o instanceof Trackable && !(tree instanceof cqlParser.LibraryContext)) {
this.track((Trackable) o, tree);
}
if (o instanceof Expression) {
addExpression((Expression) o);
}
return o;
} finally {
if (annotate) {
popChunk(tree, o);
}
}
}
@Override
public Object visitLibrary(@NotNull cqlParser.LibraryContext ctx) {
Object lastResult = null;
// NOTE: Need to set the library identifier here so the builder can begin the translation appropriately
libraryBuilder.setLibraryIdentifier(new VersionedIdentifier().withId(libraryInfo.getLibraryName()).withVersion(libraryInfo.getVersion()));
libraryBuilder.beginTranslation();
try {
// Loop through and call visit on each child (to ensure they are tracked)
for (int i = 0; i < ctx.getChildCount(); i++) {
lastResult = visit(ctx.getChild(i));
}
// Return last result (consistent with super implementation and helps w/ testing)
return lastResult;
}
finally {
libraryBuilder.endTranslation();
}
}
@Override
public VersionedIdentifier visitLibraryDefinition(@NotNull cqlParser.LibraryDefinitionContext ctx) {
VersionedIdentifier vid = of.createVersionedIdentifier()
.withId(parseString(ctx.identifier()))
.withVersion(parseString(ctx.versionSpecifier()));
libraryBuilder.setLibraryIdentifier(vid);
return vid;
}
@Override
public UsingDef visitUsingDefinition(@NotNull cqlParser.UsingDefinitionContext ctx) {
Model model = getModel(parseString(ctx.modelIdentifier()), parseString(ctx.versionSpecifier()));
return libraryBuilder.resolveUsingRef(model.getModelInfo().getName());
}
public Model getModel() {
return getModel((String)null);
}
public Model getModel(String modelName) {
return getModel(modelName, null);
}
public Model getModel(String modelName, String version) {
if (modelName == null) {
UsingDefinitionInfo defaultUsing = libraryInfo.getDefaultUsingDefinition();
modelName = defaultUsing.getName();
version = defaultUsing.getVersion();
}
VersionedIdentifier modelIdentifier = new VersionedIdentifier().withId(modelName).withVersion(version);
return libraryBuilder.getModel(modelIdentifier);
}
@Override
public Object visitIncludeDefinition(@NotNull cqlParser.IncludeDefinitionContext ctx) {
String identifier = parseString(ctx.identifier());
IncludeDef library = of.createIncludeDef()
.withLocalIdentifier(ctx.localIdentifier() == null ? identifier : parseString(ctx.localIdentifier()))
.withPath(identifier)
.withVersion(parseString(ctx.versionSpecifier()));
libraryBuilder.addInclude(library);
return library;
}
@Override
public ParameterDef visitParameterDefinition(@NotNull cqlParser.ParameterDefinitionContext ctx) {
this.trackBackMap.put(parseString(ctx.identifier()), getTrackBack(ctx));
ParameterDef param = of.createParameterDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(parseString(ctx.identifier()))
.withDefault(parseExpression(ctx.expression()))
.withParameterTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier()));
DataType paramType = null;
if (param.getParameterTypeSpecifier() != null) {
paramType = param.getParameterTypeSpecifier().getResultType();
}
if (param.getDefault() != null) {
if (paramType != null) {
libraryBuilder.verifyType(param.getDefault().getResultType(), paramType);
}
else {
paramType = param.getDefault().getResultType();
}
}
if (paramType == null) {
throw new IllegalArgumentException(String.format("Could not determine parameter type for parameter %s.", param.getName()));
}
param.setResultType(paramType);
if (param.getDefault() != null) {
param.setDefault(libraryBuilder.ensureCompatible(param.getDefault(), paramType));
}
libraryBuilder.addParameter(param);
// for use in MAT code. Holds all of the important information about the paramter
List<String> tokens = new ArrayList<>();
tokenize(tokens, ctx);
CQLParameterModelObject cqlParameterModelObject = new CQLParameterModelObject(ctx.identifier().getText(), tokens, param);
this.cqlParameterModelObjects.add(cqlParameterModelObject);
return param;
}
@Override
public NamedTypeSpecifier visitNamedTypeSpecifier(@NotNull cqlParser.NamedTypeSpecifierContext ctx) {
DataType resultType = libraryBuilder.resolveTypeName(parseString(ctx.modelIdentifier()), parseString(ctx.identifier()));
NamedTypeSpecifier result = of.createNamedTypeSpecifier()
.withName(libraryBuilder.dataTypeToQName(resultType));
// Fluent API would be nice here, but resultType isn't part of the model so...
result.setResultType(resultType);
return result;
}
@Override
public TupleElementDefinition visitTupleElementDefinition(@NotNull cqlParser.TupleElementDefinitionContext ctx) {
TupleElementDefinition result = of.createTupleElementDefinition()
.withName(parseString(ctx.identifier()))
.withType(parseTypeSpecifier(ctx.typeSpecifier()));
return result;
}
@Override
public Object visitTupleTypeSpecifier(@NotNull cqlParser.TupleTypeSpecifierContext ctx) {
TupleType resultType = new TupleType();
TupleTypeSpecifier typeSpecifier = of.createTupleTypeSpecifier();
for (cqlParser.TupleElementDefinitionContext definitionContext : ctx.tupleElementDefinition()) {
TupleElementDefinition element = (TupleElementDefinition)visit(definitionContext);
resultType.addElement(new TupleTypeElement(element.getName(), element.getType().getResultType()));
typeSpecifier.getElement().add(element);
}
typeSpecifier.setResultType(resultType);
return typeSpecifier;
}
@Override
public ChoiceTypeSpecifier visitChoiceTypeSpecifier(@NotNull cqlParser.ChoiceTypeSpecifierContext ctx) {
ArrayList<TypeSpecifier> typeSpecifiers = new ArrayList<TypeSpecifier>();
ArrayList<DataType> types = new ArrayList<DataType>();
for (cqlParser.TypeSpecifierContext typeSpecifierContext : ctx.typeSpecifier()) {
TypeSpecifier typeSpecifier = parseTypeSpecifier(typeSpecifierContext);
typeSpecifiers.add(typeSpecifier);
types.add(typeSpecifier.getResultType());
}
ChoiceTypeSpecifier result = of.createChoiceTypeSpecifier().withType(typeSpecifiers);
ChoiceType choiceType = new ChoiceType(types);
result.setResultType(choiceType);
return result;
}
@Override
public IntervalTypeSpecifier visitIntervalTypeSpecifier(@NotNull cqlParser.IntervalTypeSpecifierContext ctx) {
IntervalTypeSpecifier result = of.createIntervalTypeSpecifier().withPointType(parseTypeSpecifier(ctx.typeSpecifier()));
IntervalType intervalType = new IntervalType(result.getPointType().getResultType());
result.setResultType(intervalType);
return result;
}
@Override
public ListTypeSpecifier visitListTypeSpecifier(@NotNull cqlParser.ListTypeSpecifierContext ctx) {
ListTypeSpecifier result = of.createListTypeSpecifier().withElementType(parseTypeSpecifier(ctx.typeSpecifier()));
ListType listType = new ListType(result.getElementType().getResultType());
result.setResultType(listType);
return result;
}
@Override
public AccessModifier visitAccessModifier(@NotNull cqlParser.AccessModifierContext ctx) {
switch (ctx.getText().toLowerCase()) {
case "public" : return AccessModifier.PUBLIC;
case "private" : return AccessModifier.PRIVATE;
default: throw new IllegalArgumentException(String.format("Unknown access modifier %s.", ctx.getText().toLowerCase()));
}
}
@Override
public CodeSystemDef visitCodesystemDefinition(@NotNull cqlParser.CodesystemDefinitionContext ctx) {
CodeSystemDef cs = (CodeSystemDef)of.createCodeSystemDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(parseString(ctx.identifier()))
.withId(parseString(ctx.codesystemId()))
.withVersion(parseString(ctx.versionSpecifier()))
.withResultType(new ListType(libraryBuilder.resolveTypeName("System", "Code")));
libraryBuilder.addCodeSystem(cs);
// for use in mat code.. holds all of the important information about a code
List<String> tokens = new ArrayList<>();
for(int i = 0; i < ctx.getChildCount(); i++) {
tokens.add(ctx.getChild(i).getText());
}
CQLCodeSystemModelObject cqlCodeSystemModelObject = new CQLCodeSystemModelObject(ctx.identifier().getText(), tokens, cs);
this.cqlCodeSystemModelObjects.add(cqlCodeSystemModelObject);
return cs;
}
@Override
public CodeSystemRef visitCodesystemIdentifier(@NotNull cqlParser.CodesystemIdentifierContext ctx) {
String libraryName = parseString(ctx.libraryIdentifier());
String name = parseString(ctx.identifier());
CodeSystemDef def;
if (libraryName != null) {
def = libraryBuilder.resolveLibrary(libraryName).resolveCodeSystemRef(name);
libraryBuilder.checkAccessLevel(libraryName, name, def.getAccessLevel());
}
else {
def = libraryBuilder.resolveCodeSystemRef(name);
}
if (def == null) {
throw new IllegalArgumentException(String.format("Could not resolve reference to code system %s.", name));
}
return (CodeSystemRef)of.createCodeSystemRef()
.withLibraryName(libraryName)
.withName(name)
.withResultType(def.getResultType());
}
@Override
public CodeRef visitCodeIdentifier(@NotNull cqlParser.CodeIdentifierContext ctx) {
String libraryName = parseString(ctx.libraryIdentifier());
String name = parseString(ctx.identifier());
CodeDef def;
if (libraryName != null) {
def = libraryBuilder.resolveLibrary(libraryName).resolveCodeRef(name);
libraryBuilder.checkAccessLevel(libraryName, name, def.getAccessLevel());
}
else {
def = libraryBuilder.resolveCodeRef(name);
}
if (def == null) {
throw new IllegalArgumentException(String.format("Could not resolve reference to code %s.", name));
}
return (CodeRef)of.createCodeRef()
.withLibraryName(libraryName)
.withName(name)
.withResultType(def.getResultType());
}
@Override
public ValueSetDef visitValuesetDefinition(@NotNull cqlParser.ValuesetDefinitionContext ctx) {
ValueSetDef vs = of.createValueSetDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(parseString(ctx.identifier()))
.withId(parseString(ctx.valuesetId()))
.withVersion(parseString(ctx.versionSpecifier()));
if (ctx.codesystems() != null) {
for (cqlParser.CodesystemIdentifierContext codesystem : ctx.codesystems().codesystemIdentifier()) {
vs.getCodeSystem().add((CodeSystemRef)visit(codesystem));
}
}
vs.setResultType(new ListType(libraryBuilder.resolveTypeName("System", "Code")));
libraryBuilder.addValueSet(vs);
// use in MAT Code. Creates a Valueset Model Object which holds important information.
List<String> tokens = new ArrayList<>();
for(int i = 0; i < ctx.getChildCount(); i++) {
tokens.add(ctx.getChild(i).getText());
}
CQLValueSetModelObject cqlValueSetModelObject = new CQLValueSetModelObject(ctx.identifier().getText(), tokens, vs);
this.cqlValueSetModelObjects.add(cqlValueSetModelObject);
return vs;
}
@Override
public CodeDef visitCodeDefinition(@NotNull cqlParser.CodeDefinitionContext ctx) {
CodeDef cd = of.createCodeDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(parseString(ctx.identifier()))
.withId(parseString(ctx.codeId()));
if (ctx.codesystemIdentifier() != null) {
cd.setCodeSystem((CodeSystemRef)visit(ctx.codesystemIdentifier()));
}
if (ctx.displayClause() != null) {
cd.setDisplay(parseString(ctx.displayClause().STRING()));
}
cd.setResultType(libraryBuilder.resolveTypeName("Code"));
libraryBuilder.addCode(cd);
// for use in MAT code... holds all of the important information about a code.
List<String> tokens = new ArrayList<>();
for(int i = 0; i < ctx.getChildCount(); i++) {
tokens.add(ctx.getChild(i).getText());
}
CQLCodeModelObject cqlCodeModelObject = new CQLCodeModelObject(ctx.identifier().getText(), tokens, cd);
this.cqlCodeModelObjects.add(cqlCodeModelObject);
return cd;
}
@Override
public ConceptDef visitConceptDefinition(@NotNull cqlParser.ConceptDefinitionContext ctx) {
ConceptDef cd = of.createConceptDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(parseString(ctx.identifier()));
if (ctx.codeIdentifier() != null) {
for (cqlParser.CodeIdentifierContext ci : ctx.codeIdentifier()) {
cd.getCode().add((CodeRef)visit(ci));
}
}
if (ctx.displayClause() != null) {
cd.setDisplay(parseString(ctx.displayClause().STRING()));
}
cd.setResultType(libraryBuilder.resolveTypeName("Concept"));
libraryBuilder.addConcept(cd);
return cd;
}
@Override
public Object visitContextDefinition(@NotNull cqlParser.ContextDefinitionContext ctx) {
currentContext = parseString(ctx.identifier());
if (!(currentContext.equals("Patient") || currentContext.equals("Population"))) {
throw new IllegalArgumentException(String.format("Unknown context %s.", currentContext));
}
// If this is the first time a context definition is encountered, output a patient definition:
// define Patient = element of [<Patient model type>]
if (!implicitPatientCreated) {
if (libraryBuilder.hasUsings()) {
ModelInfo modelInfo = libraryBuilder.getModel(libraryInfo.getDefaultModelName()).getModelInfo();
String patientTypeName = modelInfo.getPatientClassName();
if (patientTypeName == null || patientTypeName.equals("")) {
throw new IllegalArgumentException("Model definition does not contain enough information to construct a patient context.");
}
DataType patientType = libraryBuilder.resolveTypeName(modelInfo.getName(), patientTypeName);
Retrieve patientRetrieve = of.createRetrieve().withDataType(libraryBuilder.dataTypeToQName(patientType));
track(patientRetrieve, ctx);
patientRetrieve.setResultType(new ListType(patientType));
String patientClassIdentifier = modelInfo.getPatientClassIdentifier();
if (patientClassIdentifier != null) {
patientRetrieve.setTemplateId(patientClassIdentifier);
}
ExpressionDef patientExpressionDef = of.createExpressionDef()
.withName("Patient")
.withContext(currentContext)
.withExpression(of.createSingletonFrom().withOperand(patientRetrieve));
track(patientExpressionDef, ctx);
patientExpressionDef.getExpression().setResultType(patientType);
patientExpressionDef.setResultType(patientType);
libraryBuilder.addExpression(patientExpressionDef);
}
else {
ExpressionDef patientExpressionDef = of.createExpressionDef()
.withName("Patient")
.withContext(currentContext)
.withExpression(of.createNull());
track(patientExpressionDef, ctx);
patientExpressionDef.getExpression().setResultType(libraryBuilder.resolveTypeName("System", "Any"));
patientExpressionDef.setResultType(patientExpressionDef.getExpression().getResultType());
libraryBuilder.addExpression(patientExpressionDef);
}
implicitPatientCreated = true;
return currentContext;
}
return currentContext;
}
public ExpressionDef internalVisitExpressionDefinition(@NotNull cqlParser.ExpressionDefinitionContext ctx) {
String identifier = parseString(ctx.identifier());
this.trackBackMap.put(identifier, getTrackBack(ctx));
ExpressionDef def = libraryBuilder.resolveExpressionRef(identifier);
if (def == null) {
libraryBuilder.pushExpressionContext(currentContext);
try {
libraryBuilder.pushExpressionDefinition(identifier);
try {
def = of.createExpressionDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(identifier)
.withContext(currentContext)
.withExpression((Expression) visit(ctx.expression()));
def.setResultType(def.getExpression().getResultType());
libraryBuilder.addExpression(def);
} finally {
libraryBuilder.popExpressionDefinition();
}
} finally {
libraryBuilder.popExpressionContext();
}
}
return def;
}
@Override
public ExpressionDef visitExpressionDefinition(@NotNull cqlParser.ExpressionDefinitionContext ctx) {
ExpressionDef expressionDef = internalVisitExpressionDefinition(ctx);
if (forwards.isEmpty() || !forwards.peek().getName().equals(expressionDef.getName())) {
if (definedExpressionDefinitions.contains(expressionDef.getName())) {
throw new IllegalArgumentException(String.format("Identifier %s is already in use in this library.", expressionDef.getName()));
}
// for use in MAT code... holds all of the important information for a definition
List<String> tokens = new ArrayList<>();
tokenize(tokens, ctx);
CQLExpressionModelObject cqlExpressionModelObject = new CQLExpressionModelObject(ctx.identifier().getText(), tokens, expressionDef);
this.cqlExpressionModelObjects.add(cqlExpressionModelObject);
// Track defined expression definitions locally, otherwise duplicate expression definitions will be missed because they are
// overwritten by name when they are encountered by the preprocessor.
definedExpressionDefinitions.add(expressionDef.getName());
}
return expressionDef;
}
@Override
public Literal visitStringLiteral(@NotNull cqlParser.StringLiteralContext ctx) {
return libraryBuilder.createLiteral(parseString(ctx.STRING()));
}
@Override
public Literal visitBooleanLiteral(@NotNull cqlParser.BooleanLiteralContext ctx) {
return libraryBuilder.createLiteral(Boolean.valueOf(ctx.getText()));
}
@Override
public Object visitIntervalSelector(@NotNull cqlParser.IntervalSelectorContext ctx) {
return libraryBuilder.createInterval(parseExpression(ctx.expression(0)), ctx.getChild(1).getText().equals("["),
parseExpression(ctx.expression(1)), ctx.getChild(5).getText().equals("]"));
}
@Override
public Object visitTupleElementSelector(@NotNull cqlParser.TupleElementSelectorContext ctx) {
TupleElement result = of.createTupleElement()
.withName(parseString(ctx.identifier()))
.withValue(parseExpression(ctx.expression()));
result.setResultType(result.getValue().getResultType());
return result;
}
@Override
public Object visitTupleSelector(@NotNull cqlParser.TupleSelectorContext ctx) {
Tuple tuple = of.createTuple();
TupleType tupleType = new TupleType();
for (cqlParser.TupleElementSelectorContext elementContext : ctx.tupleElementSelector()) {
TupleElement element = (TupleElement)visit(elementContext);
tupleType.addElement(new TupleTypeElement(element.getName(), element.getResultType()));
tuple.getElement().add(element);
}
tuple.setResultType(tupleType);
return tuple;
}
@Override
public Object visitInstanceElementSelector(@NotNull cqlParser.InstanceElementSelectorContext ctx) {
InstanceElement result = of.createInstanceElement()
.withName(parseString(ctx.identifier()))
.withValue(parseExpression(ctx.expression()));
result.setResultType(result.getValue().getResultType());
return result;
}
@Override
public Object visitInstanceSelector(@NotNull cqlParser.InstanceSelectorContext ctx) {
Instance instance = of.createInstance();
NamedTypeSpecifier classTypeSpecifier = visitNamedTypeSpecifier(ctx.namedTypeSpecifier());
instance.setClassType(classTypeSpecifier.getName());
instance.setResultType(classTypeSpecifier.getResultType());
for (cqlParser.InstanceElementSelectorContext elementContext : ctx.instanceElementSelector()) {
InstanceElement element = (InstanceElement)visit(elementContext);
DataType propertyType = libraryBuilder.resolveProperty(classTypeSpecifier.getResultType(), element.getName());
element.setValue(libraryBuilder.ensureCompatible(element.getValue(), propertyType));
instance.getElement().add(element);
}
return instance;
}
@Override
public Object visitCodeSelector(@NotNull cqlParser.CodeSelectorContext ctx) {
Code code = of.createCode();
code.setCode(parseString(ctx.STRING()));
code.setSystem((CodeSystemRef)visit(ctx.codesystemIdentifier()));
if (ctx.displayClause() != null) {
code.setDisplay(parseString(ctx.displayClause().STRING()));
}
code.setResultType(libraryBuilder.resolveTypeName("System", "Code"));
return code;
}
@Override
public Object visitConceptSelector(@NotNull cqlParser.ConceptSelectorContext ctx) {
Concept concept = of.createConcept();
if (ctx.displayClause() != null) {
concept.setDisplay(parseString(ctx.displayClause().STRING()));
}
for (cqlParser.CodeSelectorContext codeContext : ctx.codeSelector()) {
concept.getCode().add((Code)visit(codeContext));
}
concept.setResultType(libraryBuilder.resolveTypeName("System", "Concept"));
return concept;
}
@Override
public Object visitListSelector(@NotNull cqlParser.ListSelectorContext ctx) {
TypeSpecifier elementTypeSpecifier = parseTypeSpecifier(ctx.typeSpecifier());
org.hl7.elm.r1.List list = of.createList();
ListType listType = null;
if (elementTypeSpecifier != null) {
ListTypeSpecifier listTypeSpecifier = of.createListTypeSpecifier().withElementType(elementTypeSpecifier);
track(listTypeSpecifier, ctx.typeSpecifier());
listType = new ListType(elementTypeSpecifier.getResultType());
listTypeSpecifier.setResultType(listType);
}
DataType elementType = elementTypeSpecifier != null ? elementTypeSpecifier.getResultType() : null;
DataType inferredElementType = null;
List<Expression> elements = new ArrayList<>();
for (cqlParser.ExpressionContext elementContext : ctx.expression()) {
Expression element = parseExpression(elementContext);
if (elementType != null) {
libraryBuilder.verifyType(element.getResultType(), elementType);
}
else {
if (inferredElementType == null) {
inferredElementType = element.getResultType();
}
else {
DataType compatibleType = libraryBuilder.findCompatibleType(inferredElementType, element.getResultType());
if (compatibleType != null) {
inferredElementType = compatibleType;
}
else {
inferredElementType = libraryBuilder.resolveTypeName("System", "Any");
}
}
}
elements.add(element);
}
if (elementType == null) {
elementType = inferredElementType == null ? libraryBuilder.resolveTypeName("System", "Any") : inferredElementType;
}
for (Expression element : elements) {
if (!elementType.isSuperTypeOf(element.getResultType())) {
Conversion conversion = libraryBuilder.findConversion(element.getResultType(), elementType, true);
if (conversion != null) {
list.getElement().add(libraryBuilder.convertExpression(element, conversion));
}
else {
list.getElement().add(element);
}
}
else {
list.getElement().add(element);
}
}
if (listType == null) {
listType = new ListType(elementType);
}
list.setResultType(listType);
return list;
}
@Override
public Object visitTimeLiteral(@NotNull cqlParser.TimeLiteralContext ctx) {
String input = ctx.getText();
if (input.startsWith("@")) {
input = input.substring(1);
}
Pattern dateTimePattern =
Pattern.compile("T((\\d{2})(\\:(\\d{2})(\\:(\\d{2})(\\.(\\d+))?)?)?)?((Z)|(([+-])(\\d{2})(\\:?(\\d{2}))?))?");
//-12-------3---4-------5---6-------7---8-------------91---11-----1-------1----1------------
//-----------------------------------------------------0---12-----3-------4----5------------
Matcher matcher = dateTimePattern.matcher(input);
if (matcher.matches()) {
try {
Time result = of.createTime();
int hour = Integer.parseInt(matcher.group(2));
int minute = -1;
int second = -1;
int millisecond = -1;
if (hour < 0 || hour > 24) {
throw new IllegalArgumentException(String.format("Invalid hour in time literal (%s).", input));
}
result.setHour(libraryBuilder.createLiteral(hour));
if (matcher.group(4) != null) {
minute = Integer.parseInt(matcher.group(4));
if (minute < 0 || minute >= 60 || (hour == 24 && minute > 0)) {
throw new IllegalArgumentException(String.format("Invalid minute in time literal (%s).", input));
}
result.setMinute(libraryBuilder.createLiteral(minute));
}
if (matcher.group(6) != null) {
second = Integer.parseInt(matcher.group(6));
if (second < 0 || second >= 60 || (hour == 24 && second > 0)) {
throw new IllegalArgumentException(String.format("Invalid second in time literal (%s).", input));
}
result.setSecond(libraryBuilder.createLiteral(second));
}
if (matcher.group(8) != null) {
millisecond = Integer.parseInt(matcher.group(8));
if (millisecond < 0 || (hour == 24 && millisecond > 0)) {
throw new IllegalArgumentException(String.format("Invalid millisecond in time literal (%s).", input));
}
result.setMillisecond(libraryBuilder.createLiteral(millisecond));
}
if (matcher.group(10) != null && matcher.group(10).equals("Z")) {
result.setTimezoneOffset(libraryBuilder.createLiteral(0.0));
}
if (matcher.group(12) != null) {
int offsetPolarity = matcher.group(12).equals("+") ? 1 : 0;
if (matcher.group(15) != null) {
int hourOffset = Integer.parseInt(matcher.group(13));
if (hourOffset < 0 || hourOffset > 14) {
throw new IllegalArgumentException(String.format("Timezone hour offset out of range in time literal (%s).", input));
}
int minuteOffset = Integer.parseInt(matcher.group(15));
if (minuteOffset < 0 || minuteOffset >= 60 || (hourOffset == 14 && minuteOffset > 0)) {
throw new IllegalArgumentException(String.format("Timezone minute offset out of range in time literal (%s).", input));
}
result.setTimezoneOffset(libraryBuilder.createLiteral((double)(hourOffset + (minuteOffset / 60)) * offsetPolarity));
}
else {
if (matcher.group(13) != null) {
int hourOffset = Integer.parseInt(matcher.group(13));
if (hourOffset < 0 || hourOffset > 14) {
throw new IllegalArgumentException(String.format("Timezone hour offset out of range in time literal (%s).", input));
}
result.setTimezoneOffset(libraryBuilder.createLiteral((double)(hourOffset * offsetPolarity)));
}
}
}
result.setResultType(libraryBuilder.resolveTypeName("System", "Time"));
return result;
}
catch (RuntimeException e) {
throw new IllegalArgumentException(String.format("Invalid date-time input (%s). Use ISO 8601 date time representation (yyyy-MM-ddThh:mm:ss.mmmmZhh:mm).", input), e);
}
}
else {
throw new IllegalArgumentException(String.format("Invalid date-time input (%s). Use ISO 8601 date time representation (yyyy-MM-ddThh:mm:ss.mmmmZhh:mm).", input));
}
}
@Override
public Object visitDateTimeLiteral(@NotNull cqlParser.DateTimeLiteralContext ctx) {
String input = ctx.getText();
if (input.startsWith("@")) {
input = input.substring(1);
}
Pattern dateTimePattern =
Pattern.compile("(\\d{4})(-(\\d{2}))?(-(\\d{2}))?((Z)|(T((\\d{2})(\\:(\\d{2})(\\:(\\d{2})(\\.(\\d+))?)?)?)?((Z)|(([+-])(\\d{2})(\\:?(\\d{2}))?))?))?");
//1-------2-3---------4-5---------67---8-91-------1---1-------1---1-------1---1-------------11---12-----2-------2----2---------------
//----------------------------------------0-------1---2-------3---4-------5---6-------------78---90-----1-------2----3---------------
Matcher matcher = dateTimePattern.matcher(input);
if (matcher.matches()) {
try {
GregorianCalendar calendar = (GregorianCalendar)GregorianCalendar.getInstance();
DateTime result = of.createDateTime();
int year = Integer.parseInt(matcher.group(1));
int month = -1;
int day = -1;
int hour = -1;
int minute = -1;
int second = -1;
int millisecond = -1;
result.setYear(libraryBuilder.createLiteral(year));
if (matcher.group(3) != null) {
month = Integer.parseInt(matcher.group(3));
if (month < 0 || month > 12) {
throw new IllegalArgumentException(String.format("Invalid month in date/time literal (%s).", input));
}
result.setMonth(libraryBuilder.createLiteral(month));
}
if (matcher.group(5) != null) {
day = Integer.parseInt(matcher.group(5));
int maxDay = 31;
switch (month) {
case 2: maxDay = calendar.isLeapYear(year) ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11: maxDay = 30;
break;
default:
break;
}
if (day < 0 || day > maxDay) {
throw new IllegalArgumentException(String.format("Invalid day in date/time literal (%s).", input));
}
result.setDay(libraryBuilder.createLiteral(day));
}
if (matcher.group(10) != null) {
hour = Integer.parseInt(matcher.group(10));
if (hour < 0 || hour > 24) {
throw new IllegalArgumentException(String.format("Invalid hour in date/time literal (%s).", input));
}
result.setHour(libraryBuilder.createLiteral(hour));
}
if (matcher.group(12) != null) {
minute = Integer.parseInt(matcher.group(12));
if (minute < 0 || minute >= 60 || (hour == 24 && minute > 0)) {
throw new IllegalArgumentException(String.format("Invalid minute in date/time literal (%s).", input));
}
result.setMinute(libraryBuilder.createLiteral(minute));
}
if (matcher.group(14) != null) {
second = Integer.parseInt(matcher.group(14));
if (second < 0 || second >= 60 || (hour == 24 && second > 0)) {
throw new IllegalArgumentException(String.format("Invalid second in date/time literal (%s).", input));
}
result.setSecond(libraryBuilder.createLiteral(second));
}
if (matcher.group(16) != null) {
millisecond = Integer.parseInt(matcher.group(16));
if (millisecond < 0 || (hour == 24 && millisecond > 0)) {
throw new IllegalArgumentException(String.format("Invalid millisecond in date/time literal (%s).", input));
}
result.setMillisecond(libraryBuilder.createLiteral(millisecond));
}
if ((matcher.group(7) != null && matcher.group(7).equals("Z"))
|| ((matcher.group(18) != null) && matcher.group(18).equals("Z"))) {
result.setTimezoneOffset(libraryBuilder.createLiteral(0.0));
}
if (matcher.group(20) != null) {
int offsetPolarity = matcher.group(20).equals("+") ? 1 : 0;
if (matcher.group(23) != null) {
int hourOffset = Integer.parseInt(matcher.group(21));
if (hourOffset < 0 || hourOffset > 14) {
throw new IllegalArgumentException(String.format("Timezone hour offset is out of range in date/time literal (%s).", input));
}
int minuteOffset = Integer.parseInt(matcher.group(23));
if (minuteOffset < 0 || minuteOffset >= 60 || (hourOffset == 14 && minuteOffset > 0)) {
throw new IllegalArgumentException(String.format("Timezone minute offset is out of range in date/time literal (%s).", input));
}
result.setTimezoneOffset(libraryBuilder.createLiteral((double)(hourOffset + (minuteOffset / 60)) * offsetPolarity));
}
else {
if (matcher.group(21) != null) {
int hourOffset = Integer.parseInt(matcher.group(21));
if (hourOffset < 0 || hourOffset > 14) {
throw new IllegalArgumentException(String.format("Timezone hour offset is out of range in date/time literal (%s).", input));
}
result.setTimezoneOffset(libraryBuilder.createLiteral((double)(hourOffset * offsetPolarity)));
}
}
}
result.setResultType(libraryBuilder.resolveTypeName("System", "DateTime"));
return result;
}
catch (RuntimeException e) {
throw new IllegalArgumentException(String.format("Invalid date-time input (%s). Use ISO 8601 date time representation (yyyy-MM-ddThh:mm:ss.mmmmZhh:mm).", input), e);
}
}
else {
throw new IllegalArgumentException(String.format("Invalid date-time input (%s). Use ISO 8601 date time representation (yyyy-MM-ddThh:mm:ss.mmmmZhh:mm).", input));
}
}
@Override
public Null visitNullLiteral(@NotNull cqlParser.NullLiteralContext ctx) {
Null result = of.createNull();
result.setResultType(libraryBuilder.resolveTypeName("System", "Any"));
return result;
}
@Override
public Expression visitNumberLiteral(@NotNull cqlParser.NumberLiteralContext ctx) {
return libraryBuilder.createNumberLiteral(ctx.NUMBER().getText());
}
@Override
public Expression visitQuantity(@NotNull cqlParser.QuantityContext ctx) {
if (ctx.unit() != null) {
DecimalFormat df = new DecimalFormat("#.#");
df.setParseBigDecimal(true);
try {
Quantity result = of.createQuantity()
.withValue((BigDecimal) df.parse(ctx.NUMBER().getText()))
.withUnit(parseString(ctx.unit()));
result.setResultType(libraryBuilder.resolveTypeName("System", "Quantity"));
return result;
} catch (ParseException e) {
throw new IllegalArgumentException(String.format("Could not parse quantity literal: %s", ctx.getText()), e);
}
} else {
return libraryBuilder.createNumberLiteral(ctx.NUMBER().getText());
}
}
@Override
public Not visitNotExpression(@NotNull cqlParser.NotExpressionContext ctx) {
Not result = of.createNot().withOperand(parseExpression(ctx.expression()));
libraryBuilder.resolveUnaryCall("System", "Not", result);
return result;
}
@Override
public Exists visitExistenceExpression(@NotNull cqlParser.ExistenceExpressionContext ctx) {
Exists result = of.createExists().withOperand(parseExpression(ctx.expression()));
libraryBuilder.resolveUnaryCall("System", "Exists", result);
return result;
}
@Override
public BinaryExpression visitMultiplicationExpressionTerm(@NotNull cqlParser.MultiplicationExpressionTermContext ctx) {
BinaryExpression exp = null;
String operatorName = null;
switch (ctx.getChild(1).getText()) {
case "*":
exp = of.createMultiply();
operatorName = "Multiply";
break;
case "/":
exp = of.createDivide();
operatorName = "Divide";
break;
case "div":
exp = of.createTruncatedDivide();
operatorName = "TruncatedDivide";
break;
case "mod":
exp = of.createModulo();
operatorName = "Modulo";
break;
default:
throw new IllegalArgumentException(String.format("Unsupported operator: %s.", ctx.getChild(1).getText()));
}
exp.withOperand(
parseExpression(ctx.expressionTerm(0)),
parseExpression(ctx.expressionTerm(1)));
libraryBuilder.resolveBinaryCall("System", operatorName, exp);
return exp;
}
@Override
public Power visitPowerExpressionTerm(@NotNull cqlParser.PowerExpressionTermContext ctx) {
Power power = of.createPower().withOperand(
parseExpression(ctx.expressionTerm(0)),
parseExpression(ctx.expressionTerm(1)));
libraryBuilder.resolveBinaryCall("System", "Power", power);
return power;
}
@Override
public Object visitPolarityExpressionTerm(@NotNull cqlParser.PolarityExpressionTermContext ctx) {
if (ctx.getChild(0).getText().equals("+")) {
return visit(ctx.expressionTerm());
}
Negate result = of.createNegate().withOperand(parseExpression(ctx.expressionTerm()));
libraryBuilder.resolveUnaryCall("System", "Negate", result);
return result;
}
@Override
public Expression visitAdditionExpressionTerm(@NotNull cqlParser.AdditionExpressionTermContext ctx) {
Expression exp = null;
String operatorName = null;
switch (ctx.getChild(1).getText()) {
case "+":
exp = of.createAdd();
operatorName = "Add";
break;
case "-":
exp = of.createSubtract();
operatorName = "Subtract";
break;
case "&":
exp = of.createConcatenate();
operatorName = "Concatenate";
break;
default:
throw new IllegalArgumentException(String.format("Unsupported operator: %s.", ctx.getChild(1).getText()));
}
if (exp instanceof BinaryExpression) {
((BinaryExpression)exp).withOperand(
parseExpression(ctx.expressionTerm(0)),
parseExpression(ctx.expressionTerm(1)));
libraryBuilder.resolveBinaryCall("System", operatorName, (BinaryExpression)exp);
if (exp.getResultType() == libraryBuilder.resolveTypeName("System", "String")) {
Concatenate concatenate = of.createConcatenate();
concatenate.getOperand().addAll(((BinaryExpression)exp).getOperand());
concatenate.setResultType(exp.getResultType());
exp = concatenate;
}
}
else {
Concatenate concatenate = (Concatenate)exp;
concatenate.withOperand(
parseExpression(ctx.expressionTerm(0)),
parseExpression(ctx.expressionTerm(1)));
for (int i = 0; i < concatenate.getOperand().size(); i++) {
Expression operand = concatenate.getOperand().get(i);
Literal empty = libraryBuilder.createLiteral("");
ArrayList<Expression> params = new ArrayList<Expression>();
params.add(operand);
params.add(empty);
Expression coalesce = libraryBuilder.resolveFunction("System", "Coalesce", params);
concatenate.getOperand().set(i, coalesce);
}
libraryBuilder.resolveNaryCall("System", operatorName, concatenate);
}
return exp;
}
@Override
public Object visitPredecessorExpressionTerm(@NotNull cqlParser.PredecessorExpressionTermContext ctx) {
Predecessor result = of.createPredecessor().withOperand(parseExpression(ctx.expressionTerm()));
libraryBuilder.resolveUnaryCall("System", "Predecessor", result);
return result;
}
@Override
public Object visitSuccessorExpressionTerm(@NotNull cqlParser.SuccessorExpressionTermContext ctx) {
Successor result = of.createSuccessor().withOperand(parseExpression(ctx.expressionTerm()));
libraryBuilder.resolveUnaryCall("System", "Successor", result);
return result;
}
@Override
public Object visitElementExtractorExpressionTerm(@NotNull cqlParser.ElementExtractorExpressionTermContext ctx) {
SingletonFrom result = of.createSingletonFrom().withOperand(parseExpression(ctx.expressionTerm()));
if (!(result.getOperand().getResultType() instanceof ListType)) {
throw new IllegalArgumentException("List type expected.");
}
result.setResultType(((ListType)result.getOperand().getResultType()).getElementType());
libraryBuilder.resolveUnaryCall("System", "SingletonFrom", result);
return result;
}
@Override
public Object visitPointExtractorExpressionTerm(@NotNull cqlParser.PointExtractorExpressionTermContext ctx) {
PointFrom result = of.createPointFrom().withOperand(parseExpression(ctx.expressionTerm()));
if (!(result.getOperand().getResultType() instanceof IntervalType)) {
throw new IllegalArgumentException("Interval type expected.");
}
result.setResultType(((IntervalType)result.getOperand().getResultType()).getPointType());
libraryBuilder.resolveUnaryCall("System", "PointFrom", result);
return result;
}
@Override
public Object visitTypeExtentExpressionTerm(@NotNull cqlParser.TypeExtentExpressionTermContext ctx) {
String extent = parseString(ctx.getChild(0));
TypeSpecifier targetType = parseTypeSpecifier(ctx.namedTypeSpecifier());
switch (extent) {
case "minimum": {
MinValue minimum = of.createMinValue();
minimum.setValueType(libraryBuilder.dataTypeToQName(targetType.getResultType()));
minimum.setResultType(targetType.getResultType());
return minimum;
}
case "maximum": {
MaxValue maximum = of.createMaxValue();
maximum.setValueType(libraryBuilder.dataTypeToQName(targetType.getResultType()));
maximum.setResultType(targetType.getResultType());
return maximum;
}
default: throw new IllegalArgumentException(String.format("Unknown extent: %s", extent));
}
}
@Override
public Object visitTimeBoundaryExpressionTerm(@NotNull cqlParser.TimeBoundaryExpressionTermContext ctx) {
UnaryExpression result = null;
String operatorName = null;
if (ctx.getChild(0).getText().equals("start")) {
result = of.createStart().withOperand(parseExpression(ctx.expressionTerm()));
operatorName = "Start";
}
else {
result = of.createEnd().withOperand(parseExpression(ctx.expressionTerm()));
operatorName = "End";
}
if (!(result.getOperand().getResultType() instanceof IntervalType)) {
throw new IllegalArgumentException("Interval type expected.");
}
result.setResultType(((IntervalType)result.getOperand().getResultType()).getPointType());
libraryBuilder.resolveUnaryCall("System", operatorName, result);
return result;
}
private DateTimePrecision parseDateTimePrecision(String dateTimePrecision) {
if (dateTimePrecision == null) {
throw new IllegalArgumentException("dateTimePrecision is null");
}
switch (dateTimePrecision) {
case "a":
case "year":
case "years":
return DateTimePrecision.YEAR;
case "mo":
case "month":
case "months":
return DateTimePrecision.MONTH;
case "wk":
case "week":
case "weeks":
return DateTimePrecision.WEEK;
case "d":
case "day":
case "days":
return DateTimePrecision.DAY;
case "h":
case "hour":
case "hours":
return DateTimePrecision.HOUR;
case "min":
case "minute":
case "minutes":
return DateTimePrecision.MINUTE;
case "s":
case "second":
case "seconds":
return DateTimePrecision.SECOND;
case "ms":
case "millisecond":
case "milliseconds":
return DateTimePrecision.MILLISECOND;
default:
throw new IllegalArgumentException(String.format("Unknown precision '%s'.", dateTimePrecision));
}
}
@Override
public Object visitTimeUnitExpressionTerm(@NotNull cqlParser.TimeUnitExpressionTermContext ctx) {
String component = ctx.dateTimeComponent().getText();
UnaryExpression result = null;
String operatorName = null;
switch (component) {
case "date":
result = of.createDateFrom().withOperand(parseExpression(ctx.expressionTerm()));
operatorName = "DateFrom";
break;
case "time":
result = of.createTimeFrom().withOperand(parseExpression(ctx.expressionTerm()));
operatorName = "TimeFrom";
break;
case "timezone":
result = of.createTimezoneFrom().withOperand(parseExpression(ctx.expressionTerm()));
operatorName = "TimezoneFrom";
break;
case "year":
case "month":
case "week":
case "day":
case "hour":
case "minute":
case "second":
case "millisecond":
result = of.createDateTimeComponentFrom()
.withOperand(parseExpression(ctx.expressionTerm()))
.withPrecision(parseDateTimePrecision(component));
operatorName = "DateTimeComponentFrom";
break;
default:
throw new IllegalArgumentException(String.format("Unknown precision '%s'.", component));
}
libraryBuilder.resolveUnaryCall("System", operatorName, result);
return result;
}
@Override
public Object visitDurationExpressionTerm(@NotNull cqlParser.DurationExpressionTermContext ctx) {
// duration in days of X <=> days between start of X and end of X
Expression operand = parseExpression(ctx.expressionTerm());
Start start = of.createStart().withOperand(operand);
libraryBuilder.resolveUnaryCall("System", "Start", start);
End end = of.createEnd().withOperand(operand);
libraryBuilder.resolveUnaryCall("System", "End", end);
DurationBetween result = of.createDurationBetween()
.withPrecision(parseDateTimePrecision(ctx.pluralDateTimePrecision().getText()))
.withOperand(start, end);
libraryBuilder.resolveBinaryCall("System", "DurationBetween", result);
return result;
}
@Override
public Object visitBetweenExpression(@NotNull cqlParser.BetweenExpressionContext ctx) {
// X properly? between Y and Z
Expression first = parseExpression(ctx.expression());
Expression second = parseExpression(ctx.expressionTerm(0));
Expression third = parseExpression(ctx.expressionTerm(1));
boolean isProper = ctx.getChild(0).getText().equals("properly");
if (first.getResultType() instanceof IntervalType) {
BinaryExpression result = isProper ? of.createProperIncludedIn() : of.createIncludedIn()
.withOperand(first, libraryBuilder.createInterval(second, true, third, true));
libraryBuilder.resolveBinaryCall("System", isProper ? "ProperIncludedIn" : "IncludedIn", result);
return result;
}
else {
BinaryExpression result = of.createAnd()
.withOperand(
(isProper ? of.createGreater() : of.createGreaterOrEqual())
.withOperand(first, second),
(isProper ? of.createLess() : of.createLessOrEqual())
.withOperand(first, third)
);
libraryBuilder.resolveBinaryCall("System", isProper ? "Greater" : "GreaterOrEqual", (BinaryExpression) result.getOperand().get(0));
libraryBuilder.resolveBinaryCall("System", isProper ? "Less" : "LessOrEqual", (BinaryExpression) result.getOperand().get(1));
libraryBuilder.resolveBinaryCall("System", "And", result);
return result;
}
}
@Override
public Object visitDurationBetweenExpression(@NotNull cqlParser.DurationBetweenExpressionContext ctx) {
BinaryExpression result = of.createDurationBetween()
.withPrecision(parseDateTimePrecision(ctx.pluralDateTimePrecision().getText()))
.withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1)));
libraryBuilder.resolveBinaryCall("System", "DurationBetween", result);
return result;
}
@Override
public Object visitDifferenceBetweenExpression(@NotNull cqlParser.DifferenceBetweenExpressionContext ctx) {
BinaryExpression result = of.createDifferenceBetween()
.withPrecision(parseDateTimePrecision(ctx.pluralDateTimePrecision().getText()))
.withOperand(parseExpression(ctx.expressionTerm(0)), parseExpression(ctx.expressionTerm(1)));
libraryBuilder.resolveBinaryCall("System", "DifferenceBetween", result);
return result;
}
@Override
public Object visitWidthExpressionTerm(@NotNull cqlParser.WidthExpressionTermContext ctx) {
UnaryExpression result = of.createWidth().withOperand(parseExpression(ctx.expressionTerm()));
libraryBuilder.resolveUnaryCall("System", "Width", result);
return result;
}
@Override
public Expression visitParenthesizedTerm(@NotNull cqlParser.ParenthesizedTermContext ctx) {
return parseExpression(ctx.expression());
}
@Override
public Object visitMembershipExpression(@NotNull cqlParser.MembershipExpressionContext ctx) {
String operator = ctx.getChild(1).getText();
switch (operator) {
case "in":
if (ctx.dateTimePrecisionSpecifier() != null) {
In in = of.createIn()
.withPrecision(parseDateTimePrecision(ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()))
.withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1))
);
libraryBuilder.resolveBinaryCall("System", "In", in);
return in;
} else {
Expression left = parseExpression(ctx.expression(0));
Expression right = parseExpression(ctx.expression(1));
return libraryBuilder.resolveIn(left, right);
}
case "contains":
if (ctx.dateTimePrecisionSpecifier() != null) {
Contains contains = of.createContains()
.withPrecision(parseDateTimePrecision(ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()))
.withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1))
);
libraryBuilder.resolveBinaryCall("System", "Contains", contains);
return contains;
} else {
Expression left = parseExpression(ctx.expression(0));
Expression right = parseExpression(ctx.expression(1));
if (left instanceof ValueSetRef) {
InValueSet in = of.createInValueSet()
.withCode(right)
.withValueset((ValueSetRef) left);
libraryBuilder.resolveCall("System", "InValueSet", new InValueSetInvocation(in));
return in;
}
if (left instanceof CodeSystemRef) {
InCodeSystem in = of.createInCodeSystem()
.withCode(right)
.withCodesystem((CodeSystemRef)left);
libraryBuilder.resolveCall("System", "InCodeSystem", new InCodeSystemInvocation(in));
return in;
}
Contains contains = of.createContains().withOperand(left, right);
libraryBuilder.resolveBinaryCall("System", "Contains", contains);
return contains;
}
}
throw new IllegalArgumentException(String.format("Unknown operator: %s", operator));
}
@Override
public And visitAndExpression(@NotNull cqlParser.AndExpressionContext ctx) {
And and = of.createAnd().withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", "And", and);
return and;
}
@Override
public Expression visitOrExpression(@NotNull cqlParser.OrExpressionContext ctx) {
if (ctx.getChild(1).getText().equals("xor")) {
Xor xor = of.createXor().withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", "Xor", xor);
return xor;
} else {
Or or = of.createOr().withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", "Or", or);
return or;
}
}
@Override
public Expression visitImpliesExpression(@NotNull cqlParser.ImpliesExpressionContext ctx) {
Implies implies = of.createImplies().withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", "Implies", implies);
return implies;
}
@Override
public Object visitInFixSetExpression(@NotNull cqlParser.InFixSetExpressionContext ctx) {
String operator = ctx.getChild(1).getText();
Expression left = parseExpression(ctx.expression(0));
Expression right = parseExpression(ctx.expression(1));
// for union of lists
// collect list of types in either side
// cast both operands to a choice type with all types
// for intersect of lists
// collect list of types in both sides
// cast both operands to a choice type with all types
// TODO: cast the result to a choice type with only types in both sides
// for difference of lists
// collect list of types in both sides
// cast both operands to a choice type with all types
// TODO: cast the result to the initial type of the left
if (left.getResultType() instanceof ListType && right.getResultType() instanceof ListType) {
ListType leftListType = (ListType)left.getResultType();
ListType rightListType = (ListType)right.getResultType();
if (!(leftListType.isSuperTypeOf(rightListType) || rightListType.isSuperTypeOf(leftListType))
&& !(leftListType.isCompatibleWith(rightListType) || rightListType.isCompatibleWith(leftListType))) {
Set<DataType> elementTypes = new HashSet<DataType>();
if (leftListType.getElementType() instanceof ChoiceType) {
for (DataType choice : ((ChoiceType)leftListType.getElementType()).getTypes()) {
elementTypes.add(choice);
}
}
else {
elementTypes.add(leftListType.getElementType());
}
if (rightListType.getElementType() instanceof ChoiceType) {
for (DataType choice : ((ChoiceType)rightListType.getElementType()).getTypes()) {
elementTypes.add(choice);
}
}
else {
elementTypes.add(rightListType.getElementType());
}
if (elementTypes.size() > 1) {
ListType targetType = new ListType(new ChoiceType(elementTypes));
left = of.createAs().withOperand(left).withAsTypeSpecifier(libraryBuilder.dataTypeToTypeSpecifier(targetType));
track(left, ctx.expression(0));
left.setResultType(targetType);
right = of.createAs().withOperand(right).withAsTypeSpecifier(libraryBuilder.dataTypeToTypeSpecifier(targetType));
track(right, ctx.expression(1));
right.setResultType(targetType);
}
}
}
switch (operator) {
case "|":
case "union":
Union union = of.createUnion().withOperand(left, right);
libraryBuilder.resolveBinaryCall("System", "Union", union);
return union;
case "intersect":
Intersect intersect = of.createIntersect().withOperand(left, right);
libraryBuilder.resolveBinaryCall("System", "Intersect", intersect);
return intersect;
case "except":
Except except = of.createExcept().withOperand(left, right);
libraryBuilder.resolveBinaryCall("System", "Except", except);
return except;
}
return of.createNull();
}
@Override
public Expression visitEqualityExpression(@NotNull cqlParser.EqualityExpressionContext ctx) {
String operator = parseString(ctx.getChild(1));
if (operator.equals("~") || operator.equals("!~")) {
BinaryExpression equivalent = of.createEquivalent().withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", "Equivalent", equivalent);
if (!"~".equals(parseString(ctx.getChild(1)))) {
track(equivalent, ctx);
Not not = of.createNot().withOperand(equivalent);
libraryBuilder.resolveUnaryCall("System", "Not", not);
return not;
}
return equivalent;
}
else {
BinaryExpression equal = of.createEqual().withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", "Equal", equal);
if (!"=".equals(parseString(ctx.getChild(1)))) {
track(equal, ctx);
Not not = of.createNot().withOperand(equal);
libraryBuilder.resolveUnaryCall("System", "Not", not);
return not;
}
return equal;
}
}
@Override
public BinaryExpression visitInequalityExpression(@NotNull cqlParser.InequalityExpressionContext ctx) {
BinaryExpression exp;
String operatorName;
switch (parseString(ctx.getChild(1))) {
case "<=":
operatorName = "LessOrEqual";
exp = of.createLessOrEqual();
break;
case "<":
operatorName = "Less";
exp = of.createLess();
break;
case ">":
operatorName = "Greater";
exp = of.createGreater();
break;
case ">=":
operatorName = "GreaterOrEqual";
exp = of.createGreaterOrEqual();
break;
default:
throw new IllegalArgumentException(String.format("Unknown operator: %s", ctx.getChild(1).getText()));
}
exp.withOperand(
parseExpression(ctx.expression(0)),
parseExpression(ctx.expression(1)));
libraryBuilder.resolveBinaryCall("System", operatorName, exp);
return exp;
}
@Override
public List<String> visitQualifiedIdentifier(@NotNull cqlParser.QualifiedIdentifierContext ctx) {
// Return the list of qualified identifiers for resolution by the containing element
List<String> identifiers = new ArrayList<>();
for (cqlParser.QualifierContext qualifierContext : ctx.qualifier()) {
String qualifier = parseString(qualifierContext);
identifiers.add(qualifier);
}
String identifier = parseString(ctx.identifier());
identifiers.add(identifier);
return identifiers;
}
@Override
public Object visitTermExpression(@NotNull cqlParser.TermExpressionContext ctx) {
Object result = super.visitTermExpression(ctx);
if (result instanceof LibraryRef) {
throw new IllegalArgumentException(String.format("Identifier %s is a library and cannot be used as an expression.", ((LibraryRef)result).getLibraryName()));
}
return result;
}
@Override
public Object visitTerminal(@NotNull TerminalNode node) {
String text = node.getText();
int tokenType = node.getSymbol().getType();
if (cqlLexer.STRING == tokenType || cqlLexer.QUOTEDIDENTIFIER == tokenType) {
// chop off leading and trailing ' or "
text = text.substring(1, text.length() - 1);
if (cqlLexer.STRING == tokenType) {
text = text.replace("''", "'");
}
else {
text = text.replace("\"\"", "\"");
}
}
return text;
}
@Override
public Object visitConversionExpressionTerm(@NotNull cqlParser.ConversionExpressionTermContext ctx) {
TypeSpecifier targetType = parseTypeSpecifier(ctx.typeSpecifier());
Expression operand = parseExpression(ctx.expression());
if (!DataTypes.equal(operand.getResultType(), targetType.getResultType())) {
Conversion conversion = libraryBuilder.findConversion(operand.getResultType(), targetType.getResultType(), false);
if (conversion == null) {
throw new IllegalArgumentException(String.format("Could not resolve conversion from type %s to type %s.",
operand.getResultType(), targetType.getResultType()));
}
return libraryBuilder.convertExpression(operand, conversion);
}
return operand;
}
@Override
public Object visitTypeExpression(@NotNull cqlParser.TypeExpressionContext ctx) {
if (ctx.getChild(1).getText().equals("is")) {
Is is = of.createIs()
.withOperand(parseExpression(ctx.expression()))
.withIsTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier()));
is.setResultType(libraryBuilder.resolveTypeName("System", "Boolean"));
return is;
}
As as = of.createAs()
.withOperand(parseExpression(ctx.expression()))
.withAsTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier()))
.withStrict(false);
DataType targetType = as.getAsTypeSpecifier().getResultType();
DataTypes.verifyCast(targetType, as.getOperand().getResultType());
as.setResultType(targetType);
return as;
}
@Override
public Object visitCastExpression(@NotNull cqlParser.CastExpressionContext ctx) {
As as = of.createAs()
.withOperand(parseExpression(ctx.expression()))
.withAsTypeSpecifier(parseTypeSpecifier(ctx.typeSpecifier()))
.withStrict(true);
DataType targetType = as.getAsTypeSpecifier().getResultType();
DataTypes.verifyCast(targetType, as.getOperand().getResultType());
as.setResultType(targetType);
return as;
}
@Override
public Expression visitBooleanExpression(@NotNull cqlParser.BooleanExpressionContext ctx) {
UnaryExpression exp = null;
Expression left = (Expression) visit(ctx.expression());
String lastChild = ctx.getChild(ctx.getChildCount() - 1).getText();
String nextToLast = ctx.getChild(ctx.getChildCount() - 2).getText();
switch (lastChild) {
case "null" :
exp = of.createIsNull().withOperand(left);
libraryBuilder.resolveUnaryCall("System", "IsNull", exp);
break;
case "true" :
exp = of.createIsTrue().withOperand(left);
libraryBuilder.resolveUnaryCall("System", "IsTrue", exp);
break;
case "false" :
exp = of.createIsFalse().withOperand(left);
libraryBuilder.resolveUnaryCall("System", "IsFalse", exp);
break;
default:
throw new IllegalArgumentException(String.format("Unknown boolean test predicate %s.", lastChild));
}
if ("not".equals(nextToLast)) {
track(exp, ctx);
exp = of.createNot().withOperand(exp);
libraryBuilder.resolveUnaryCall("System", "Not", exp);
}
return exp;
}
@Override
public Object visitTimingExpression(@NotNull cqlParser.TimingExpressionContext ctx) {
Expression left = parseExpression(ctx.expression(0));
Expression right = parseExpression(ctx.expression(1));
TimingOperatorContext timingOperatorContext = new TimingOperatorContext(left, right);
timingOperators.push(timingOperatorContext);
try {
return visit(ctx.intervalOperatorPhrase());
} finally {
timingOperators.pop();
}
}
@Override
public Object visitConcurrentWithIntervalOperatorPhrase(@NotNull cqlParser.ConcurrentWithIntervalOperatorPhraseContext ctx) {
// ('starts' | 'ends' | 'occurs')? 'same' dateTimePrecision? (relativeQualifier | 'as') ('start' | 'end')?
TimingOperatorContext timingOperator = timingOperators.peek();
ParseTree firstChild = ctx.getChild(0);
if ("starts".equals(firstChild.getText())) {
Start start = of.createStart().withOperand(timingOperator.getLeft());
track(start, firstChild);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setLeft(start);
}
if ("ends".equals(firstChild.getText())) {
End end = of.createEnd().withOperand(timingOperator.getLeft());
track(end, firstChild);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setLeft(end);
}
ParseTree lastChild = ctx.getChild(ctx.getChildCount() - 1);
if ("start".equals(lastChild.getText())) {
Start start = of.createStart().withOperand(timingOperator.getRight());
track(start, lastChild);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setRight(start);
}
if ("end".equals(lastChild.getText())) {
End end = of.createEnd().withOperand(timingOperator.getRight());
track(end, lastChild);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setRight(end);
}
String operatorName = null;
BinaryExpression operator = null;
if (ctx.relativeQualifier() == null) {
if (ctx.dateTimePrecision() != null) {
operator = of.createSameAs().withPrecision(parseDateTimePrecision(ctx.dateTimePrecision().getText()));
} else {
operator = of.createSameAs();
}
operatorName = "SameAs";
} else {
switch (ctx.relativeQualifier().getText()) {
case "or after": {
if (ctx.dateTimePrecision() != null) {
operator = of.createSameOrAfter().withPrecision(parseDateTimePrecision(ctx.dateTimePrecision().getText()));
} else {
operator = of.createSameOrAfter();
}
operatorName = "SameOrAfter";
}
break;
case "or before": {
if (ctx.dateTimePrecision() != null) {
operator = of.createSameOrBefore().withPrecision(parseDateTimePrecision(ctx.dateTimePrecision().getText()));
} else {
operator = of.createSameOrBefore();
}
operatorName = "SameOrBefore";
}
break;
default:
throw new IllegalArgumentException(String.format("Unknown relative qualifier: '%s'.", ctx.relativeQualifier().getText()));
}
}
operator = operator.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", operatorName, operator);
return operator;
}
@Override
public Object visitIncludesIntervalOperatorPhrase(@NotNull cqlParser.IncludesIntervalOperatorPhraseContext ctx) {
// 'properly'? 'includes' dateTimePrecisionSpecifier? ('start' | 'end')?
boolean isProper = false;
boolean isRightPoint = false;
TimingOperatorContext timingOperator = timingOperators.peek();
for (ParseTree pt : ctx.children) {
if ("properly".equals(pt.getText())) {
isProper = true;
continue;
}
if ("start".equals(pt.getText())) {
Start start = of.createStart().withOperand(timingOperator.getRight());
track(start, pt);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setRight(start);
isRightPoint = true;
continue;
}
if ("end".equals(pt.getText())) {
End end = of.createEnd().withOperand(timingOperator.getRight());
track(end, pt);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setRight(end);
isRightPoint = true;
continue;
}
}
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
if (!isRightPoint &&
!(timingOperator.getRight().getResultType() instanceof IntervalType
|| timingOperator.getRight().getResultType() instanceof ListType)) {
isRightPoint = true;
}
if (isRightPoint) {
if (isProper) {
if (dateTimePrecision != null) {
ProperContains properContains = of.createProperContains().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperContains", properContains);
return properContains;
}
ProperContains properContains = of.createProperContains()
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperContains", properContains);
return properContains;
}
if (dateTimePrecision != null) {
Contains contains = of.createContains().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Contains", contains);
return contains;
}
Contains contains = of.createContains().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Contains", contains);
return contains;
}
if (isProper) {
if (dateTimePrecision != null) {
ProperIncludes properIncludes = of.createProperIncludes().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperIncludes", properIncludes);
return properIncludes;
}
ProperIncludes properIncludes = of.createProperIncludes().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperIncludes", properIncludes);
return properIncludes;
}
if (dateTimePrecision != null) {
Includes includes = of.createIncludes().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Includes", includes);
return includes;
}
Includes includes = of.createIncludes().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Includes", includes);
return includes;
}
@Override
public Object visitIncludedInIntervalOperatorPhrase(@NotNull cqlParser.IncludedInIntervalOperatorPhraseContext ctx) {
// ('starts' | 'ends' | 'occurs')? 'properly'? ('during' | 'included in') dateTimePrecisionSpecifier?
boolean isProper = false;
boolean isLeftPoint = false;
TimingOperatorContext timingOperator = timingOperators.peek();
for (ParseTree pt : ctx.children) {
if ("starts".equals(pt.getText())) {
Start start = of.createStart().withOperand(timingOperator.getLeft());
track(start, pt);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setLeft(start);
isLeftPoint = true;
continue;
}
if ("ends".equals(pt.getText())) {
End end = of.createEnd().withOperand(timingOperator.getLeft());
track(end, pt);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setLeft(end);
isLeftPoint = true;
continue;
}
if ("properly".equals(pt.getText())) {
isProper = true;
continue;
}
}
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
if (!isLeftPoint &&
!(timingOperator.getLeft().getResultType() instanceof IntervalType
|| timingOperator.getLeft().getResultType() instanceof ListType)) {
isLeftPoint = true;
}
if (isLeftPoint) {
if (isProper) {
if (dateTimePrecision != null) {
ProperIn properIn = of.createProperIn().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperIn", properIn);
return properIn;
}
ProperIn properIn = of.createProperIn().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperIn", properIn);
return properIn;
}
if (dateTimePrecision != null) {
In in = of.createIn().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "In", in);
return in;
}
In in = of.createIn().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "In", in);
return in;
}
if (isProper) {
if (dateTimePrecision != null) {
ProperIncludedIn properIncludedIn = of.createProperIncludedIn().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperIncludedIn", properIncludedIn);
return properIncludedIn;
}
ProperIncludedIn properIncludedIn = of.createProperIncludedIn().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "ProperIncludedIn", properIncludedIn);
return properIncludedIn;
}
if (dateTimePrecision != null) {
IncludedIn includedIn = of.createIncludedIn().withPrecision(parseDateTimePrecision(dateTimePrecision))
.withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "IncludedIn", includedIn);
return includedIn;
}
IncludedIn includedIn = of.createIncludedIn().withOperand(timingOperator.getLeft(), timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "IncludedIn", includedIn);
return includedIn;
}
@Override
public Object visitBeforeOrAfterIntervalOperatorPhrase(@NotNull cqlParser.BeforeOrAfterIntervalOperatorPhraseContext ctx) {
// ('starts' | 'ends' | 'occurs')? quantityOffset? ('before' | 'after') dateTimePrecisionSpecifier? ('start' | 'end')?
// duration before/after
// A starts 3 days before start B
//* start of A same day as start of B - 3 days
// A starts 3 days after start B
//* start of A same day as start of B + 3 days
// or more/less duration before/after
// A starts 3 days or more before start B
//* start of A <= start of B - 3 days
// A starts 3 days or more after start B
//* start of A >= start of B + 3 days
// A starts 3 days or less before start B
//* start of A in [start of B - 3 days, start of B)
// A starts 3 days or less after start B
//* start of A in (start of B, start of B + 3 days]
// less/more than duration before/after
// A starts more than 3 days before start B
//* start of A < start of B - 3 days
// A starts more than 3 days after start B
//* start of A > start of B + 3 days
// A starts less than 3 days before start B
//* start of A in (start of B - 3 days, start of B)
// A starts less than 3 days after start B
//* start of A in (start of B, start of B + 3 days)
TimingOperatorContext timingOperator = timingOperators.peek();
boolean isBefore = false;
boolean isInclusive = false;
for (ParseTree child : ctx.children) {
if ("starts".equals(child.getText())) {
Start start = of.createStart().withOperand(timingOperator.getLeft());
track(start, child);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setLeft(start);
continue;
}
if ("ends".equals(child.getText())) {
End end = of.createEnd().withOperand(timingOperator.getLeft());
track(end, child);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setLeft(end);
continue;
}
if ("start".equals(child.getText())) {
Start start = of.createStart().withOperand(timingOperator.getRight());
track(start, child);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setRight(start);
continue;
}
if ("end".equals(child.getText())) {
End end = of.createEnd().withOperand(timingOperator.getRight());
track(end, child);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setRight(end);
continue;
}
}
for (ParseTree child : ctx.temporalRelationship().children) {
if ("before".equals(child.getText())) {
isBefore = true;
continue;
}
if ("on or".equals(child.getText()) || "or on".equals(child.getText())) {
isInclusive = true;
continue;
}
}
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
if (ctx.quantityOffset() == null) {
if (isInclusive) {
if (isBefore) {
SameOrBefore sameOrBefore = of.createSameOrBefore().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
sameOrBefore.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "SameOrBefore", sameOrBefore);
return sameOrBefore;
} else {
SameOrAfter sameOrAfter = of.createSameOrAfter().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
sameOrAfter.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "SameOrAfter", sameOrAfter);
return sameOrAfter;
}
}
else {
if (isBefore) {
Before before = of.createBefore().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
before.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "Before", before);
return before;
} else {
After after = of.createAfter().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
after.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "After", after);
return after;
}
}
} else {
Quantity quantity = (Quantity)visit(ctx.quantityOffset().quantity());
if (timingOperator.getLeft().getResultType() instanceof IntervalType) {
if (isBefore) {
End end = of.createEnd().withOperand(timingOperator.getLeft());
track(end, timingOperator.getLeft());
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setLeft(end);
}
else {
Start start = of.createStart().withOperand(timingOperator.getLeft());
track(start, timingOperator.getLeft());
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setLeft(start);
}
}
if (timingOperator.getRight().getResultType() instanceof IntervalType) {
if (isBefore) {
Start start = of.createStart().withOperand(timingOperator.getRight());
track(start, timingOperator.getRight());
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setRight(start);
}
else {
End end = of.createEnd().withOperand(timingOperator.getRight());
track(end, timingOperator.getRight());
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setRight(end);
}
}
if (ctx.quantityOffset().offsetRelativeQualifier() == null && ctx.quantityOffset().exclusiveRelativeQualifier() == null) {
// Use a SameAs
// For a Before, subtract the quantity from the right operand
// For an After, add the quantity to the right operand
if (isBefore) {
Subtract subtract = of.createSubtract().withOperand(timingOperator.getRight(), quantity);
track(subtract, timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Subtract", subtract);
timingOperator.setRight(subtract);
}
else {
Add add = of.createAdd().withOperand(timingOperator.getRight(), quantity);
track(add, timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Add", add);
timingOperator.setRight(add);
}
SameAs sameAs = of.createSameAs().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
sameAs.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "SameAs", sameAs);
return sameAs;
}
else {
boolean isOffsetInclusive = ctx.quantityOffset().offsetRelativeQualifier() != null;
String qualifier = ctx.quantityOffset().offsetRelativeQualifier() != null
? ctx.quantityOffset().offsetRelativeQualifier().getText()
: ctx.quantityOffset().exclusiveRelativeQualifier().getText();
switch (qualifier) {
case "more than":
case "or more":
// For More Than/Or More, Use a Before/After/SameOrBefore/SameOrAfter
// For a Before, subtract the quantity from the right operand
// For an After, add the quantity to the right operand
if (isBefore) {
Subtract subtract = of.createSubtract().withOperand(timingOperator.getRight(), quantity);
track(subtract, timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Subtract", subtract);
timingOperator.setRight(subtract);
if (!isOffsetInclusive) {
Before before = of.createBefore().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
before.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "Before", before);
return before;
}
else {
SameOrBefore sameOrBefore = of.createSameOrBefore().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
sameOrBefore.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "SameOrBefore", sameOrBefore);
return sameOrBefore;
}
}
else {
Add add = of.createAdd().withOperand(timingOperator.getRight(), quantity);
track(add, timingOperator.getRight());
libraryBuilder.resolveBinaryCall("System", "Add", add);
timingOperator.setRight(add);
if (!isOffsetInclusive) {
After after = of.createAfter().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
after.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "After", after);
return after;
}
else {
SameOrAfter sameOrAfter = of.createSameOrAfter().withOperand(timingOperator.getLeft(), timingOperator.getRight());
if (dateTimePrecision != null) {
sameOrAfter.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
libraryBuilder.resolveBinaryCall("System", "SameOrAfter", sameOrAfter);
return sameOrAfter;
}
}
case "less than":
case "or less":
// For Less Than/Or Less, Use an In
// For Before, construct an interval from right - quantity to right
// For After, construct an interval from right to right + quantity
Expression lowerBound = null;
Expression upperBound = null;
Expression right = timingOperator.getRight();
if (isBefore) {
lowerBound = of.createSubtract().withOperand(right, quantity);
track(lowerBound, right);
libraryBuilder.resolveBinaryCall("System", "Subtract", (BinaryExpression)lowerBound);
upperBound = right;
}
else {
lowerBound = right;
upperBound = of.createAdd().withOperand(right, quantity);
track(upperBound, right);
libraryBuilder.resolveBinaryCall("System", "Add", (BinaryExpression)upperBound);
}
// 3 days or less before -> [B - 3 days, B)
// less than 3 days before -> (B - 3 days, B)
// 3 days or less after -> (B, B + 3 days]
// less than 3 days after -> (B, B + 3 days)
Interval interval =
isBefore
? libraryBuilder.createInterval(lowerBound, isOffsetInclusive, upperBound, isInclusive)
: libraryBuilder.createInterval(lowerBound, isInclusive, upperBound, isOffsetInclusive);
track(interval, ctx.quantityOffset());
In in = of.createIn().withOperand(timingOperator.getLeft(), interval);
if (dateTimePrecision != null) {
in.setPrecision(parseDateTimePrecision(dateTimePrecision));
}
track(in, ctx.quantityOffset());
libraryBuilder.resolveBinaryCall("System", "In", in);
return in;
}
}
}
throw new IllegalArgumentException("Unable to resolve interval operator phrase.");
}
private BinaryExpression resolveBetweenOperator(String unit, Expression left, Expression right) {
if (unit != null) {
DurationBetween between = of.createDurationBetween().withPrecision(parseDateTimePrecision(unit)).withOperand(left, right);
libraryBuilder.resolveBinaryCall("System", "DurationBetween", between);
return between;
}
return null;
}
@Override
public Object visitWithinIntervalOperatorPhrase(@NotNull cqlParser.WithinIntervalOperatorPhraseContext ctx) {
// ('starts' | 'ends' | 'occurs')? 'properly'? 'within' quantityLiteral 'of' ('start' | 'end')?
// A starts within 3 days of start B
//* start of A in [start of B - 3 days, start of B + 3 days]
// A starts within 3 days of B
//* start of A in [start of B - 3 days, end of B + 3 days]
TimingOperatorContext timingOperator = timingOperators.peek();
boolean isProper = false;
for (ParseTree child : ctx.children) {
if ("starts".equals(child.getText())) {
Start start = of.createStart().withOperand(timingOperator.getLeft());
track(start, child);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setLeft(start);
continue;
}
if ("ends".equals(child.getText())) {
End end = of.createEnd().withOperand(timingOperator.getLeft());
track(end, child);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setLeft(end);
continue;
}
if ("start".equals(child.getText())) {
Start start = of.createStart().withOperand(timingOperator.getRight());
track(start, child);
libraryBuilder.resolveUnaryCall("System", "Start", start);
timingOperator.setRight(start);
continue;
}
if ("end".equals(child.getText())) {
End end = of.createEnd().withOperand(timingOperator.getRight());
track(end, child);
libraryBuilder.resolveUnaryCall("System", "End", end);
timingOperator.setRight(end);
continue;
}
if ("properly".equals(child.getText())) {
isProper = true;
continue;
}
}
Quantity quantity = (Quantity)visit(ctx.quantity());
Expression lowerBound = null;
Expression upperBound = null;
if (timingOperator.getRight().getResultType() instanceof IntervalType) {
lowerBound = of.createStart().withOperand(timingOperator.getRight());
track(lowerBound, ctx.quantity());
libraryBuilder.resolveUnaryCall("System", "Start", (Start)lowerBound);
upperBound = of.createEnd().withOperand(timingOperator.getRight());
track(upperBound, ctx.quantity());
libraryBuilder.resolveUnaryCall("System", "End", (End)upperBound);
}
else {
lowerBound = timingOperator.getRight();
upperBound = timingOperator.getRight();
}
lowerBound = of.createSubtract().withOperand(lowerBound, quantity);
track(lowerBound, ctx.quantity());
libraryBuilder.resolveBinaryCall("System", "Subtract", (BinaryExpression)lowerBound);
upperBound = of.createAdd().withOperand(upperBound, quantity);
track(upperBound, ctx.quantity());
libraryBuilder.resolveBinaryCall("System", "Add", (BinaryExpression)upperBound);
Interval interval = libraryBuilder.createInterval(lowerBound, !isProper, upperBound, !isProper);
track(interval, ctx.quantity());
In in = of.createIn().withOperand(timingOperator.getLeft(), interval);
libraryBuilder.resolveBinaryCall("System", "In", in);
return in;
}
@Override
public Object visitMeetsIntervalOperatorPhrase(@NotNull cqlParser.MeetsIntervalOperatorPhraseContext ctx) {
String operatorName = null;
BinaryExpression operator;
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
if (ctx.getChildCount() == (1 + (dateTimePrecision == null ? 0 : 1))) {
operator = dateTimePrecision != null
? of.createMeets().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createMeets();
operatorName = "Meets";
} else {
if ("before".equals(ctx.getChild(1).getText())) {
operator = dateTimePrecision != null
? of.createMeetsBefore().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createMeetsBefore();
operatorName = "MeetsBefore";
} else {
operator = dateTimePrecision != null
? of.createMeetsAfter().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createMeetsAfter();
operatorName = "MeetsAfter";
}
}
operator.withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight());
libraryBuilder.resolveBinaryCall("System", operatorName, operator);
return operator;
}
@Override
public Object visitOverlapsIntervalOperatorPhrase(@NotNull cqlParser.OverlapsIntervalOperatorPhraseContext ctx) {
String operatorName = null;
BinaryExpression operator;
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
if (ctx.getChildCount() == (1 + (dateTimePrecision == null ? 0 : 1))) {
operator = dateTimePrecision != null
? of.createOverlaps().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createOverlaps();
operatorName = "Overlaps";
} else {
if ("before".equals(ctx.getChild(1).getText())) {
operator = dateTimePrecision != null
? of.createOverlapsBefore().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createOverlapsBefore();
operatorName = "OverlapsBefore";
} else {
operator = dateTimePrecision != null
? of.createOverlapsAfter().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createOverlapsAfter();
operatorName = "OverlapsAfter";
}
}
operator.withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight());
libraryBuilder.resolveBinaryCall("System", operatorName, operator);
return operator;
}
@Override
public Object visitStartsIntervalOperatorPhrase(@NotNull cqlParser.StartsIntervalOperatorPhraseContext ctx) {
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
Starts starts = (dateTimePrecision != null
? of.createStarts().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createStarts()
).withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight());
libraryBuilder.resolveBinaryCall("System", "Starts", starts);
return starts;
}
@Override
public Object visitEndsIntervalOperatorPhrase(@NotNull cqlParser.EndsIntervalOperatorPhraseContext ctx) {
String dateTimePrecision = ctx.dateTimePrecisionSpecifier() != null
? ctx.dateTimePrecisionSpecifier().dateTimePrecision().getText()
: null;
Ends ends = (dateTimePrecision != null
? of.createEnds().withPrecision(parseDateTimePrecision(dateTimePrecision))
: of.createEnds()
).withOperand(timingOperators.peek().getLeft(), timingOperators.peek().getRight());
libraryBuilder.resolveBinaryCall("System", "Ends", ends);
return ends;
}
public Expression resolveIfThenElse(If ifObject) {
ifObject.setCondition(libraryBuilder.convertExpression(ifObject.getCondition(), libraryBuilder.resolveTypeName("System", "Boolean")));
DataType resultType = libraryBuilder.ensureCompatibleTypes(ifObject.getThen().getResultType(), ifObject.getElse().getResultType());
ifObject.setResultType(resultType);
ifObject.setThen(libraryBuilder.ensureCompatible(ifObject.getThen(), resultType));
ifObject.setElse(libraryBuilder.ensureCompatible(ifObject.getElse(), resultType));
return ifObject;
}
@Override
public Object visitIfThenElseExpressionTerm(@NotNull cqlParser.IfThenElseExpressionTermContext ctx) {
If ifObject = of.createIf()
.withCondition(parseExpression(ctx.expression(0)))
.withThen(parseExpression(ctx.expression(1)))
.withElse(parseExpression(ctx.expression(2)));
return resolveIfThenElse(ifObject);
}
@Override
public Object visitCaseExpressionTerm(@NotNull cqlParser.CaseExpressionTermContext ctx) {
Case result = of.createCase();
Boolean hitElse = false;
DataType resultType = null;
for (ParseTree pt : ctx.children) {
if ("else".equals(pt.getText())) {
hitElse = true;
continue;
}
if (pt instanceof cqlParser.ExpressionContext) {
if (hitElse) {
result.setElse(parseExpression(pt));
resultType = libraryBuilder.ensureCompatibleTypes(resultType, result.getElse().getResultType());
} else {
result.setComparand(parseExpression(pt));
}
}
if (pt instanceof cqlParser.CaseExpressionItemContext) {
CaseItem caseItem = (CaseItem)visit(pt);
if (result.getComparand() != null) {
libraryBuilder.verifyType(caseItem.getWhen().getResultType(), result.getComparand().getResultType());
}
else {
DataTypes.verifyType(caseItem.getWhen().getResultType(), libraryBuilder.resolveTypeName("System", "Boolean"));
}
if (resultType == null) {
resultType = caseItem.getThen().getResultType();
}
else {
resultType = libraryBuilder.ensureCompatibleTypes(resultType, caseItem.getThen().getResultType());
}
result.getCaseItem().add(caseItem);
}
}
for (CaseItem caseItem : result.getCaseItem()) {
if (result.getComparand() != null) {
caseItem.setWhen(libraryBuilder.ensureCompatible(caseItem.getWhen(), result.getComparand().getResultType()));
}
caseItem.setThen(libraryBuilder.ensureCompatible(caseItem.getThen(), resultType));
}
result.setElse(libraryBuilder.ensureCompatible(result.getElse(), resultType));
result.setResultType(resultType);
return result;
}
@Override
public Object visitCaseExpressionItem(@NotNull cqlParser.CaseExpressionItemContext ctx) {
return of.createCaseItem()
.withWhen(parseExpression(ctx.expression(0)))
.withThen(parseExpression(ctx.expression(1)));
}
@Override
public Object visitAggregateExpressionTerm(@NotNull cqlParser.AggregateExpressionTermContext ctx) {
switch (ctx.getChild(0).getText()) {
case "distinct":
Distinct distinct = of.createDistinct().withOperand(parseExpression(ctx.expression()));
libraryBuilder.resolveUnaryCall("System", "Distinct", distinct);
return distinct;
case "collapse":
Collapse collapse = of.createCollapse().withOperand(parseExpression(ctx.expression()));
libraryBuilder.resolveUnaryCall("System", "Collapse", collapse);
return collapse;
case "flatten":
Flatten flatten = of.createFlatten().withOperand(parseExpression(ctx.expression()));
libraryBuilder.resolveUnaryCall("System", "Flatten", flatten);
return flatten;
}
throw new IllegalArgumentException(String.format("Unknown aggregate operator %s.", ctx.getChild(0).getText()));
}
@Override
public Retrieve visitRetrieve(@NotNull cqlParser.RetrieveContext ctx) {
String model = parseString(ctx.namedTypeSpecifier().modelIdentifier());
String label = parseString(ctx.namedTypeSpecifier().identifier());
DataType dataType = libraryBuilder.resolveTypeName(model, label);
if (dataType == null) {
throw new IllegalArgumentException(String.format("Could not resolve type name %s.", label));
}
if (!(dataType instanceof ClassType) || !((ClassType)dataType).isRetrievable()) {
throw new IllegalArgumentException(String.format("Specified data type %s does not support retrieval.", label));
}
ClassType classType = (ClassType)dataType;
// BTR -> The original intent of this code was to have the retrieve return the base type, and use the "templateId"
// element of the retrieve to communicate the "positive" or "negative" profile to the data access layer.
// However, because this notion of carrying the "profile" through a type is not general, it causes inconsistencies
// when using retrieve results with functions defined in terms of the same type (see GitHub Issue #131).
// Based on the discussion there, the retrieve will now return the declared type, whether it is a profile or not.
//ProfileType profileType = dataType instanceof ProfileType ? (ProfileType)dataType : null;
//NamedType namedType = profileType == null ? classType : (NamedType)classType.getBaseType();
NamedType namedType = classType;
ModelInfo modelInfo = libraryBuilder.getModel(namedType.getNamespace()).getModelInfo();
boolean useStrictRetrieveTyping = modelInfo.isStrictRetrieveTyping() != null && modelInfo.isStrictRetrieveTyping();
Retrieve retrieve = of.createRetrieve()
.withDataType(libraryBuilder.dataTypeToQName((DataType)namedType))
.withTemplateId(classType.getIdentifier());
if (ctx.terminology() != null) {
if (ctx.codePath() != null) {
retrieve.setCodeProperty(parseString(ctx.codePath()));
} else if (classType.getPrimaryCodePath() != null) {
retrieve.setCodeProperty(classType.getPrimaryCodePath());
}
Property property = null;
if (retrieve.getCodeProperty() == null) {
libraryBuilder.recordParsingException(new CqlSemanticException("Retrieve has a terminology target but does not specify a code path and the type of the retrieve does not have a primary code path defined.",
useStrictRetrieveTyping ? CqlTranslatorException.ErrorSeverity.Error : CqlTranslatorException.ErrorSeverity.Warning,
getTrackBack(ctx)));
}
else {
try {
DataType codeType = libraryBuilder.resolvePath((DataType) namedType, retrieve.getCodeProperty());
property = of.createProperty().withPath(retrieve.getCodeProperty());
property.setResultType(codeType);
}
catch (Exception e) {
libraryBuilder.recordParsingException(new CqlSemanticException(String.format("Could not resolve code path %s for the type of the retrieve %s.",
retrieve.getCodeProperty(), namedType.getName()), useStrictRetrieveTyping ? CqlTranslatorException.ErrorSeverity.Error : CqlTranslatorException.ErrorSeverity.Warning,
getTrackBack(ctx), e));
}
}
Expression terminology = null;
if (ctx.terminology().qualifiedIdentifier() != null) {
List<String> identifiers = (List<String>) visit(ctx.terminology());
terminology = resolveQualifiedIdentifier(identifiers);
}
else {
terminology = parseExpression(ctx.terminology().expression());
}
// Resolve the terminology target using an in or = operator
try {
if (terminology.getResultType() instanceof ListType) {
Expression in = libraryBuilder.resolveIn(property, terminology);
if (in instanceof In) {
retrieve.setCodes(((In) in).getOperand().get(1));
} else if (in instanceof InValueSet) {
retrieve.setCodes(((InValueSet) in).getValueset());
} else if (in instanceof InCodeSystem) {
retrieve.setCodes(((InCodeSystem) in).getCodesystem());
} else {
libraryBuilder.recordParsingException(new CqlSemanticException(String.format("Unexpected membership operator %s in retrieve", in.getClass().getSimpleName()),
useStrictRetrieveTyping ? CqlTranslatorException.ErrorSeverity.Error : CqlTranslatorException.ErrorSeverity.Warning,
getTrackBack(ctx)));
}
}
else {
// Resolve with equality to verify the type of the target
BinaryExpression equal = of.createEqual().withOperand(property, terminology);
libraryBuilder.resolveBinaryCall("System", "Equal", equal);
// Automatically promote to a list for use in the retrieve target
retrieve.setCodes(libraryBuilder.resolveToList(equal.getOperand().get(1)));
}
}
catch (Exception e) {
// If something goes wrong attempting to resolve, just set to the expression and report it as a warning,
// it shouldn't prevent translation unless the modelinfo indicates strict retrieve typing
retrieve.setCodes(terminology);
libraryBuilder.recordParsingException(new CqlSemanticException("Could not resolve membership operator for terminology target of the retrieve.",
useStrictRetrieveTyping ? CqlTranslatorException.ErrorSeverity.Error : CqlTranslatorException.ErrorSeverity.Warning,
getTrackBack(ctx), e));
}
}
retrieves.add(retrieve);
retrieve.setResultType(new ListType((DataType) namedType));
return retrieve;
}
@Override
public Object visitSingleSourceClause(@NotNull cqlParser.SingleSourceClauseContext ctx) {
List<AliasedQuerySource> sources = new ArrayList<>();
sources.add((AliasedQuerySource) visit(ctx.aliasedQuerySource()));
return sources;
}
@Override
public Object visitMultipleSourceClause(@NotNull cqlParser.MultipleSourceClauseContext ctx) {
List<AliasedQuerySource> sources = new ArrayList<>();
for (cqlParser.AliasedQuerySourceContext source : ctx.aliasedQuerySource()) {
sources.add((AliasedQuerySource) visit(source));
}
return sources;
}
@Override
public Object visitQuery(@NotNull cqlParser.QueryContext ctx) {
QueryContext queryContext = new QueryContext();
libraryBuilder.pushQueryContext(queryContext);
try {
List<AliasedQuerySource> sources;
queryContext.enterSourceClause();
try {
sources = (List<AliasedQuerySource>)visit(ctx.sourceClause());
}
finally {
queryContext.exitSourceClause();
}
queryContext.addPrimaryQuerySources(sources);
// If we are evaluating a population-level query whose source ranges over any patient-context expressions,
// then references to patient context expressions within the iteration clauses of the query can be accessed
// at the patient, rather than the population, context.
boolean expressionContextPushed = false;
if (libraryBuilder.inPopulationContext() && queryContext.referencesPatientContext()) {
libraryBuilder.pushExpressionContext("Patient");
expressionContextPushed = true;
}
try {
List<LetClause> dfcx = ctx.letClause() != null ? (List<LetClause>) visit(ctx.letClause()) : null;
List<RelationshipClause> qicx = new ArrayList<>();
if (ctx.queryInclusionClause() != null) {
for (cqlParser.QueryInclusionClauseContext queryInclusionClauseContext : ctx.queryInclusionClause()) {
qicx.add((RelationshipClause) visit(queryInclusionClauseContext));
}
}
Expression where = ctx.whereClause() != null ? (Expression) visit(ctx.whereClause()) : null;
if (dateRangeOptimization && where != null) {
for (AliasedQuerySource aqs : sources) {
where = optimizeDateRangeInQuery(where, aqs);
}
}
ReturnClause ret = ctx.returnClause() != null ? (ReturnClause) visit(ctx.returnClause()) : null;
if ((ret == null) && (sources.size() > 1)) {
ret = of.createReturnClause()
.withDistinct(true);
Tuple returnExpression = of.createTuple();
TupleType returnType = new TupleType();
for (AliasedQuerySource aqs : sources) {
TupleElement element =
of.createTupleElement()
.withName(aqs.getAlias())
.withValue(of.createAliasRef().withName(aqs.getAlias()));
DataType sourceType = aqs.getResultType() instanceof ListType ? ((ListType)aqs.getResultType()).getElementType() : aqs.getResultType();
element.getValue().setResultType(sourceType); // Doesn't use the fluent API to avoid casting
element.setResultType(element.getValue().getResultType());
returnType.addElement(new TupleTypeElement(element.getName(), element.getResultType()));
returnExpression.getElement().add(element);
}
returnExpression.setResultType(queryContext.isSingular() ? returnType : new ListType(returnType));
ret.setExpression(returnExpression);
ret.setResultType(returnExpression.getResultType());
}
queryContext.removeQuerySources(sources);
if (dfcx != null) {
queryContext.removeLetClauses(dfcx);
}
DataType queryResultType = ret == null ? sources.get(0).getResultType() : ret.getResultType();
queryContext.setResultElementType(queryContext.isSingular() ? null : ((ListType)queryResultType).getElementType());
SortClause sort = null;
if (ctx.sortClause() != null) {
if (queryContext.isSingular()) {
throw new IllegalArgumentException("Sort clause cannot be used in a singular query.");
}
queryContext.enterSortClause();
try {
sort = (SortClause)visit(ctx.sortClause());
// Validate that the sort can be performed based on the existence of comparison operators for all types involved
for (SortByItem sortByItem : sort.getBy()) {
if (sortByItem instanceof ByDirection) {
// validate that there is a comparison operator defined for the result element type of the query context
libraryBuilder.verifyComparable(queryContext.getResultElementType()); }
else {
libraryBuilder.verifyComparable(sortByItem.getResultType());
}
}
}
finally {
queryContext.exitSortClause();
}
}
Query query = of.createQuery()
.withSource(sources)
.withLet(dfcx)
.withRelationship(qicx)
.withWhere(where)
.withReturn(ret)
.withSort(sort);
query.setResultType(queryResultType);
return query;
}
finally {
if (expressionContextPushed) {
libraryBuilder.popExpressionContext();
}
}
} finally {
libraryBuilder.popQueryContext();
}
}
// TODO: Expand this optimization to work the DateLow/DateHigh property attributes
/**
* Some systems may wish to optimize performance by restricting retrieves with available date ranges. Specifying
* date ranges in a retrieve was removed from the CQL grammar, but it is still possible to extract date ranges from
* the where clause and put them in the Retrieve in ELM. The <code>optimizeDateRangeInQuery</code> method
* attempts to do this automatically. If optimization is possible, it will remove the corresponding "during" from
* the where clause and insert the date range into the Retrieve.
*
* @param aqs the AliasedQuerySource containing the ClinicalRequest to possibly refactor a date range into.
* @param where the Where clause to search for potential date range optimizations
* @return the where clause with optimized "durings" removed, or <code>null</code> if there is no longer a Where
* clause after optimization.
*/
public Expression optimizeDateRangeInQuery(Expression where, AliasedQuerySource aqs) {
if (aqs.getExpression() instanceof Retrieve) {
Retrieve retrieve = (Retrieve) aqs.getExpression();
String alias = aqs.getAlias();
if ((where instanceof IncludedIn || where instanceof In) && attemptDateRangeOptimization((BinaryExpression) where, retrieve, alias)) {
where = null;
}
else if (where instanceof And && attemptDateRangeOptimization((And) where, retrieve, alias)) {
// Now optimize out the trues from the Ands
where = consolidateAnd((And) where);
}
}
return where;
}
/**
* Test a <code>BinaryExpression</code> expression and determine if it is suitable to be refactored into the
* <code>Retrieve</code> as a date range restriction. If so, adjust the <code>Retrieve</code>
* accordingly and return <code>true</code>.
*
* @param during the <code>BinaryExpression</code> expression to potentially refactor into the <code>Retrieve</code>
* @param retrieve the <code>Retrieve</code> to add qualifying date ranges to (if applicable)
* @param alias the alias of the <code>Retrieve</code> in the query.
* @return <code>true</code> if the date range was set in the <code>Retrieve</code>; <code>false</code>
* otherwise.
*/
private boolean attemptDateRangeOptimization(BinaryExpression during, Retrieve retrieve, String alias) {
if (retrieve.getDateProperty() != null || retrieve.getDateRange() != null) {
return false;
}
Expression left = during.getOperand().get(0);
Expression right = during.getOperand().get(1);
String propertyPath = getPropertyPath(left, alias);
if (propertyPath != null && isRHSEligibleForDateRangeOptimization(right)) {
retrieve.setDateProperty(propertyPath);
retrieve.setDateRange(right);
return true;
}
return false;
}
/**
* Collapse a property path expression back to it's qualified form for use as the path attribute of the retrieve.
*
* @param reference the <code>Expression</code> to collapse
* @param alias the alias of the <code>Retrieve</code> in the query.
* @return The collapsed path
* operands (or sub-operands) were modified; <code>false</code> otherwise.
*/
private String getPropertyPath(Expression reference, String alias) {
if (reference instanceof Property) {
Property property = (Property)reference;
if (alias.equals(property.getScope())) {
return property.getPath();
}
else if (property.getSource() != null) {
String subPath = getPropertyPath(property.getSource(), alias);
if (subPath != null) {
return String.format("%s.%s", subPath, property.getPath());
}
}
}
return null;
}
/**
* Test an <code>And</code> expression and determine if it contains any operands (first-level or nested deeper)
* than are <code>IncludedIn</code> expressions that can be refactored into a <code>Retrieve</code>. If so,
* adjust the <code>Retrieve</code> accordingly and reset the corresponding operand to a literal
* <code>true</code>. This <code>and</code> branch containing a <code>true</code> can be further consolidated
* later.
*
* @param and the <code>And</code> expression containing operands to potentially refactor into the
* <code>Retrieve</code>
* @param retrieve the <code>Retrieve</code> to add qualifying date ranges to (if applicable)
* @param alias the alias of the <code>Retrieve</code> in the query.
* @return <code>true</code> if the date range was set in the <code>Retrieve</code> and the <code>And</code>
* operands (or sub-operands) were modified; <code>false</code> otherwise.
*/
private boolean attemptDateRangeOptimization(And and, Retrieve retrieve, String alias) {
if (retrieve.getDateProperty() != null || retrieve.getDateRange() != null) {
return false;
}
for (int i = 0; i < and.getOperand().size(); i++) {
Expression operand = and.getOperand().get(i);
if ((operand instanceof IncludedIn || operand instanceof In) && attemptDateRangeOptimization((BinaryExpression) operand, retrieve, alias)) {
// Replace optimized part in And with true -- to be optimized out later
and.getOperand().set(i, libraryBuilder.createLiteral(true));
return true;
} else if (operand instanceof And && attemptDateRangeOptimization((And) operand, retrieve, alias)) {
return true;
}
}
return false;
}
/**
* If any branches in the <code>And</code> tree contain a <code>true</code>, refactor it out.
*
* @param and the <code>And</code> tree to attempt to consolidate
* @return the potentially consolidated <code>And</code>
*/
private Expression consolidateAnd(And and) {
Expression result = and;
Expression lhs = and.getOperand().get(0);
Expression rhs = and.getOperand().get(1);
if (isBooleanLiteral(lhs, true)) {
result = rhs;
} else if (isBooleanLiteral(rhs, true)) {
result = lhs;
} else if (lhs instanceof And) {
and.getOperand().set(0, consolidateAnd((And) lhs));
} else if (rhs instanceof And) {
and.getOperand().set(1, consolidateAnd((And) rhs));
}
return result;
}
/**
* Determine if the right-hand side of an <code>IncludedIn</code> expression can be refactored into the date range
* of a <code>Retrieve</code>. Currently, refactoring is only supported when the RHS is a literal
* DateTime interval, a literal DateTime, a parameter representing a DateTime interval or a DateTime, or an
* expression reference representing a DateTime interval or a DateTime.
*
* @param rhs the right-hand side of the <code>IncludedIn</code> to test for potential optimization
* @return <code>true</code> if the RHS supports refactoring to a <code>Retrieve</code>, <code>false</code>
* otherwise.
*/
private boolean isRHSEligibleForDateRangeOptimization(Expression rhs) {
return
rhs.getResultType().isSubTypeOf(libraryBuilder.resolveTypeName("System", "DateTime"))
|| rhs.getResultType().isSubTypeOf(new IntervalType(libraryBuilder.resolveTypeName("System", "DateTime")));
// BTR: The only requirement for the optimization is that the expression be of type DateTime or Interval<DateTime>
// Whether or not the expression can be statically evaluated (literal, in the loose sense of the word) is really
// a function of the engine in determining the "initial" data requirements, versus subsequent data requirements
// Element targetElement = rhs;
// if (rhs instanceof ParameterRef) {
// String paramName = ((ParameterRef) rhs).getName();
// for (ParameterDef def : getLibrary().getParameters().getDef()) {
// if (paramName.equals(def.getName())) {
// targetElement = def.getParameterTypeSpecifier();
// if (targetElement == null) {
// targetElement = def.getDefault();
// }
// break;
// }
// }
// } else if (rhs instanceof ExpressionRef && !(rhs instanceof FunctionRef)) {
// // TODO: Support forward declaration, if necessary
// String expName = ((ExpressionRef) rhs).getName();
// for (ExpressionDef def : getLibrary().getStatements().getDef()) {
// if (expName.equals(def.getName())) {
// targetElement = def.getExpression();
// }
// }
// }
//
// boolean isEligible = false;
// if (targetElement instanceof DateTime) {
// isEligible = true;
// } else if (targetElement instanceof Interval) {
// Interval ivl = (Interval) targetElement;
// isEligible = (ivl.getLow() != null && ivl.getLow() instanceof DateTime) || (ivl.getHigh() != null && ivl.getHigh() instanceof DateTime);
// } else if (targetElement instanceof IntervalTypeSpecifier) {
// IntervalTypeSpecifier spec = (IntervalTypeSpecifier) targetElement;
// isEligible = isDateTimeTypeSpecifier(spec.getPointType());
// } else if (targetElement instanceof NamedTypeSpecifier) {
// isEligible = isDateTimeTypeSpecifier(targetElement);
// }
// return isEligible;
}
private boolean isDateTimeTypeSpecifier(Element e) {
return e.getResultType().equals(libraryBuilder.resolveTypeName("System", "DateTime"));
}
@Override
public Object visitLetClause(@NotNull cqlParser.LetClauseContext ctx) {
List<LetClause> letClauseItems = new ArrayList<>();
for (cqlParser.LetClauseItemContext letClauseItem : ctx.letClauseItem()) {
letClauseItems.add((LetClause) visit(letClauseItem));
}
return letClauseItems;
}
@Override
public Object visitLetClauseItem(@NotNull cqlParser.LetClauseItemContext ctx) {
LetClause letClause = of.createLetClause().withExpression(parseExpression(ctx.expression()))
.withIdentifier(parseString(ctx.identifier()));
letClause.setResultType(letClause.getExpression().getResultType());
libraryBuilder.peekQueryContext().addLetClause(letClause);
return letClause;
}
@Override
public Object visitAliasedQuerySource(@NotNull cqlParser.AliasedQuerySourceContext ctx) {
AliasedQuerySource source = of.createAliasedQuerySource().withExpression(parseExpression(ctx.querySource()))
.withAlias(parseString(ctx.alias()));
source.setResultType(source.getExpression().getResultType());
return source;
}
@Override
public Object visitWithClause(@NotNull cqlParser.WithClauseContext ctx) {
AliasedQuerySource aqs = (AliasedQuerySource) visit(ctx.aliasedQuerySource());
libraryBuilder.peekQueryContext().addRelatedQuerySource(aqs);
try {
Expression expression = (Expression) visit(ctx.expression());
DataTypes.verifyType(expression.getResultType(), libraryBuilder.resolveTypeName("System", "Boolean"));
RelationshipClause result = of.createWith();
result.withExpression(aqs.getExpression()).withAlias(aqs.getAlias()).withSuchThat(expression);
result.setResultType(aqs.getResultType());
return result;
} finally {
libraryBuilder.peekQueryContext().removeQuerySource(aqs);
}
}
@Override
public Object visitWithoutClause(@NotNull cqlParser.WithoutClauseContext ctx) {
AliasedQuerySource aqs = (AliasedQuerySource) visit(ctx.aliasedQuerySource());
libraryBuilder.peekQueryContext().addRelatedQuerySource(aqs);
try {
Expression expression = (Expression) visit(ctx.expression());
DataTypes.verifyType(expression.getResultType(), libraryBuilder.resolveTypeName("System", "Boolean"));
RelationshipClause result = of.createWithout();
result.withExpression(aqs.getExpression()).withAlias(aqs.getAlias()).withSuchThat(expression);
result.setResultType(aqs.getResultType());
return result;
} finally {
libraryBuilder.peekQueryContext().removeQuerySource(aqs);
}
}
@Override
public Object visitWhereClause(@NotNull cqlParser.WhereClauseContext ctx) {
Expression result = (Expression)visit(ctx.expression());
DataTypes.verifyType(result.getResultType(), libraryBuilder.resolveTypeName("System", "Boolean"));
return result;
}
@Override
public Object visitReturnClause(@NotNull cqlParser.ReturnClauseContext ctx) {
ReturnClause returnClause = of.createReturnClause();
if (ctx.getChild(1) instanceof TerminalNode) {
switch (ctx.getChild(1).getText()) {
case "all":
returnClause.setDistinct(false);
break;
case "distinct":
returnClause.setDistinct(true);
break;
default:
break;
}
}
returnClause.setExpression(parseExpression(ctx.expression()));
returnClause.setResultType(libraryBuilder.peekQueryContext().isSingular()
? returnClause.getExpression().getResultType()
: new ListType(returnClause.getExpression().getResultType()));
return returnClause;
}
@Override
public SortDirection visitSortDirection(@NotNull cqlParser.SortDirectionContext ctx) {
if (ctx.getText().equals("desc")) {
return SortDirection.DESC;
}
return SortDirection.ASC;
}
private SortDirection parseSortDirection(cqlParser.SortDirectionContext ctx) {
if (ctx != null) {
return visitSortDirection(ctx);
}
return SortDirection.ASC;
}
@Override
public SortByItem visitSortByItem(@NotNull cqlParser.SortByItemContext ctx) {
Expression sortExpression = parseExpression(ctx.expressionTerm());
if (sortExpression instanceof IdentifierRef) {
return (SortByItem)of.createByColumn()
.withPath(((IdentifierRef)sortExpression).getName())
.withDirection(parseSortDirection(ctx.sortDirection()))
.withResultType(sortExpression.getResultType());
}
return (SortByItem)of.createByExpression()
.withExpression(sortExpression)
.withDirection(parseSortDirection(ctx.sortDirection()))
.withResultType(sortExpression.getResultType());
}
@Override
public Object visitSortClause(@NotNull cqlParser.SortClauseContext ctx) {
if (ctx.sortDirection() != null) {
return of.createSortClause()
.withBy(of.createByDirection().withDirection(parseSortDirection(ctx.sortDirection())));
}
List<SortByItem> sortItems = new ArrayList<>();
if (ctx.sortByItem() != null) {
for (cqlParser.SortByItemContext sortByItemContext : ctx.sortByItem()) {
sortItems.add((SortByItem) visit(sortByItemContext));
}
}
return of.createSortClause().withBy(sortItems);
}
@Override
public Object visitQuerySource(@NotNull cqlParser.QuerySourceContext ctx) {
if (ctx.expression() != null) {
return visit(ctx.expression());
} else if (ctx.retrieve() != null) {
return visit(ctx.retrieve());
} else {
List<String> identifiers = (List<String>) visit(ctx.qualifiedIdentifier());
return resolveQualifiedIdentifier(identifiers);
}
}
@Override
public Object visitIndexedExpressionTerm(@NotNull cqlParser.IndexedExpressionTermContext ctx) {
Indexer indexer = of.createIndexer()
.withOperand(parseExpression(ctx.expressionTerm()))
.withOperand(parseExpression(ctx.expression()));
// TODO: Support zero-based indexers as defined by the isZeroBased attribute
libraryBuilder.resolveBinaryCall("System", "Indexer", indexer);
return indexer;
}
@Override
public Expression visitInvocationExpressionTerm(@NotNull cqlParser.InvocationExpressionTermContext ctx) {
Expression left = parseExpression(ctx.expressionTerm());
libraryBuilder.pushExpressionTarget(left);
try {
return (Expression)visit(ctx.invocation());
}
finally {
libraryBuilder.popExpressionTarget();
}
}
@Override
public Expression visitExternalConstant(@NotNull cqlParser.ExternalConstantContext ctx) {
return libraryBuilder.resolveIdentifier(ctx.getText(), true);
}
@Override
public Expression visitThisInvocation(@NotNull cqlParser.ThisInvocationContext ctx) {
return libraryBuilder.resolveIdentifier(ctx.getText(), true);
}
@Override
public Expression visitMemberInvocation(@NotNull cqlParser.MemberInvocationContext ctx) {
String identifier = parseString(ctx.identifier());
if (libraryBuilder.hasExpressionTarget()) {
Expression target = libraryBuilder.popExpressionTarget();
try {
return libraryBuilder.resolveAccessor(target, identifier);
}
finally {
libraryBuilder.pushExpressionTarget(target);
}
}
return resolveIdentifier(identifier);
}
public Expression resolveQualifiedIdentifier(List<String> identifiers) {
Expression current = null;
for (String identifier : identifiers) {
if (current == null) {
current = resolveIdentifier(identifier);
} else {
current = libraryBuilder.resolveAccessor(current, identifier);
}
}
return current;
}
private Expression resolveIdentifier(String identifier) {
// If the identifier cannot be resolved in the library builder, check for forward declarations for expressions and parameters
Expression result = libraryBuilder.resolveIdentifier(identifier, false);
if (result == null) {
ExpressionDefinitionInfo expressionInfo = libraryInfo.resolveExpressionReference(identifier);
if (expressionInfo != null) {
String saveContext = currentContext;
currentContext = expressionInfo.getContext();
try {
Stack<Chunk> saveChunks = chunks;
chunks = new Stack<Chunk>();
forwards.push(expressionInfo);
try {
// Have to call the visit to get the outer processing to occur
visit(expressionInfo.getDefinition());
}
finally {
chunks = saveChunks;
forwards.pop();
}
} finally {
currentContext = saveContext;
}
}
ParameterDefinitionInfo parameterInfo = libraryInfo.resolveParameterReference(identifier);
if (parameterInfo != null) {
visitParameterDefinition(parameterInfo.getDefinition());
}
result = libraryBuilder.resolveIdentifier(identifier, true);
}
return result;
}
private Expression resolveFunction(String libraryName, @NotNull cqlParser.FunctionContext ctx) {
String functionName = parseString(ctx.identifier());
if ((libraryName == null || libraryName.equals("System")) && functionName.equals("distinct")) {
// Because distinct can be both a keyword and the name of a method, it can be resolved by the
// parser as a function, instead of as an aggregateExpressionTerm. In this case, the function
// name needs to be translated to the System function name in order to resolve.
functionName = "Distinct";
}
return resolveFunction(libraryName, functionName, ctx.paramList());
}
private Expression resolveFunction(String libraryName, String functionName, cqlParser.ParamListContext paramList) {
List<Expression> expressions = new ArrayList<Expression>();
if (paramList != null && paramList.expression() != null) {
for (cqlParser.ExpressionContext expressionContext : paramList.expression()) {
expressions.add((Expression)visit(expressionContext));
}
}
// If the function cannot be resolved in the builder and the call is to a function in the current library,
// check for forward declarations of functions
boolean checkForward = libraryName == null || libraryName.equals("") || libraryName.equals(this.libraryInfo.getLibraryName());
Expression result = libraryBuilder.resolveFunction(libraryName, functionName, expressions, !checkForward);
if (result == null) {
Iterable<FunctionDefinitionInfo> functionInfos = libraryInfo.resolveFunctionReference(functionName);
if (functionInfos != null) {
for (FunctionDefinitionInfo functionInfo : functionInfos) {
String saveContext = currentContext;
currentContext = functionInfo.getContext();
try {
Stack<Chunk> saveChunks = chunks;
chunks = new Stack<Chunk>();
forwardFunctions.push(functionInfo);
try {
// Have to call the visit to allow the outer processing to occur
visit(functionInfo.getDefinition());
}
finally {
forwardFunctions.pop();
chunks = saveChunks;
}
} finally {
currentContext = saveContext;
}
}
}
result = libraryBuilder.resolveFunction(libraryName, functionName, expressions, true);
}
return result;
}
@Override
public Expression visitFunction(@NotNull cqlParser.FunctionContext ctx) {
if (libraryBuilder.hasExpressionTarget()) {
Expression target = libraryBuilder.popExpressionTarget();
try {
// If the target is a library reference, resolve as a standard qualified call
if (target instanceof LibraryRef) {
return resolveFunction(((LibraryRef)target).getLibraryName(), ctx);
}
// NOTE: FHIRPath method invocation
// If the target is an expression, resolve as a method invocation
if (target instanceof Expression && methodInvocation) {
return systemMethodResolver.resolveMethod((Expression)target, ctx, true);
}
throw new IllegalArgumentException(String.format("Invalid invocation target: %s", target.getClass().getName()));
}
finally {
libraryBuilder.pushExpressionTarget(target);
}
}
// If we are in an implicit $this context, the function may be resolved as a method invocation
Expression thisRef = libraryBuilder.resolveIdentifier("$this", false);
if (thisRef != null) {
Expression result = systemMethodResolver.resolveMethod(thisRef, ctx, false);
if (result != null) {
return result;
}
}
// If there is no target, resolve as a system function
return resolveFunction(null, ctx);
}
@Override
public Object visitFunctionBody(@NotNull cqlParser.FunctionBodyContext ctx) {
return visit(ctx.expression());
}
public Object internalVisitFunctionDefinition(@NotNull cqlParser.FunctionDefinitionContext ctx) {
this.trackBackMap.put(parseString(ctx.identifier()), getTrackBack(ctx));
FunctionDef fun = of.createFunctionDef()
.withAccessLevel(parseAccessModifier(ctx.accessModifier()))
.withName(parseString(ctx.identifier()));
if (ctx.operandDefinition() != null) {
for (cqlParser.OperandDefinitionContext opdef : ctx.operandDefinition()) {
TypeSpecifier typeSpecifier = parseTypeSpecifier(opdef.typeSpecifier());
fun.getOperand().add(
(OperandDef)of.createOperandDef()
.withName(parseString(opdef.identifier()))
.withOperandTypeSpecifier(typeSpecifier)
.withResultType(typeSpecifier.getResultType())
);
}
}
TypeSpecifier resultType = null;
if (ctx.typeSpecifier() != null) {
resultType = parseTypeSpecifier(ctx.typeSpecifier());
}
if (!libraryBuilder.getTranslatedLibrary().contains(fun)) {
if (ctx.functionBody() != null) {
libraryBuilder.beginFunctionDef(fun);
try {
libraryBuilder.pushExpressionContext(currentContext);
try {
libraryBuilder.pushExpressionDefinition(String.format("%s()", fun.getName()));
try {
fun.setExpression(parseExpression(ctx.functionBody()));
} finally {
libraryBuilder.popExpressionDefinition();
}
} finally {
libraryBuilder.popExpressionContext();
}
} finally {
libraryBuilder.endFunctionDef();
}
if (resultType != null && fun.getExpression() != null && fun.getExpression().getResultType() != null) {
if (!DataTypes.subTypeOf(fun.getExpression().getResultType(), resultType.getResultType())) {
throw new IllegalArgumentException(String.format("Function %s has declared return type %s but the function body returns incompatible type %s.",
fun.getName(), resultType.getResultType(), fun.getExpression().getResultType()));
}
}
fun.setResultType(fun.getExpression().getResultType());
}
else {
fun.setExternal(true);
if (resultType == null) {
throw new IllegalArgumentException(String.format("Function %s is marked external but does not declare a return type.", fun.getName()));
}
fun.setResultType(resultType.getResultType());
}
fun.setContext(currentContext);
if (fun.getResultType() != null) {
libraryBuilder.addExpression(fun);
}
}
return fun;
}
@Override
public Object visitFunctionDefinition(@NotNull cqlParser.FunctionDefinitionContext ctx) {
FunctionDef result = (FunctionDef)internalVisitFunctionDefinition(ctx);
Operator operator = Operator.fromFunctionDef(result);
if (forwardFunctions.isEmpty() || !forwardFunctions.peek().getName().equals(operator.getName())) {
Set<Signature> definedSignatures = definedFunctionDefinitions.get(operator.getName());
if (definedSignatures == null) {
definedSignatures = new HashSet<>();
definedFunctionDefinitions.put(operator.getName(), definedSignatures);
}
if (definedSignatures.contains(operator.getSignature())) {
throw new IllegalArgumentException(String.format("A function named %s with the same type of arguments is already defined in this library.", operator.getName()));
}
// for use in MAT code... holds all of the important information about a function.
List<String> tokens = new ArrayList<>();
tokenize(tokens, ctx);
CQLFunctionModelObject cqlFunctionModelObject = new CQLFunctionModelObject(ctx.identifier().getText(), tokens, result);
this.cqlFunctionModelObjects.add(cqlFunctionModelObject);
definedSignatures.add(operator.getSignature());
}
return result;
}
private AccessModifier parseAccessModifier(ParseTree pt) {
return pt == null ? AccessModifier.PUBLIC : (AccessModifier)visit(pt);
}
public String parseString(ParseTree pt) {
return StringEscapeUtils.unescapeCql(pt == null ? null : (String) visit(pt));
}
private Expression parseExpression(ParseTree pt) {
return pt == null ? null : (Expression) visit(pt);
}
private TypeSpecifier parseTypeSpecifier(ParseTree pt) {
return pt == null ? null : (TypeSpecifier) visit(pt);
}
private boolean isBooleanLiteral(Expression expression, Boolean bool) {
boolean ret = false;
if (expression instanceof Literal) {
Literal lit = (Literal) expression;
ret = lit.getValueType().equals(libraryBuilder.dataTypeToQName(libraryBuilder.resolveTypeName("System", "Boolean")));
if (ret && bool != null) {
ret = bool.equals(Boolean.valueOf(lit.getValue()));
}
}
return ret;
}
private void addExpression(Expression expression) {
expressions.add(expression);
}
private TrackBack getTrackBack(ParseTree tree) {
if (tree instanceof ParserRuleContext) {
return getTrackBack((ParserRuleContext)tree);
}
if (tree instanceof TerminalNode) {
return getTrackBack((TerminalNode)tree);
}
return null;
}
private TrackBack getTrackBack(TerminalNode node) {
TrackBack tb = new TrackBack(
libraryBuilder.getLibraryIdentifier(),
node.getSymbol().getLine(),
node.getSymbol().getCharPositionInLine() + 1, // 1-based instead of 0-based
node.getSymbol().getLine(),
node.getSymbol().getCharPositionInLine() + node.getSymbol().getText().length()
);
return tb;
}
private TrackBack getTrackBack(ParserRuleContext ctx) {
TrackBack tb = new TrackBack(
libraryBuilder.getLibraryIdentifier(),
ctx.getStart().getLine(),
ctx.getStart().getCharPositionInLine() + 1, // 1-based instead of 0-based
ctx.getStop().getLine(),
ctx.getStop().getCharPositionInLine() + ctx.getStop().getText().length() // 1-based instead of 0-based
);
return tb;
}
private void decorate(Element element, TrackBack tb) {
if (locate && tb != null) {
element.setLocator(tb.toLocator());
}
if (resultTypes && element.getResultType() != null) {
if (element.getResultType() instanceof NamedType) {
element.setResultTypeName(libraryBuilder.dataTypeToQName(element.getResultType()));
}
else {
element.setResultTypeSpecifier(libraryBuilder.dataTypeToTypeSpecifier(element.getResultType()));
}
}
}
private TrackBack track(Trackable trackable, ParseTree pt) {
TrackBack tb = getTrackBack(pt);
if (tb != null) {
trackable.getTrackbacks().add(tb);
}
if (trackable instanceof Element) {
decorate((Element)trackable, tb);
}
return tb;
}
private TrackBack track(Trackable trackable, Element from) {
TrackBack tb = from.getTrackbacks().size() > 0 ? from.getTrackbacks().get(0) : null;
if (tb != null) {
trackable.getTrackbacks().add(tb);
}
if (trackable instanceof Element) {
decorate((Element)trackable, tb);
}
return tb;
}
// MAT code below... get information from the visitor
/**
* Splits the context into nice, individual tokens.
* @param tokens the list of tokens
* @param context the parse tree to parse through
*/
private void tokenize(List<String> tokens, ParseTree context) {
if(context.getChildCount() == 0) {
tokens.add(context.getText());
}
else {
for(int i = 0; i < context.getChildCount(); i++) {
tokenize(tokens, context.getChild(i));
}
}
}
public List<CQLValueSetModelObject> getCqlValueSetModelObjects() {
return cqlValueSetModelObjects;
}
public List<CQLParameterModelObject> getCqlParameterModelObjects() {
return cqlParameterModelObjects;
}
public List<CQLCodeModelObject> getCqlCodeModelObjects() {
return cqlCodeModelObjects;
}
public List<CQLCodeSystemModelObject> getCqlCodeSystemModelObjects() {
return cqlCodeSystemModelObjects;
}
public List<CQLExpressionModelObject> getCqlExpressionModelObjects() {
return cqlExpressionModelObjects;
}
public List<CQLFunctionModelObject> getCqlFunctionModelObjects() {
return cqlFunctionModelObjects;
}
public List<CQLIncludeModelObject> getCqlIncludeModelObjects() {
return cqlIncludeModelObjects;
}
public Map<String, TrackBack> getTrackBackMap() {
return trackBackMap;
}
}
| cc0-1.0 |
falkena/openhab | bundles/binding/org.openhab.binding.fritzboxtr064/src/main/java/org/openhab/binding/fritzboxtr064/internal/ItemMap.java | 1715 | /**
* Copyright (c) 2010-2017 by the respective copyright holders.
*
* 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.openhab.binding.fritzboxtr064.internal;
import java.util.Set;
/***
* Represents a item mapping. An item mapping is a collection of all parameters
* based on the config string of the item. config string is like the key of an item mapping.
* Item Mappings must be created manually to support desired fbox tr064 functions.
* Since the FritzBox SOAP services typically return several values in one request,
* an item mapping can map a single {@link #getReadServiceCommand() service command} to
* multiple {@link #getItemCommands() item commands}. This is used to fetch all configured
* items of a service command in a single call.
*
* @author gitbock
*
*/
public interface ItemMap {
/**
* @return Names of the item commands which are provided by the response to the
* {@link #getItemArgumentName(String) SOAP service command} of this map.
*/
Set<String> getItemCommands();
/**
* Get the name of the XML element in the TR064 service call which contains the value of the given command.
* For writing calls, this is an element in the service request, for reading calls in the service response.
*
* @return Name of the XML element for the item value.
*/
String getItemArgumentName(String itemCommand);
String getServiceId();
String getReadServiceCommand();
SoapValueParser getSoapValueParser();
}
| epl-1.0 |
opendaylight/bgpcep | bgp/extensions/flowspec/src/main/java/org/opendaylight/protocol/bgp/flowspec/ipv6/FlowspecIpv6NlriParserHelper.java | 8229 | /*
* Copyright (c) 2016 Brocade Communications 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.protocol.bgp.flowspec.ipv6;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.opendaylight.protocol.bgp.flowspec.AbstractFlowspecNlriParser;
import org.opendaylight.protocol.bgp.flowspec.handlers.NumericOneByteOperandParser;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.FlowspecBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.flowspec.FlowspecType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.DestinationIpv6PrefixCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.DestinationIpv6PrefixCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.FlowLabelCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.FlowLabelCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.NextHeaderCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.NextHeaderCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.SourceIpv6PrefixCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.SourceIpv6PrefixCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.flow.label._case.FlowLabel;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.flow.label._case.FlowLabelBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.next.header._case.NextHeaders;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.flowspec.rev200120.flowspec.destination.group.ipv6.flowspec.flowspec.type.next.header._case.NextHeadersBuilder;
import org.opendaylight.yangtools.yang.common.Uint32;
import org.opendaylight.yangtools.yang.common.Uint8;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
public final class FlowspecIpv6NlriParserHelper {
private static final NodeIdentifier NEXT_HEADER_NID = new NodeIdentifier(NextHeaders.QNAME);
private static final NodeIdentifier FLOW_LABEL_NID = new NodeIdentifier(FlowLabel.QNAME);
private FlowspecIpv6NlriParserHelper() {
}
public static void extractFlowspec(final ChoiceNode fsType, final FlowspecBuilder fsBuilder) {
if (fsType.findChildByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID).isPresent()) {
fsBuilder.setFlowspecType(new DestinationIpv6PrefixCaseBuilder()
.setDestinationPrefix(new Ipv6Prefix((String) fsType
.findChildByArg(AbstractFlowspecNlriParser.DEST_PREFIX_NID).get().body())).build());
} else if (fsType.findChildByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID).isPresent()) {
fsBuilder.setFlowspecType(new SourceIpv6PrefixCaseBuilder().setSourcePrefix(new Ipv6Prefix((String) fsType
.findChildByArg(AbstractFlowspecNlriParser.SOURCE_PREFIX_NID).get().body())).build());
} else if (fsType.findChildByArg(NEXT_HEADER_NID).isPresent()) {
fsBuilder.setFlowspecType(new NextHeaderCaseBuilder()
.setNextHeaders(createNextHeaders((UnkeyedListNode) fsType.findChildByArg(NEXT_HEADER_NID).get()))
.build());
} else if (fsType.findChildByArg(FLOW_LABEL_NID).isPresent()) {
fsBuilder.setFlowspecType(new FlowLabelCaseBuilder()
.setFlowLabel(createFlowLabels((UnkeyedListNode) fsType.findChildByArg(FLOW_LABEL_NID).get())).build());
}
}
public static void buildFlowspecString(final FlowspecType value, final StringBuilder buffer) {
if (value instanceof DestinationIpv6PrefixCase) {
buffer.append("to ");
buffer.append(((DestinationIpv6PrefixCase) value).getDestinationPrefix().getValue());
} else if (value instanceof SourceIpv6PrefixCase) {
buffer.append("from ");
buffer.append(((SourceIpv6PrefixCase) value).getSourcePrefix().getValue());
} else if (value instanceof NextHeaderCase) {
buffer.append("where next header ");
buffer.append(NumericOneByteOperandParser.INSTANCE.toString(((NextHeaderCase) value).getNextHeaders()));
} else if (value instanceof FlowLabelCase) {
buffer.append("where flow label ");
buffer.append(stringFlowLabel(((FlowLabelCase) value).getFlowLabel()));
}
}
private static List<NextHeaders> createNextHeaders(final UnkeyedListNode nextHeadersData) {
final List<NextHeaders> nextHeaders = new ArrayList<>();
for (final UnkeyedListEntryNode node : nextHeadersData.body()) {
final NextHeadersBuilder nextHeadersBuilder = new NextHeadersBuilder();
node.findChildByArg(AbstractFlowspecNlriParser.OP_NID).ifPresent(
dataContainerChild -> nextHeadersBuilder.setOp(NumericOneByteOperandParser
.INSTANCE.create((Set<String>) dataContainerChild.body())));
node.findChildByArg(AbstractFlowspecNlriParser.VALUE_NID).ifPresent(
dataContainerChild -> nextHeadersBuilder.setValue((Uint8) dataContainerChild.body()));
nextHeaders.add(nextHeadersBuilder.build());
}
return nextHeaders;
}
private static List<FlowLabel> createFlowLabels(final UnkeyedListNode flowLabelsData) {
final List<FlowLabel> flowLabels = new ArrayList<>();
for (final UnkeyedListEntryNode node : flowLabelsData.body()) {
final FlowLabelBuilder flowLabelsBuilder = new FlowLabelBuilder();
node.findChildByArg(AbstractFlowspecNlriParser.OP_NID).ifPresent(
dataContainerChild -> flowLabelsBuilder.setOp(NumericOneByteOperandParser
.INSTANCE.create((Set<String>) dataContainerChild.body())));
node.findChildByArg(AbstractFlowspecNlriParser.VALUE_NID).ifPresent(
dataContainerChild -> flowLabelsBuilder.setValue((Uint32) dataContainerChild.body()));
flowLabels.add(flowLabelsBuilder.build());
}
return flowLabels;
}
private static String stringFlowLabel(final List<FlowLabel> list) {
final StringBuilder buffer = new StringBuilder();
boolean isFirst = true;
for (final FlowLabel item : list) {
buffer.append(NumericOneByteOperandParser.INSTANCE.toString(item.getOp(), isFirst));
buffer.append(item.getValue());
buffer.append(' ');
if (isFirst) {
isFirst = false;
}
}
return buffer.toString();
}
}
| epl-1.0 |
adolfosbh/cs2as | org.xtext.example.delphi/src-gen/org/xtext/example/delphi/delphi/impl/designatorImpl.java | 6792 | /**
* generated by Xtext 2.10.0
*/
package org.xtext.example.delphi.delphi.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.xtext.example.delphi.delphi.DelphiPackage;
import org.xtext.example.delphi.delphi.designator;
import org.xtext.example.delphi.delphi.designatorSubPart;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>designator</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.xtext.example.delphi.delphi.impl.designatorImpl#getSubpart <em>Subpart</em>}</li>
* <li>{@link org.xtext.example.delphi.delphi.impl.designatorImpl#getDesignator <em>Designator</em>}</li>
* </ul>
*
* @generated
*/
public class designatorImpl extends CSTraceImpl implements designator
{
/**
* The cached value of the '{@link #getSubpart() <em>Subpart</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSubpart()
* @generated
* @ordered
*/
protected designatorSubPart subpart;
/**
* The cached value of the '{@link #getDesignator() <em>Designator</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDesignator()
* @generated
* @ordered
*/
protected designator designator;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected designatorImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return DelphiPackage.Literals.DESIGNATOR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public designatorSubPart getSubpart()
{
return subpart;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetSubpart(designatorSubPart newSubpart, NotificationChain msgs)
{
designatorSubPart oldSubpart = subpart;
subpart = newSubpart;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, DelphiPackage.DESIGNATOR__SUBPART, oldSubpart, newSubpart);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setSubpart(designatorSubPart newSubpart)
{
if (newSubpart != subpart) {
NotificationChain msgs = null;
if (subpart != null)
msgs = ((InternalEObject)subpart).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - DelphiPackage.DESIGNATOR__SUBPART, null, msgs);
if (newSubpart != null)
msgs = ((InternalEObject)newSubpart).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - DelphiPackage.DESIGNATOR__SUBPART, null, msgs);
msgs = basicSetSubpart(newSubpart, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, DelphiPackage.DESIGNATOR__SUBPART, newSubpart, newSubpart));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public designator getDesignator()
{
return designator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDesignator(designator newDesignator, NotificationChain msgs)
{
designator oldDesignator = designator;
designator = newDesignator;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, DelphiPackage.DESIGNATOR__DESIGNATOR, oldDesignator, newDesignator);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDesignator(designator newDesignator)
{
if (newDesignator != designator) {
NotificationChain msgs = null;
if (designator != null)
msgs = ((InternalEObject)designator).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - DelphiPackage.DESIGNATOR__DESIGNATOR, null, msgs);
if (newDesignator != null)
msgs = ((InternalEObject)newDesignator).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - DelphiPackage.DESIGNATOR__DESIGNATOR, null, msgs);
msgs = basicSetDesignator(newDesignator, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, DelphiPackage.DESIGNATOR__DESIGNATOR, newDesignator, newDesignator));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID) {
case DelphiPackage.DESIGNATOR__SUBPART:
return basicSetSubpart(null, msgs);
case DelphiPackage.DESIGNATOR__DESIGNATOR:
return basicSetDesignator(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID) {
case DelphiPackage.DESIGNATOR__SUBPART:
return getSubpart();
case DelphiPackage.DESIGNATOR__DESIGNATOR:
return getDesignator();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID) {
case DelphiPackage.DESIGNATOR__SUBPART:
setSubpart((designatorSubPart)newValue);
return;
case DelphiPackage.DESIGNATOR__DESIGNATOR:
setDesignator((designator)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID) {
case DelphiPackage.DESIGNATOR__SUBPART:
setSubpart((designatorSubPart)null);
return;
case DelphiPackage.DESIGNATOR__DESIGNATOR:
setDesignator((designator)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID) {
case DelphiPackage.DESIGNATOR__SUBPART:
return subpart != null;
case DelphiPackage.DESIGNATOR__DESIGNATOR:
return designator != null;
}
return super.eIsSet(featureID);
}
} //designatorImpl
| epl-1.0 |
peterkir/org.eclipse.oomph | plugins/org.eclipse.oomph.predicates.edit/src/org/eclipse/oomph/predicates/provider/LocationPredicateItemProvider.java | 4449 | /*
* Copyright (c) 2014, 2015 Eike Stepper (Berlin, Germany) 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:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.oomph.predicates.provider;
import org.eclipse.oomph.predicates.LocationPredicate;
import org.eclipse.oomph.predicates.PredicatesPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import java.util.Collection;
import java.util.List;
/**
* This is the item provider adapter for a {@link org.eclipse.oomph.predicates.LocationPredicate} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class LocationPredicateItemProvider extends PredicateItemProvider
{
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LocationPredicateItemProvider(AdapterFactory adapterFactory)
{
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object)
{
if (itemPropertyDescriptors == null)
{
super.getPropertyDescriptors(object);
addPatternPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Pattern feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addPatternPropertyDescriptor(Object object)
{
itemPropertyDescriptors.add(createItemPropertyDescriptor(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(),
getString("_UI_LocationPredicate_pattern_feature"), getString("_UI_LocationPredicate_pattern_description"),
PredicatesPackage.Literals.LOCATION_PREDICATE__PATTERN, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null));
}
/**
* This returns LocationPredicate.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object)
{
return overlayImage(object, getResourceLocator().getImage("full/obj16/LocationPredicate"));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected boolean shouldComposeCreationImage()
{
return true;
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public String getText(Object object)
{
String label = ((LocationPredicate)object).getPattern();
return label == null || label.length() == 0 ? getString("_UI_LocationPredicate_type") : "Location like " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification)
{
updateChildren(notification);
switch (notification.getFeatureID(LocationPredicate.class))
{
case PredicatesPackage.LOCATION_PREDICATE__PATTERN:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object)
{
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
takari/nexus-perf | src/test/java/com/sonatype/nexus/perftest/RequestRateTest.java | 1242 | /*
* Copyright (c) 2007-2013 Sonatype, Inc. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the Eclipse
* Public License Version 1.0, which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*/
package com.sonatype.nexus.perftest;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
public class RequestRateTest {
@Test
public void testStringParsing() {
Assert.assertEquals(TimeUnit.DAYS.toMillis(1) / 10, new RequestRate("10/DAY").getPeriodMillis());
Assert.assertEquals(TimeUnit.DAYS.toMillis(1) / 10, new RequestRate(" 10 / DAY ").getPeriodMillis());
}
@Test
public void testNextDelay() {
RequestRate rate = new RequestRate("100/HOUR");
int count = 100;
long delay = 0;
double total = 0;
for (int i = 0; i < count; i++) {
long nextDelay = rate.nextDelayMillis();
Assert.assertTrue(Integer.toString(i) + " next=" + nextDelay + " curr=" + delay, nextDelay > delay);
total += (nextDelay - delay);
delay = nextDelay;
}
Assert.assertEquals((double) rate.getPeriodMillis(), total / count, rate.getPeriodMillis() / 100);
}
}
| epl-1.0 |
sleshchenko/che | plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/corext/refactoring/typeconstraints2/TypeVariable2.java | 2348 | /**
* ***************************************************************************** Copyright (c) 2000,
* 2011 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
*
* <p>Contributors: IBM Corporation - initial API and implementation
* *****************************************************************************
*/
package org.eclipse.jdt.internal.corext.refactoring.typeconstraints2;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.CompilationUnitRange;
import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType;
/** A TypeVariable is a ConstraintVariable which stands for a single type reference (in source). */
public final class TypeVariable2 extends ConstraintVariable2 implements ITypeConstraintVariable {
private final CompilationUnitRange fRange;
public TypeVariable2(TType type, CompilationUnitRange range) {
super(type);
Assert.isNotNull(range);
fRange = range;
}
public CompilationUnitRange getRange() {
return fRange;
}
/*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return getRange().hashCode() ^ getType().hashCode();
}
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object other) {
// TODO: unique per construction? //return this == other;
if (this == other) return true;
if (other.getClass() != TypeVariable2.class) return false;
TypeVariable2 otherTypeVariable = (TypeVariable2) other;
return getRange().equals(otherTypeVariable.getRange())
&& getType() == otherTypeVariable.getType();
}
public void setCompilationUnit(ICompilationUnit unit) {
throw new UnsupportedOperationException();
}
public ICompilationUnit getCompilationUnit() {
return fRange.getCompilationUnit();
}
@Override
public String toString() {
return super.toString()
+ " ["
+ fRange.getSourceRange().getOffset()
+ '+'
+ fRange.getSourceRange().getLength()
+ ']'; // $NON-NLS-1$
}
}
| epl-1.0 |
sleshchenko/che | ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/signature/SignatureHelpProvider.java | 1321 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* 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:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.api.editor.signature;
import com.google.common.base.Optional;
import javax.validation.constraints.NotNull;
import org.eclipse.che.api.promises.client.Promise;
import org.eclipse.che.ide.api.editor.document.Document;
import org.eclipse.che.ide.api.editor.texteditor.TextEditor;
/**
* Calculates signature information at cursor position.
*
* @author Evgen Vidolob
*/
public interface SignatureHelpProvider {
/**
* Requests to provide signature information
*
* @param document the document where request called
* @param offset the offset where request called
* @return the promise.
*/
@NotNull
Promise<Optional<SignatureHelp>> signatureHelp(Document document, int offset);
/** Installs the SignatureHelpProvider on the given text view. */
void install(TextEditor editor);
/** Removes the SignatureHelpProvider from the text view it has previously been installed on. */
void uninstall();
}
| epl-1.0 |
diverse-project/k3 | k3-sample/lego/lego/src/robot/robot/SetTurnAngleCmd.java | 1268 | /**
*/
package robot.robot;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Set Turn Angle Cmd</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link robot.robot.SetTurnAngleCmd#getAngle <em>Angle</em>}</li>
* </ul>
* </p>
*
* @see robot.robot.RobotPackage#getSetTurnAngleCmd()
* @model
* @generated
*/
public interface SetTurnAngleCmd extends Command {
/**
* Returns the value of the '<em><b>Angle</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Angle</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Angle</em>' attribute.
* @see #setAngle(Double)
* @see robot.robot.RobotPackage#getSetTurnAngleCmd_Angle()
* @model dataType="robot.Double" required="true"
* @generated
*/
Double getAngle();
/**
* Sets the value of the '{@link robot.robot.SetTurnAngleCmd#getAngle <em>Angle</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Angle</em>' attribute.
* @see #getAngle()
* @generated
*/
void setAngle(Double value);
} // SetTurnAngleCmd
| epl-1.0 |
GoClipse/goclipse | melnorme_util/src/melnorme/utilbox/concurrency/ThreadPoolExecutorExt.java | 5803 | /*******************************************************************************
* Copyright (c) 2015 Bruno Medeiros and other 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
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.utilbox.concurrency;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertFail;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertNotNull;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertTrue;
import static melnorme.utilbox.misc.MiscUtil.isUncheckedException;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
/**
* An extension to {@link ThreadPoolExecutor}:
* - Safer handling of uncaught exceptions, they must be handled by given UncaughtExceptionHandler.
* - Has a few minor utils.
*/
public class ThreadPoolExecutorExt extends ThreadPoolExecutor implements ExecutorService, ICommonExecutor {
public static interface UncaughtExceptionHandler extends Consumer<Throwable> { }
protected final String name;
protected final UncaughtExceptionHandler uncaughtExceptionHandler;
public ThreadPoolExecutorExt(String name, UncaughtExceptionHandler ueHandler) {
this(1, 1, new LinkedBlockingQueue<Runnable>(), name, ueHandler);
}
public ThreadPoolExecutorExt(int corePoolSize, int maximumPoolSize,
BlockingQueue<Runnable> workQueue, String name, UncaughtExceptionHandler ueHandler) {
this(corePoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS, workQueue, name, ueHandler);
}
public ThreadPoolExecutorExt(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, String name, UncaughtExceptionHandler ueHandler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
new ExecutorThreadFactory(name, ueHandler));
this.name = assertNotNull(name);
this.uncaughtExceptionHandler = assertNotNull(ueHandler);
}
@Override
public String getName() {
return name;
}
protected final AtomicInteger executeCount = new AtomicInteger(0);
@Override
public long getSubmittedTaskCount() {
return executeCount.get();
}
@Override
public void execute(Runnable command) {
executeCount.incrementAndGet();
// Check this assertion contract early, and in submitter's thread.
execute_checkPreConditions(command);
super.execute(command);
}
public static void execute_checkPreConditions(Runnable command) {
if(command instanceof ICancellableTask) {
ICancellableTask cancellable = (ICancellableTask) command;
assertTrue(cancellable.canExecute());
}
}
@Override
public void submitTask(ICancellableTask runnableTask) {
this.execute(runnableTask);
}
/* ----------------- ----------------- */
@Override
public List<Runnable> shutdownNowAndCancelAll() {
List<Runnable> remaining = super.shutdownNow();
for (Runnable runnable : remaining) {
if(runnable instanceof FutureTask<?>) {
FutureTask<?> futureTask = (FutureTask<?>) runnable;
futureTask.cancel(true);
} else if(runnable instanceof Future2<?>) {
Future2<?> futureTask = (Future2<?>) runnable;
futureTask.tryCancel();
}
}
return remaining;
}
/* ----------------- Uncaught exception handling ----------------- */
public static class ExecutorThreadFactory extends NamingThreadFactory {
protected final UncaughtExceptionHandler ueHandler;
public ExecutorThreadFactory(String poolName, UncaughtExceptionHandler ueHandler) {
super(poolName);
this.ueHandler = ueHandler;
}
@Override
public Thread newThread(Runnable runable) {
Thread newThread = super.newThread(runable);
newThread.setUncaughtExceptionHandler((thread, throwable) -> ueHandler.accept(throwable));
return newThread;
}
}
@Override
protected void afterExecute(final Runnable runnable, final Throwable throwable) {
if (throwable == null && runnable instanceof Future) {
Future<?> future = (Future<?>) runnable;
assertTrue(future.isDone());
try {
future.get();
} catch (InterruptedException ie) {
// This should not happen because the future is done, get() should return succesfully
throw assertFail();
} catch (CancellationException ce) {
assertTrue(future.isCancelled());
return;
} catch (ExecutionException ee) {
Throwable futureThrowable = ee.getCause();
if(!isUncheckedException(futureThrowable)) {
// for Future's, we only consider it to be unexpected if it's an unchecked exception
// otherwise it can be expected the task client code know how to handle to exception
return;
} else {
handleUnexpectedException(futureThrowable);
}
}
}
// We don't handle the uncaught throwables here.
// Instead the thread uncaught exception handler handles them.
}
protected final void handleUnexpectedException(Throwable throwable) {
// Handle the uncaught exception.
// Usually this will log the exception, so that the user is noticed an internal error occurred.
uncaughtExceptionHandler.accept(throwable);
}
} | epl-1.0 |
crsx/crsx | src/net/sf/crsx/generic/Inliner.java | 5480 | /* Copyright © 2015 IBM Corporation. */
package net.sf.crsx.generic;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.sf.crsx.CRSException;
import net.sf.crsx.Contractum;
import net.sf.crsx.Factory;
import net.sf.crsx.Kind;
import net.sf.crsx.Term;
import net.sf.crsx.Valuation;
import net.sf.crsx.util.Buffer;
import net.sf.crsx.util.Pair;
import net.sf.crsx.util.SortedMultiMap;
import net.sf.crsx.util.Util;
/**
* Rule inliner
*
* Runs after the dispatchifier
*
* @author villardl
*/
public class Inliner
{
final GenericCRS crs;
/** All rules */
private SortedMultiMap<String, GenericRule> rulesByFunction;
/** Rules not to inline */
private HashSet<GenericRule> excludes;
//
public Inliner(GenericCRS crs)
{
super();
this.crs = crs;
}
/**
* Implements $Inline
*
* @param constructors must be set to all constructor symbols before call (not updated)
* @param dataForms updated with all data forms indexed by symbol
* @param functionForms updated with all function forms from {@link Factory#formsOf(String)} for all sorted symbols, indexed by symbol
* @param fullSort updated with the full form of every sort, by sort name
* @param rulesByFunction updated with all rules (overridden by {@link #lastDispatchify}) indexed by function symbol
* @throws CRSException
*/
public void inline(Set<String> constructors, SortedMultiMap<String, Term> dataForms, SortedMultiMap<String, Pair<Term, Term>> functionForms, Map<String, Term> fullSort, SortedMultiMap<String, GenericRule> rulesByFunction)
throws CRSException
{
this.rulesByFunction = rulesByFunction;
this.excludes = new HashSet<GenericRule>();
// Iterate until nothing to do.
List<GenericRule> toInline;
do
{
toInline = toInline();
if (toInline.isEmpty())
break;
for (GenericRule r : toInline)
inline(r);
}
while (true);
}
/**
* Partially evaluate the contraction of the given rule.
*
* @throws CRSException
*/
private void inline(GenericRule rule) throws CRSException
{
String function = Util.symbol(rule.contractum); // Name of the function to partially evaluate
// Get all possible candidate rules
Set<GenericRule> rules = rulesByFunction.multiGet(function);
assert rules != null;
if (rules.size() == 1)
{
// Get rule to evaluate.
GenericRule inlinedRule = rules.iterator().next();
// Use dynamic match for computing valuation (conservative)
// Does not work well on redex with properties and meta-variables.
// For instance Redex=F[#1], Pattern=F[W[#2]] produces no valuation (which is normal).
// TODO: staticMatch.
Valuation valuation = inlinedRule.match(rule.contractum);
if (valuation != null)
{
Buffer b = new Buffer(rule.contractum.maker());
valuation.staticContract(b.sink());
Contractum newcontractum = (Contractum) b.term(true);
if (newcontractum != null)
{
boolean print = false;
if (print)
{
System.out.println("\n\n=============================== START INLINE:\n" + rule);
System.out.println("\n----- inlined rule:\n" + inlinedRule);
}
// Override existing rule with new contractum.
GenericRule newRule = new GenericRule(crs, rule.name, rule.pattern, newcontractum, rule.options);
String ruleSymbol = Util.symbol(rule.pattern);
rulesByFunction.multiRemove(ruleSymbol, rule);
rulesByFunction.multiAdd(ruleSymbol, newRule);
if (print)
System.out.println("------ \nafter:\n" + newRule);
} else
excludes.add(rule);
}
else
excludes.add(rule);
}
else
{
// Can't inline function with multiple rules as it requires something like $[Dispatch
// TODO: could do it if only one rule statically match.
excludes.add(rule);
}
}
/**
* Compute the list of rules that should be considered for inlining their contractum
* @return A list of rules
*/
private List<GenericRule> toInline()
{
ArrayList<GenericRule> rules = new ArrayList<GenericRule>(64);
for (String function : rulesByFunction.multiKeySet())
{
for (GenericRule r : rulesByFunction.multiGet(function))
{
boolean candidate = false;
if (r.getContractum().kind() == Kind.CONSTRUCTION)
{
String symbol1 = r.getContractum().constructor().symbol();
// for now don't inline recursive rules
if (!r.pattern.constructor().symbol().equals(symbol1))
{
Set<GenericRule> rules1 = rulesByFunction.multiGet(symbol1);
candidate = inline(r, rules1);
}
}
if (candidate)
rules.add(r);
}
}
return rules;
}
/**
* Determines whether the given rules should be inlined
* @param rule the rule's contractum to considered
* @param candidates the rules matching the rule's top-level contractum symbol */
private boolean inline(GenericRule rule, Set<GenericRule> candidates)
{
if (excludes.contains(rule))
return false;
// For now only single rule can be inlined.
if (candidates.size() != 1)
return false;
GenericRule r = candidates.iterator().next();
final String function = Util.symbol(rule.getContractum());
// Not inlinable if recursive
if (r.contractum.kind() == Kind.CONSTRUCTION && Util.symbol(r.contractum).equals(function))
return false;
if (r.inline())
return true;
// By default: don't inline
return false;
}
}
| epl-1.0 |
steria/java8Workshop | nashorn/src/test/java/no/steria/nashorn/SimpleNashornTest.java | 1099 | package no.steria.nashorn;
import no.steria.nashorn.light.LightBulb;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;
public class SimpleNashornTest {
@Test
public void should_reply_when_Nashorn_calls() throws Exception {
SimpleNashorn simpleNashorn = new SimpleNashorn();
HelloNashorn helloNashorn = simpleNashorn.loadHelloNashorn();
assertThat(helloNashorn.sayHello("Nashorn")).isEqualTo("Hello Nashorn");
}
@Test
public void should_reply_when_Java8_calls() throws Exception {
SimpleNashorn simpleNashorn = new SimpleNashorn();
HelloNashorn helloNashorn = simpleNashorn.loadHelloNashorn();
assertThat(helloNashorn.sayHello("Java8")).isEqualTo("Hello Java8");
}
@Test
public void should_turn_on_lightbulb_using_nashorn() throws Exception {
SimpleNashorn simpleNashorn = new SimpleNashorn();
HelloNashorn helloNashorn = simpleNashorn.loadHelloNashorn();
helloNashorn.turnOnLightBulb();
assertThat(LightBulb.getInstance().isOn()).isTrue();
}
} | epl-1.0 |
opendaylight/yangtools | model/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/stmt/UnknownEffectiveStatement.java | 1197 | /*
* Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.yang.model.api.stmt;
import com.google.common.annotations.Beta;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
/**
* Effective counterpart to {@link UnknownStatement}. This interface exists only for the purposes of providing a bridge
* from {@link UnknownSchemaNode} to {@link EffectiveStatement} via {@link UnknownSchemaNode#asEffectiveStatement()}.
*
* @param <A> Argument type ({@link Empty} if statement does not have argument.)
* @param <D> Class representing declared version of this statement.
*/
@Beta
// FIXME: remove this interface once UnknownSchemaNode is gone
public interface UnknownEffectiveStatement<A, D extends UnknownStatement<A>> extends EffectiveStatement<A, D> {
}
| epl-1.0 |
zsmartsystems/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.dongle.ember/src/test/java/com/zsmartsystems/zigbee/dongle/ember/ezsp/command/EzspAddEndpointResponseTest.java | 1334 | /**
* Copyright (c) 2016-2022 by the respective copyright holders.
* 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 com.zsmartsystems.zigbee.dongle.ember.ezsp.command;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.EzspFrame;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.EzspFrameTest;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.command.EzspAddEndpointResponse;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.structure.EzspStatus;
/**
*
* @author Chris Jackson
*
*/
public class EzspAddEndpointResponseTest extends EzspFrameTest {
@Test
public void testVersionError() {
EzspFrame.setEzspVersion(4);
EzspAddEndpointResponse response = new EzspAddEndpointResponse(getPacketData("02 80 02 36"));
System.out.println(response);
assertEquals(2, response.getSequenceNumber());
assertEquals(true, response.isResponse());
assertEquals(EzspAddEndpointResponse.FRAME_ID, response.getFrameId());
assertEquals(EzspStatus.EZSP_ERROR_INVALID_VALUE, response.getStatus());
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/core/helper/CoreHelper.java | 1197 | /*******************************************************************************
* Copyright (c) 2012, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Blaise Doughan - 2.5 - initial implementation
******************************************************************************/
package org.eclipse.persistence.internal.core.helper;
public class CoreHelper {
/** Store CR string, for some reason \n is not platform independent. */
protected static String CR = null;
/**
* Return a string containing the platform-appropriate
* characters for carriage return.
*/
public static String cr() {
// bug 2756643
if (CR == null) {
CR = System.getProperty("line.separator");
}
return CR;
}
}
| epl-1.0 |
fp7-netide/IDE | plugins/eu.netide.parameters/src/parameters/impl/ParameterImpl.java | 4971 | /**
*/
package parameters.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import parameters.Parameter;
import parameters.ParametersPackage;
import parameters.Type;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Parameter</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link parameters.impl.ParameterImpl#getName <em>Name</em>}</li>
* <li>{@link parameters.impl.ParameterImpl#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class ParameterImpl extends MinimalEObjectImpl.Container implements Parameter {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getType() <em>Type</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected Type type;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ParameterImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ParametersPackage.Literals.PARAMETER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ParametersPackage.PARAMETER__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Type getType() {
if (type != null && type.eIsProxy()) {
InternalEObject oldType = (InternalEObject)type;
type = (Type)eResolveProxy(oldType);
if (type != oldType) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, ParametersPackage.PARAMETER__TYPE, oldType, type));
}
}
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Type basicGetType() {
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(Type newType) {
Type oldType = type;
type = newType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ParametersPackage.PARAMETER__TYPE, oldType, type));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ParametersPackage.PARAMETER__NAME:
return getName();
case ParametersPackage.PARAMETER__TYPE:
if (resolve) return getType();
return basicGetType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ParametersPackage.PARAMETER__NAME:
setName((String)newValue);
return;
case ParametersPackage.PARAMETER__TYPE:
setType((Type)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ParametersPackage.PARAMETER__NAME:
setName(NAME_EDEFAULT);
return;
case ParametersPackage.PARAMETER__TYPE:
setType((Type)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ParametersPackage.PARAMETER__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case ParametersPackage.PARAMETER__TYPE:
return type != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //ParameterImpl
| epl-1.0 |
kolovos/texlipse | net.sourceforge.texlipse/src/net/sourceforge/texlipse/builder/ExternalProgram.java | 7927 | /*
* $Id: ExternalProgram.java,v 1.5 2006/04/04 22:14:05 borisvl Exp $
*
* Copyright (c) 2004-2005 by the TeXlapse Team.
* 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 net.sourceforge.texlipse.builder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Properties;
import net.sourceforge.texlipse.PathUtils;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.properties.TexlipseProperties;
/**
* Helper methods to run an external program.
*
* @author Kimmo Karlsson
* @author Boris von Loesch
*/
public class ExternalProgram {
// the command to run
private String[] command;
// the directory to the command in
private File dir;
// the process that executes the command
private Process process;
// output messages to this console
private String consoleOutput;
/**
* Creates a new command runner.
*/
public ExternalProgram() {
this.command = null;
this.dir = null;
this.process = null;
this.consoleOutput = null;
}
/**
* Resets the command runner.
*
* @param command command to run
* @param dir directory to run the command in
*/
public void setup(String[] command, File dir, String console) {
this.command = command;
this.dir = dir;
this.process = null;
this.consoleOutput = console;
}
/**
* Force termination of the running process.
*/
public void stop() {
if (process != null) {
process.destroy();
// can't null the process here, because run()-method of this class is still executing
//process = null;
}
}
/**
* Reads the contents of a stream.
*
* @param is the stream
* @return the contents of the stream as a String
*/
protected String readOutput(InputStream is) {
StringWriter store = new StringWriter();
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
store.write(line + '\n');
if (consoleOutput != null) {
BuilderRegistry.printToConsole(consoleOutput + "> " + line);
}
}
} catch (IOException e) {
}
store.flush();
return store.getBuffer().toString();
}
/**
* Runs the external program as a process and waits
* for the process to finish execution.
*
* @param queryMessage text which will trigger the query dialog
* @return the text produced to standard output by the process
* @throws Exception
*/
public String run(String[] queryMessage) throws Exception {
return run(true, queryMessage);
}
/**
* Runs the external program as a process and waits
* for the process to finish execution.
*
* @return the text produced to standard output by the process
* @throws Exception
*/
public String run() throws Exception {
return run(true, null);
}
/**
* Runs the external program as a process and waits
* for the process to finish execution.
*
* @param wait if true, this method will block until
* the process has finished execution
* @return the text produced to standard output by the process
* @throws IOException
*/
protected String run(boolean wait, String[] queryMessage) throws IOException {
String output = null;
String errorOutput = null;
if ((command != null) && (dir != null)) {
StringBuffer commandSB = new StringBuffer();
for (int i = 0; i < command.length; i++) {
commandSB.append(command[i]);
commandSB.append(" ");
}
BuilderRegistry.printToConsole("running: " + commandSB.toString());
Runtime rt = Runtime.getRuntime();
// Add builder program path to environmet variables.
// This is needed at least on Mac OS X, where Eclipse overwrites
// the "path" environment variable, and xelatex needs its directory in the path.
Properties envProp = PathUtils.getEnv();
int index = command[0].lastIndexOf(File.separatorChar);
if (index > 0) {
String commandPath = command[0].substring(0, index);
String key = PathUtils.findPathKey(envProp);
envProp.setProperty(key, envProp.getProperty(key) + File.pathSeparatorChar + commandPath);
}
String[] env = PathUtils.mergeEnvFromPrefs(envProp, TexlipseProperties.BUILD_ENV_SETTINGS);
process = rt.exec(command, env, dir);
} else {
throw new IllegalStateException();
}
final StringBuffer thErrorOutput = new StringBuffer();
final StringBuffer thOutput = new StringBuffer();
// scan the standard output stream
final OutputScanner scanner = new OutputScanner(process.getInputStream(),
process.getOutputStream(), queryMessage, consoleOutput);
// scan also the standard error stream
final OutputScanner errorScanner = new OutputScanner(process.getErrorStream(),
process.getOutputStream(), queryMessage, consoleOutput);
final Thread errorThread = new Thread() {
public void run() {
if (errorScanner.scanOutput()) {
thErrorOutput.append(errorScanner.getText());
}
};
};
final Thread outputThread = new Thread() {
public void run() {
if (scanner.scanOutput()) {
thOutput.append(scanner.getText());
} else {
// Abort by user: Abort build, clear all output
process.destroy();
try {
errorThread.join();
} catch (InterruptedException e) {
// Should not happen
TexlipsePlugin.log("Output scanner interrupted", e);
}
thOutput.setLength(0);
thErrorOutput.setLength(0);
}
};
};
outputThread.start();
errorThread.start();
try {
// Wait until stream read has finished
errorThread.join();
outputThread.join();
} catch (InterruptedException e) {
TexlipsePlugin.log("Output scanner interrupted", e);
// Should not happen
}
output = thOutput.toString();
errorOutput = thErrorOutput.toString();
if (wait) {
// the process status code is not useful here
//int code =
try {
process.waitFor();
} catch (InterruptedException e) {
//Should not happen
TexlipsePlugin.log("Process interrupted", e);
}
}
process = null;
// combine the error output with normal output
// to collect information from for example makeindex
if (errorOutput.length() > 0) {
output += "\n" + errorOutput;
}
return output;
}
}
| epl-1.0 |
robertsmieja/CS4233-Strategy | test/strategy/game/version/delta/combat/DeltaStrategyCombatTest.java | 15648 | /*******************************************************************************
* This files was developed for CS4233: Object-Oriented Analysis & Design.
* The course was taken at Worcester Polytechnic Institute.
*
* 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 strategy.game.version.delta.combat;
import static org.junit.Assert.assertEquals;
import static strategy.common.PlayerColor.BLUE;
import static strategy.common.PlayerColor.RED;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import strategy.common.PlayerColor;
import strategy.common.StrategyException;
import strategy.game.common.Location2D;
import strategy.game.common.Piece;
import strategy.game.common.PieceLocationDescriptor;
import strategy.game.common.PieceType;
import strategy.game.version.common.combat.CombatResult;
import strategy.game.version.common.combat.CombatRuleSet;
import strategy.game.version.delta.combat.DeltaCombatRuleSet;
/**
* All tests relating to Delta Strategy and Combat
* @author rjsmieja, jrspicola
* @version Sep 11, 2013
*/
public class DeltaStrategyCombatTest{
private CombatRuleSet combatRules;
private static List<PieceType> DeltaPieces;
private ArrayList<PieceType> piecesToLoseAgainst;
private ArrayList<PieceType> piecesToWinAgainst;
@BeforeClass
public static void oneTimeSetup() throws StrategyException
{
DeltaPieces = new ArrayList<PieceType>();
DeltaPieces.add(PieceType.MARSHAL);
DeltaPieces.add(PieceType.GENERAL);
DeltaPieces.add(PieceType.COLONEL);
DeltaPieces.add(PieceType.MAJOR);
DeltaPieces.add(PieceType.CAPTAIN);
DeltaPieces.add(PieceType.LIEUTENANT);
DeltaPieces.add(PieceType.SERGEANT);
DeltaPieces.add(PieceType.MINER);
DeltaPieces.add(PieceType.SCOUT);
DeltaPieces.add(PieceType.SPY);
// DeltaPieces.add(PieceType.BOMB);
// DeltaPieces.add(PieceType.FLAG);
}
@Before
public void setup(){
combatRules = new DeltaCombatRuleSet();
piecesToWinAgainst = new ArrayList<PieceType>();
piecesToLoseAgainst = new ArrayList<PieceType>();
}
@Test
public void testMarshalWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.GENERAL);
piecesToWinAgainst.add(PieceType.COLONEL);
piecesToWinAgainst.add(PieceType.MAJOR);
piecesToWinAgainst.add(PieceType.CAPTAIN);
piecesToWinAgainst.add(PieceType.LIEUTENANT);
piecesToWinAgainst.add(PieceType.SERGEANT);
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.MARSHAL, RED, piece, BLUE);
testCombat(PieceType.MARSHAL, BLUE, piece, RED);
}
}
@Test
public void testMarshalLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.MARSHAL, BLUE);
testCombat(piece, BLUE, PieceType.MARSHAL, RED);
}
}
@Test
public void testGeneralWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.COLONEL);
piecesToWinAgainst.add(PieceType.MAJOR);
piecesToWinAgainst.add(PieceType.CAPTAIN);
piecesToWinAgainst.add(PieceType.LIEUTENANT);
piecesToWinAgainst.add(PieceType.SERGEANT);
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.GENERAL, RED, piece, BLUE);
testCombat(PieceType.GENERAL, BLUE, piece, RED);
}
}
@Test
public void testGeneralLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.GENERAL, BLUE);
testCombat(piece, BLUE, PieceType.GENERAL, RED);
}
}
@Test
public void testColonelWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.MAJOR);
piecesToWinAgainst.add(PieceType.CAPTAIN);
piecesToWinAgainst.add(PieceType.LIEUTENANT);
piecesToWinAgainst.add(PieceType.SERGEANT);
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.COLONEL, RED, piece, BLUE);
testCombat(PieceType.COLONEL, BLUE, piece, RED);
}
}
@Test
public void testColonelLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.COLONEL, BLUE);
testCombat(piece, BLUE, PieceType.COLONEL, RED);
}
}
@Test
public void testMajorWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.CAPTAIN);
piecesToWinAgainst.add(PieceType.LIEUTENANT);
piecesToWinAgainst.add(PieceType.SERGEANT);
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.MAJOR, RED, piece, BLUE);
testCombat(PieceType.MAJOR, BLUE, piece, RED);
}
}
@Test
public void testMajorLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.MAJOR, BLUE);
testCombat(piece, BLUE, PieceType.MAJOR, RED);
}
}
@Test
public void testCaptainWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.LIEUTENANT);
piecesToWinAgainst.add(PieceType.SERGEANT);
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.CAPTAIN, RED, piece, BLUE);
testCombat(PieceType.CAPTAIN, BLUE, piece, RED);
}
}
@Test
public void testCaptainLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
piecesToLoseAgainst.add(PieceType.MAJOR);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.CAPTAIN, BLUE);
testCombat(piece, BLUE, PieceType.CAPTAIN, RED);
}
}
@Test
public void testLieutenantWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.SERGEANT);
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.LIEUTENANT, RED, piece, BLUE);
testCombat(PieceType.LIEUTENANT, BLUE, piece, RED);
}
}
@Test
public void testLieutenantLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
piecesToLoseAgainst.add(PieceType.MAJOR);
piecesToLoseAgainst.add(PieceType.CAPTAIN);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.LIEUTENANT, BLUE);
testCombat(piece, BLUE, PieceType.LIEUTENANT, RED);
}
}
@Test
public void testSergantWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.MINER);
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.SERGEANT, RED, piece, BLUE);
testCombat(PieceType.SERGEANT, BLUE, piece, RED);
}
}
@Test
public void testSergantLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
piecesToLoseAgainst.add(PieceType.MAJOR);
piecesToLoseAgainst.add(PieceType.CAPTAIN);
piecesToLoseAgainst.add(PieceType.LIEUTENANT);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.SERGEANT, BLUE);
testCombat(piece, BLUE, PieceType.SERGEANT, RED);
}
}
@Test
public void testMinerWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.SCOUT);
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.MINER, RED, piece, BLUE);
testCombat(PieceType.MINER, BLUE, piece, RED);
}
}
@Test
public void testMinerLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
piecesToLoseAgainst.add(PieceType.MAJOR);
piecesToLoseAgainst.add(PieceType.CAPTAIN);
piecesToLoseAgainst.add(PieceType.LIEUTENANT);
piecesToLoseAgainst.add(PieceType.SERGEANT);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.MINER, BLUE);
testCombat(piece, BLUE, PieceType.MINER, RED);
}
}
@Test
public void testScoutWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.SPY);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.SCOUT, RED, piece, BLUE);
testCombat(PieceType.SCOUT, BLUE, piece, RED);
}
}
@Test
public void testScoutLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
piecesToLoseAgainst.add(PieceType.MAJOR);
piecesToLoseAgainst.add(PieceType.CAPTAIN);
piecesToLoseAgainst.add(PieceType.LIEUTENANT);
piecesToLoseAgainst.add(PieceType.SERGEANT);
piecesToLoseAgainst.add(PieceType.MINER);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.SCOUT, BLUE);
testCombat(piece, BLUE, PieceType.SCOUT, RED);
}
}
@Test
public void testSpyWins() throws StrategyException{
piecesToWinAgainst.add(PieceType.MARSHAL);
for (PieceType piece : piecesToWinAgainst){
testCombat(PieceType.SPY, RED, piece, BLUE);
testCombat(PieceType.SPY, BLUE, piece, RED);
}
}
@Test
public void testSpyLosses() throws StrategyException{
piecesToLoseAgainst.add(PieceType.MARSHAL);
piecesToLoseAgainst.add(PieceType.GENERAL);
piecesToLoseAgainst.add(PieceType.COLONEL);
piecesToLoseAgainst.add(PieceType.MAJOR);
piecesToLoseAgainst.add(PieceType.CAPTAIN);
piecesToLoseAgainst.add(PieceType.LIEUTENANT);
piecesToLoseAgainst.add(PieceType.SERGEANT);
piecesToLoseAgainst.add(PieceType.MINER);
for (PieceType piece : piecesToLoseAgainst){
testCombat(piece, RED, PieceType.SPY, BLUE);
testCombat(piece, BLUE, PieceType.SPY, RED);
}
}
@Test(expected=StrategyException.class)
public void testFlagAttack() throws StrategyException{
testCombat(PieceType.FLAG, RED, PieceType.LIEUTENANT, BLUE);
}
@Test
public void testFlagDefend() throws StrategyException{
for (PieceType piece: DeltaPieces){
testCombat_WinsOnly(piece, RED, PieceType.FLAG, BLUE);
testCombat_WinsOnly(piece, BLUE, PieceType.FLAG, RED);
}
}
@Test(expected=StrategyException.class)
public void testBombAttack() throws StrategyException{
testCombat(PieceType.BOMB, RED, PieceType.LIEUTENANT, BLUE);
}
@Test
public void testBombDefend() throws StrategyException{
for (PieceType piece: DeltaPieces){
testCombat_LosesOnly(piece, RED, PieceType.BOMB, BLUE);
testCombat_LosesOnly(piece, BLUE, PieceType.BOMB, RED);
}
}
// Helper methods
private void testCombat_WinsOnly(PieceType winningPiece, PlayerColor winningPlayer, PieceType losingPiece, PlayerColor losingPlayer) throws StrategyException{
PieceLocationDescriptor winner = new PieceLocationDescriptor(new Piece(winningPiece, winningPlayer), new Location2D(0,0));
PieceLocationDescriptor loser = new PieceLocationDescriptor(new Piece(losingPiece, losingPlayer), new Location2D(0,1));
CombatResult combatResult = combatRules.doCombat(winner, loser);
assertEquals("Expected <"+ winner.getPiece() +"> to win, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", winner, combatResult.getWinningPiece());
assertEquals("Expected <"+ winner.getPiece() +"> to lose, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", loser, combatResult.getLosingPiece());
}
private void testCombat_LosesOnly(PieceType losingPiece, PlayerColor losingPlayer, PieceType winningPiece, PlayerColor winningPlayer) throws StrategyException{
PieceLocationDescriptor loser = new PieceLocationDescriptor(new Piece(losingPiece, losingPlayer), new Location2D(0,0));
PieceLocationDescriptor winner = new PieceLocationDescriptor(new Piece(winningPiece, winningPlayer), new Location2D(0,1));
CombatResult combatResult = combatRules.doCombat(loser, winner);
if(losingPiece == PieceType.MINER && winningPiece == PieceType.BOMB){
assertEquals("Expected <"+ loser.getPiece() +"> to win, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", loser, combatResult.getWinningPiece());
assertEquals("Expected <"+ loser.getPiece() +"> to lose, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", winner, combatResult.getLosingPiece());
} else {
assertEquals("Expected <"+ winner.getPiece() +"> to win, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", winner, combatResult.getWinningPiece());
assertEquals("Expected <"+ winner.getPiece() +"> to lose, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", loser, combatResult.getLosingPiece());
}
}
private void testCombat(PieceType winningPiece, PlayerColor winningPlayer, PieceType losingPiece, PlayerColor losingPlayer) throws StrategyException{
PieceLocationDescriptor winner = new PieceLocationDescriptor(new Piece(winningPiece, winningPlayer), new Location2D(0,0));
PieceLocationDescriptor loser = new PieceLocationDescriptor(new Piece(losingPiece, losingPlayer), new Location2D(0,1));
CombatResult combatResult = combatRules.doCombat(winner, loser);
assertEquals("Expected <"+ winner.getPiece() +"> to win, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", winner, combatResult.getWinningPiece());
assertEquals("Expected <"+ winner.getPiece() +"> to lose, but was actually <" + combatResult.getWinningPiece().getPiece() + ">", loser, combatResult.getLosingPiece());
CombatResult reverseCombatResult = combatRules.doCombat(loser, winner);
if((winningPiece == PieceType.SPY && losingPiece == PieceType.MARSHAL) || winningPiece == PieceType.MARSHAL && losingPiece == PieceType.SPY){
assertEquals("Expected <"+ loser.getPiece() +"> to win, but was actually <" + reverseCombatResult.getLosingPiece().getPiece() + ">", loser, reverseCombatResult.getWinningPiece());
assertEquals("Expected <"+ loser.getPiece() +"> to lose, but was actually <" + reverseCombatResult.getLosingPiece().getPiece() + ">", winner, reverseCombatResult.getLosingPiece());
}else{
assertEquals("Expected <"+ winner.getPiece() +"> to win, but was actually <" + reverseCombatResult.getWinningPiece().getPiece() + ">", winner, reverseCombatResult.getWinningPiece());
assertEquals("Expected <"+ winner.getPiece() +"> to lose, but was actually <" + reverseCombatResult.getWinningPiece().getPiece() + ">", loser, reverseCombatResult.getLosingPiece());
}
}
} | epl-1.0 |
edgarmueller/emfstore-rest | bundles/org.eclipse.emf.emfstore.client/src/org/eclipse/emf/emfstore/internal/client/model/changeTracking/notification/filter/EmptyRemovalsFilter.java | 1830 | /*******************************************************************************
* Copyright (c) 2008-2011 Chair for Applied Software Engineering,
* Technische Universitaet Muenchen.
* 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:
* Slawomir Chodnicki - initial API and implementation
******************************************************************************/
package org.eclipse.emf.emfstore.internal.client.model.changeTracking.notification.filter;
import java.util.Collection;
import org.eclipse.emf.emfstore.client.handler.ESNotificationFilter;
import org.eclipse.emf.emfstore.common.model.ESObjectContainer;
import org.eclipse.emf.emfstore.common.model.util.ESNotificationInfo;
/**
* <p>
* This class filters zero effect remove operations from a notification recording.
* </p>
* <p>
* An example of a zero effect remove would be a notification that <code>[]</code> changed to <code>null</code>.
* </p>
*
* @author chodnick
*/
public class EmptyRemovalsFilter implements ESNotificationFilter {
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.client.handler.ESNotificationFilter#check(org.eclipse.emf.emfstore.common.model.util.ESNotificationInfo,
* org.eclipse.emf.emfstore.common.model.ESObjectContainer)
*/
public boolean check(ESNotificationInfo notificationInfo, ESObjectContainer<?> container) {
return notificationInfo.isRemoveManyEvent()
&& notificationInfo.getNewValue() == null
&& notificationInfo.getOldValue() instanceof Collection<?>
&& ((Collection<?>) notificationInfo.getOldValue()).isEmpty() && notificationInfo.wasSet();
}
}
| epl-1.0 |
stzilli/kapua | rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessPermissions.java | 10776 | /*******************************************************************************
* Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.app.api.resources.v1.resources;
import org.eclipse.kapua.KapuaEntityNotFoundException;
import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource;
import org.eclipse.kapua.app.api.core.model.CountResult;
import org.eclipse.kapua.app.api.core.model.EntityId;
import org.eclipse.kapua.app.api.core.model.ScopeId;
import org.eclipse.kapua.locator.KapuaLocator;
import org.eclipse.kapua.model.KapuaEntityAttributes;
import org.eclipse.kapua.model.query.SortOrder;
import org.eclipse.kapua.model.query.predicate.AndPredicate;
import org.eclipse.kapua.service.KapuaService;
import org.eclipse.kapua.service.authorization.access.AccessInfo;
import org.eclipse.kapua.service.authorization.access.AccessPermission;
import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes;
import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator;
import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory;
import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult;
import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery;
import org.eclipse.kapua.service.authorization.access.AccessPermissionService;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.common.base.Strings;
/**
* {@link AccessPermission} REST API resource.
*
* @since 1.0.0
*/
@Path("{scopeId}/accessinfos/{accessInfoId}/permissions")
public class AccessPermissions extends AbstractKapuaResource {
private final KapuaLocator locator = KapuaLocator.getInstance();
private final AccessPermissionService accessPermissionService = locator.getService(AccessPermissionService.class);
private final AccessPermissionFactory accessPermissionFactory = locator.getFactory(AccessPermissionFactory.class);
/**
* Gets the {@link AccessPermission} list in the scope.
*
* @param scopeId The {@link ScopeId} in which to search results.
* @param accessInfoId The optional {@link AccessInfo} id to filter results.
* @param offset The result set offset.
* @param limit The result set limit.
* @param sortParam The name of the parameter that will be used as a sorting key
* @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive.
* @return The {@link AccessPermissionListResult} of all the {@link AccessPermission}s associated to the current selected scope.
* @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions.
* @since 1.0.0
*/
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public AccessPermissionListResult simpleQuery(
@PathParam("scopeId") ScopeId scopeId,
@PathParam("accessInfoId") EntityId accessInfoId,
@QueryParam("sortParam") String sortParam,
@QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir,
@QueryParam("offset") @DefaultValue("0") int offset,
@QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException {
AccessPermissionQuery query = accessPermissionFactory.newQuery(scopeId);
query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId));
if (!Strings.isNullOrEmpty(sortParam)) {
query.setSortCriteria(query.fieldSortCriteria(sortParam, sortDir));
}
query.setOffset(offset);
query.setLimit(limit);
return query(scopeId, accessInfoId, query);
}
/**
* Queries the {@link AccessPermission}s with the given {@link AccessPermissionQuery} parameter.
*
* @param scopeId The {@link ScopeId} in which to search results.
* @param accessInfoId The {@link AccessInfo} id in which to search results.
* @param query The {@link AccessPermissionQuery} to use to filter results.
* @return The {@link AccessPermissionListResult} of all the result matching the given {@link AccessPermissionQuery} parameter.
* @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions.
* @since 1.0.0
*/
@POST
@Path("_query")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public AccessPermissionListResult query(
@PathParam("scopeId") ScopeId scopeId,
@PathParam("accessInfoId") EntityId accessInfoId,
AccessPermissionQuery query) throws KapuaException {
query.setScopeId(scopeId);
query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId));
return accessPermissionService.query(query);
}
/**
* Counts the {@link AccessPermission}s with the given {@link AccessPermissionQuery} parameter.
*
* @param scopeId The {@link ScopeId} in which to count results.
* @param accessInfoId The {@link AccessInfo} id in which to count results.
* @param query The {@link AccessPermissionQuery} to use to filter count results.
* @return The count of all the result matching the given {@link AccessPermissionQuery} parameter.
* @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions.
* @since 1.0.0
*/
@POST
@Path("_count")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public CountResult count(
@PathParam("scopeId") ScopeId scopeId,
@PathParam("accessInfoId") EntityId accessInfoId,
AccessPermissionQuery query) throws KapuaException {
query.setScopeId(scopeId);
query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId));
return new CountResult(accessPermissionService.count(query));
}
/**
* Creates a new {@link AccessPermission} based on the information provided in {@link AccessPermissionCreator}
* parameter.
*
* @param scopeId The {@link ScopeId} in which to create the AccessPermission.
* @param accessInfoId The {@link AccessInfo} id in which to create the AccessPermission.
* @param accessPermissionCreator Provides the information for the new {@link AccessPermission} to be created.
* @return The newly created {@link AccessPermission} object.
* @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions.
* @since 1.0.0
*/
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response create(
@PathParam("scopeId") ScopeId scopeId,
@PathParam("accessInfoId") EntityId accessInfoId,
AccessPermissionCreator accessPermissionCreator) throws KapuaException {
accessPermissionCreator.setScopeId(scopeId);
accessPermissionCreator.setAccessInfoId(accessInfoId);
return returnCreated(accessPermissionService.create(accessPermissionCreator));
}
/**
* Returns the AccessPermission specified by the "accessPermissionId" path parameter.
*
* @param scopeId The {@link ScopeId} of the requested {@link AccessPermission}.
* @param accessInfoId The {@link AccessInfo} id of the requested {@link AccessPermission}.
* @param accessPermissionId The id of the requested AccessPermission.
* @return The requested AccessPermission object.
* @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions.
* @since 1.0.0
*/
@GET
@Path("{accessPermissionId}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public AccessPermission find(
@PathParam("scopeId") ScopeId scopeId,
@PathParam("accessInfoId") EntityId accessInfoId,
@PathParam("accessPermissionId") EntityId accessPermissionId) throws KapuaException {
AccessPermissionQuery query = accessPermissionFactory.newQuery(scopeId);
AndPredicate andPredicate = query.andPredicate(
query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId),
query.attributePredicate(KapuaEntityAttributes.ENTITY_ID, accessPermissionId)
);
query.setPredicate(andPredicate);
query.setOffset(0);
query.setLimit(1);
AccessPermissionListResult results = accessPermissionService.query(query);
if (results.isEmpty()) {
throw new KapuaEntityNotFoundException(AccessPermission.TYPE, accessPermissionId);
}
return results.getFirstItem();
}
/**
* Deletes the {@link AccessPermission} specified by the "accessPermissionId" path parameter.
*
* @param scopeId The {@link ScopeId} of the {@link AccessPermission} to delete.
* @param accessInfoId The {@link AccessInfo} id of the {@link AccessPermission} to delete.
* @param accessPermissionId The id of the AccessPermission to be deleted.
* @return HTTP 200 if operation has completed successfully.
* @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions.
* @since 1.0.0
*/
@DELETE
@Path("{accessPermissionId}")
public Response deleteAccessPermission(
@PathParam("scopeId") ScopeId scopeId,
@PathParam("accessInfoId") EntityId accessInfoId,
@PathParam("accessPermissionId") EntityId accessPermissionId) throws KapuaException {
accessPermissionService.delete(scopeId, accessPermissionId);
return returnNoContent();
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.mongo_fat/fat/src/com/ibm/ws/mongo/fat/MongoSSLInvalidTrustTest.java | 3773 | /*******************************************************************************
* Copyright (c) 2015, 2022 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.mongo.fat;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import componenttest.annotation.AllowedFFDC;
import componenttest.annotation.Server;
import componenttest.custom.junit.runner.FATRunner;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
import componenttest.topology.impl.LibertyServer;
import componenttest.topology.utils.FATServletClient;
@RunWith(FATRunner.class)
@Mode(TestMode.FULL)
public class MongoSSLInvalidTrustTest extends FATServletClient {
@Server("mongo.fat.server.ssl")
public static LibertyServer server;
@BeforeClass
public static void beforeClass() throws Exception {
MongoServerSelector.assignMongoServers(server);
FATSuite.createApp(server);
server.startServer();
if (!FATSuite.waitForMongoSSL(server)) {
// Call afterClass to stop the server; then restart
afterClass();
server.startServer();
assertTrue("Did not find message(s) indicating MongoDBService(s) had activated", FATSuite.waitForMongoSSL(server));
}
}
@AfterClass
public static void afterClass() throws Exception {
// TODO: CWWKE0701E - Circular reference detected trying to get service
// {org.osgi.service.cm.ManagedServiceFactory,
// com.ibm.wsspi.logging.Introspector,
// com.ibm.ws.runtime.update.RuntimeUpdateListener,
// com.ibm.wsspi.application.lifecycle.ApplicationRecycleCoordinator}
server.stopServer("CWPKI0823E:.*", // SSL HANDSHAKE FAILURE
"CWWKE0701E",
"CWWKG0033W");
}
@Before
public void beforeEach() throws Exception {
server.setMarkToEndOfLog();
}
@Test
@AllowedFFDC({ "java.security.cert.CertPathBuilderException", "sun.security.validator.ValidatorException", "com.ibm.security.cert.IBMCertPathBuilderException" })
public void testCertAuthInvalidTrust() throws Exception {
testInvalidConfig("mongo/testdb-invalid-certificate-trust", "MongoTimeoutException");
// CWPKI0823E: SSL HANDSHAKE FAILURE: A signer with SubjectDN [{0}] was sent from the host [{1}]. The signer might
// need to be added to local trust store [{2}], located in SSL configuration alias [{3}]. The extended error message from the SSL handshake exception is: [{4}].
assertNotNull("Server exception for error CWPKI0823E was not found within the allotted interval", server.waitForStringInLogUsingMark("CWPKI0823E"));
assertNotNull("SSLHandshakeException was not found within the allotted interval", server.waitForStringInLogUsingMark("SSLHandshakeException"));
}
private void testInvalidConfig(String jndiName, String expectedEx) throws Exception {
FATServletClient.runTest(server, FATSuite.APP_NAME + "/MongoSSLTestServlet",
"testInvalidConfig&jndiName=" + jndiName + "&expectedEx=" + expectedEx + "&forTest=" + testName.getMethodName());
}
}
| epl-1.0 |
lunifera/lunifera-dsl | org.lunifera.dsl.semantic.dto/emf-gen/org/lunifera/dsl/semantic/dto/LDtoInheritedReference.java | 3857 | /**
* Copyright (c) 2011 - 2014, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg)
* 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
*
* Based on ideas from Xtext, Xtend, Xcore
*
* Contributors:
* Florian Pirchner - Initial implementation
*
*/
package org.lunifera.dsl.semantic.dto;
import org.eclipse.xtext.common.types.JvmTypeReference;
import org.lunifera.dsl.semantic.common.types.LMultiplicity;
import org.lunifera.dsl.semantic.common.types.LReference;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>LDto Inherited Reference</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.lunifera.dsl.semantic.dto.LDtoInheritedReference#getInheritedFeature <em>Inherited Feature</em>}</li>
* <li>{@link org.lunifera.dsl.semantic.dto.LDtoInheritedReference#getInheritedFeatureTypeJvm <em>Inherited Feature Type Jvm</em>}</li>
* </ul>
* </p>
*
* @see org.lunifera.dsl.semantic.dto.LunDtoPackage#getLDtoInheritedReference()
* @model
* @generated
*/
public interface LDtoInheritedReference extends LDtoAbstractReference {
/**
* Returns the value of the '<em><b>Inherited Feature</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Inherited Feature</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Inherited Feature</em>' reference.
* @see #setInheritedFeature(LReference)
* @see org.lunifera.dsl.semantic.dto.LunDtoPackage#getLDtoInheritedReference_InheritedFeature()
* @model
* @generated
*/
LReference getInheritedFeature();
/**
* Sets the value of the '{@link org.lunifera.dsl.semantic.dto.LDtoInheritedReference#getInheritedFeature <em>Inherited Feature</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Inherited Feature</em>' reference.
* @see #getInheritedFeature()
* @generated
*/
void setInheritedFeature(LReference value);
/**
* Returns the value of the '<em><b>Inherited Feature Type Jvm</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Inherited Feature Type Jvm</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Inherited Feature Type Jvm</em>' containment reference.
* @see #setInheritedFeatureTypeJvm(JvmTypeReference)
* @see org.lunifera.dsl.semantic.dto.LunDtoPackage#getLDtoInheritedReference_InheritedFeatureTypeJvm()
* @model containment="true" transient="true"
* @generated
*/
JvmTypeReference getInheritedFeatureTypeJvm();
/**
* Sets the value of the '{@link org.lunifera.dsl.semantic.dto.LDtoInheritedReference#getInheritedFeatureTypeJvm <em>Inherited Feature Type Jvm</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Inherited Feature Type Jvm</em>' containment reference.
* @see #getInheritedFeatureTypeJvm()
* @generated
*/
void setInheritedFeatureTypeJvm(JvmTypeReference value);
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model kind="operation" unique="false"
* annotation="http://www.eclipse.org/emf/2002/GenModel body='<%org.lunifera.dsl.semantic.common.types.LReference%> _inheritedFeature = this.getInheritedFeature();\nreturn _inheritedFeature.getMultiplicity();'"
* @generated
*/
LMultiplicity getInheritedMultiplicity();
} // LDtoInheritedReference
| epl-1.0 |
rfheh/MoodPhoto | MoodPhoto/src/com/mp/util/AppLog.java | 571 | package com.mp.util;
import android.util.Log;
import com.mp.BuildConfig;
import com.mp.application.MPApplication;
public class AppLog {
static boolean debug = BuildConfig.DEBUG;
static final String TAG = MPApplication.class.getSimpleName();
public static void i(String msg) {
i(TAG, msg);
}
public static void i(String tag, String msg) {
if (debug) {
Log.i(tag, msg);
}
}
public static void e(String msg) {
e(TAG, msg);
}
public static void e(String tag, String msg) {
if (debug)
Log.e(tag, msg);
}
}
| epl-1.0 |
peterkir/klib.io | io.klib.gogo/src/io/klib/gogo/argumentstarter/ArgumentToGogoMapper.java | 4212 | package io.klib.gogo.argumentstarter;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import aQute.bnd.annotation.component.Activate;
import aQute.bnd.annotation.component.Component;
import aQute.bnd.annotation.component.Reference;
@Component(immediate = true)
public class ArgumentToGogoMapper {
private String[] args;
private CommandProcessor cmdproc;
@Reference(target = "(launcher.arguments=*)")
void args(final Object object, final Map<String,Object> map) {
args = (String[]) map.get("launcher.arguments");
}
@Reference
void setCommandSession(final CommandProcessor cp) {
this.cmdproc = cp;
}
@Activate
private void activate() {
long startTime = System.currentTimeMillis();
// we process only if program arguments are available
if (args.length > 0) {
String[] gogoCommands = args[0].split(":");
String argScope = gogoCommands[0];
String argFunction = gogoCommands[1];
BundleContext bc = FrameworkUtil.getBundle(ArgumentToGogoMapper.class).getBundleContext();
@SuppressWarnings("rawtypes")
ServiceReference[] refs = null;
String filter = MessageFormat.format("(&({0}={1})({2}={3}))",
CommandProcessor.COMMAND_SCOPE,
argScope,
CommandProcessor.COMMAND_FUNCTION,
argFunction);
try {
refs = bc.getAllServiceReferences(null, filter);
}
catch (InvalidSyntaxException e) {
// this should not happen
}
if (refs.length == 0) {
String msg = MessageFormat.format("No OSGi command found for {0}:{1}", argScope, argFunction);
System.out.println(msg);
}
else {
String joinedGogoShellCmd = Arrays.asList(args).stream().map(i -> i.toString()).collect(Collectors.joining(" "));
CommandSession cs = cmdproc.createSession(null, System.out, System.err);
try {
cs.execute(joinedGogoShellCmd);
String msg = MessageFormat.format("execution took <{0}> ms for gogo command <{1}> ",
System.currentTimeMillis() - startTime,
joinedGogoShellCmd);
System.out.println(msg);
}
catch (IllegalArgumentException iae) {
printGogoHelp(cs, argScope, argFunction);
}
catch (Exception e) {
e.printStackTrace();
}
}
// shutting down the framework
try {
bc.getBundle(0).stop();
Thread.sleep(1000);
}
catch (BundleException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
System.exit(0);
}
}
}
private void printGogoHelp(final CommandSession cs, final String argScope, final String argFunction) {
String userCmd = MessageFormat.format("{0}:{1}", argScope, argFunction);
try {
System.out.println(MessageFormat.format("The specified cmd {0} has no valid syntax. Following signatures are supported.",
userCmd));
cs.execute("help " + userCmd);
}
catch (Exception e) {
// should not happen
}
}
}
| epl-1.0 |
sleshchenko/che | ide/commons-gwt/src/main/java/org/eclipse/che/ide/ui/loaders/PopupLoaderMessages.java | 1544 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* 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:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.ui.loaders;
import com.google.gwt.i18n.client.Messages;
/**
* Messages for Popup loader widget.
*
* @author Vitaliy Guliy
*/
public interface PopupLoaderMessages extends Messages {
@Key("startingWorkspaceRuntime.title")
String startingWorkspaceRuntime();
@Key("startingWorkspaceRuntime.description")
String startingWorkspaceRuntimeDescription();
@Key("startingWorkspaceAgent.title")
String startingWorkspaceAgent();
@Key("startingWorkspaceAgent.description")
String startingWorkspaceAgentDescription();
@Key("stoppingWorkspace.title")
String stoppingWorkspace();
@Key("stoppingWorkspace.description")
String stoppingWorkspaceDescription();
@Key("creatingProject.title")
String creatingProject();
@Key("creatingProject.description")
String creatingProjectDescription();
@Key("workspaceStopped.title")
String workspaceStopped();
@Key("wsAgentStopped.title")
String wsAgentStopped();
@Key("workspaceStopped.description")
String workspaceStoppedDescription();
@Key("wsAgentStopped.description")
String wsAgentStoppedDescription();
@Key("downloadOutputs")
String downloadOutputs();
}
| epl-1.0 |
Yakindu/statecharts | test-plugins/org.yakindu.sct.generator.java.test/src-gen/org/yakindu/scr/booleanexpressions/BooleanExpressionsStatemachine.java | 7570 | /** Generated by YAKINDU Statechart Tools code generator. */
package org.yakindu.scr.booleanexpressions;
public class BooleanExpressionsStatemachine implements IBooleanExpressionsStatemachine {
protected class SCInterfaceImpl implements SCInterface {
private boolean e1;
public void raiseE1() {
e1 = true;
}
private boolean myBool1;
public boolean getMyBool1() {
return myBool1;
}
public void setMyBool1(boolean value) {
this.myBool1 = value;
}
private boolean myBool2;
public boolean getMyBool2() {
return myBool2;
}
public void setMyBool2(boolean value) {
this.myBool2 = value;
}
private boolean and;
public boolean getAnd() {
return and;
}
public void setAnd(boolean value) {
this.and = value;
}
private boolean or;
public boolean getOr() {
return or;
}
public void setOr(boolean value) {
this.or = value;
}
private boolean not;
public boolean getNot() {
return not;
}
public void setNot(boolean value) {
this.not = value;
}
private boolean equal;
public boolean getEqual() {
return equal;
}
public void setEqual(boolean value) {
this.equal = value;
}
private boolean notequal;
public boolean getNotequal() {
return notequal;
}
public void setNotequal(boolean value) {
this.notequal = value;
}
protected void clearEvents() {
e1 = false;
}
}
protected SCInterfaceImpl sCInterface;
private boolean initialized = false;
public enum State {
main_region_StateA,
main_region_StateB,
$NullState$
};
private final State[] stateVector = new State[1];
private int nextStateIndex;
public BooleanExpressionsStatemachine() {
sCInterface = new SCInterfaceImpl();
}
public void init() {
this.initialized = true;
for (int i = 0; i < 1; i++) {
stateVector[i] = State.$NullState$;
}
clearEvents();
clearOutEvents();
sCInterface.setMyBool1(false);
sCInterface.setMyBool2(false);
sCInterface.setAnd(false);
sCInterface.setOr(false);
sCInterface.setNot(false);
sCInterface.setEqual(false);
sCInterface.setNotequal(false);
}
public void enter() {
if (!initialized) {
throw new IllegalStateException(
"The state machine needs to be initialized first by calling the init() function."
);
}
enterSequence_main_region_default();
}
public void runCycle() {
if (!initialized)
throw new IllegalStateException(
"The state machine needs to be initialized first by calling the init() function.");
clearOutEvents();
for (nextStateIndex = 0; nextStateIndex < stateVector.length; nextStateIndex++) {
switch (stateVector[nextStateIndex]) {
case main_region_StateA:
main_region_StateA_react(true);
break;
case main_region_StateB:
main_region_StateB_react(true);
break;
default:
// $NullState$
}
}
clearEvents();
}
public void exit() {
exitSequence_main_region();
}
/**
* @see IStatemachine#isActive()
*/
public boolean isActive() {
return stateVector[0] != State.$NullState$;
}
/**
* Always returns 'false' since this state machine can never become final.
*
* @see IStatemachine#isFinal()
*/
public boolean isFinal() {
return false;
}
/**
* This method resets the incoming events (time events included).
*/
protected void clearEvents() {
sCInterface.clearEvents();
}
/**
* This method resets the outgoing events.
*/
protected void clearOutEvents() {
}
/**
* Returns true if the given state is currently active otherwise false.
*/
public boolean isStateActive(State state) {
switch (state) {
case main_region_StateA:
return stateVector[0] == State.main_region_StateA;
case main_region_StateB:
return stateVector[0] == State.main_region_StateB;
default:
return false;
}
}
public SCInterface getSCInterface() {
return sCInterface;
}
public void raiseE1() {
sCInterface.raiseE1();
}
public boolean getMyBool1() {
return sCInterface.getMyBool1();
}
public void setMyBool1(boolean value) {
sCInterface.setMyBool1(value);
}
public boolean getMyBool2() {
return sCInterface.getMyBool2();
}
public void setMyBool2(boolean value) {
sCInterface.setMyBool2(value);
}
public boolean getAnd() {
return sCInterface.getAnd();
}
public void setAnd(boolean value) {
sCInterface.setAnd(value);
}
public boolean getOr() {
return sCInterface.getOr();
}
public void setOr(boolean value) {
sCInterface.setOr(value);
}
public boolean getNot() {
return sCInterface.getNot();
}
public void setNot(boolean value) {
sCInterface.setNot(value);
}
public boolean getEqual() {
return sCInterface.getEqual();
}
public void setEqual(boolean value) {
sCInterface.setEqual(value);
}
public boolean getNotequal() {
return sCInterface.getNotequal();
}
public void setNotequal(boolean value) {
sCInterface.setNotequal(value);
}
/* Entry action for state 'StateA'. */
private void entryAction_main_region_StateA() {
sCInterface.setMyBool1(true);
sCInterface.setMyBool2(false);
}
/* Entry action for state 'StateB'. */
private void entryAction_main_region_StateB() {
sCInterface.setAnd((sCInterface.myBool1 && sCInterface.myBool2));
sCInterface.setOr((sCInterface.myBool1 || sCInterface.myBool2));
sCInterface.setNot(!sCInterface.myBool1);
sCInterface.setEqual(sCInterface.myBool1==sCInterface.myBool2);
sCInterface.setNotequal((sCInterface.myBool1!=sCInterface.myBool2));
}
/* 'default' enter sequence for state StateA */
private void enterSequence_main_region_StateA_default() {
entryAction_main_region_StateA();
nextStateIndex = 0;
stateVector[0] = State.main_region_StateA;
}
/* 'default' enter sequence for state StateB */
private void enterSequence_main_region_StateB_default() {
entryAction_main_region_StateB();
nextStateIndex = 0;
stateVector[0] = State.main_region_StateB;
}
/* 'default' enter sequence for region main region */
private void enterSequence_main_region_default() {
react_main_region__entry_Default();
}
/* Default exit sequence for state StateA */
private void exitSequence_main_region_StateA() {
nextStateIndex = 0;
stateVector[0] = State.$NullState$;
}
/* Default exit sequence for state StateB */
private void exitSequence_main_region_StateB() {
nextStateIndex = 0;
stateVector[0] = State.$NullState$;
}
/* Default exit sequence for region main region */
private void exitSequence_main_region() {
switch (stateVector[0]) {
case main_region_StateA:
exitSequence_main_region_StateA();
break;
case main_region_StateB:
exitSequence_main_region_StateB();
break;
default:
break;
}
}
/* Default react sequence for initial entry */
private void react_main_region__entry_Default() {
enterSequence_main_region_StateA_default();
}
private boolean react() {
return false;
}
private boolean main_region_StateA_react(boolean try_transition) {
boolean did_transition = try_transition;
if (try_transition) {
if (react()==false) {
if (sCInterface.e1) {
exitSequence_main_region_StateA();
enterSequence_main_region_StateB_default();
} else {
did_transition = false;
}
}
}
return did_transition;
}
private boolean main_region_StateB_react(boolean try_transition) {
boolean did_transition = try_transition;
if (try_transition) {
if (react()==false) {
did_transition = false;
}
}
return did_transition;
}
}
| epl-1.0 |
UBPL/jive | edu.buffalo.cse.jive.debug.jdi/src/edu/buffalo/cse/jive/debug/JiveDebugPlugin.java | 5373 | package edu.buffalo.cse.jive.debug;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IProcess;
import org.osgi.framework.BundleContext;
import com.sun.jdi.VirtualMachine;
import edu.buffalo.cse.jive.core.ast.ASTFactory;
import edu.buffalo.cse.jive.core.ast.ASTPluginProxy;
import edu.buffalo.cse.jive.debug.jdi.model.IJDIManager;
import edu.buffalo.cse.jive.debug.jdi.model.IJDIModelFactory;
import edu.buffalo.cse.jive.debug.jdi.model.IModelFilter;
import edu.buffalo.cse.jive.debug.model.IJiveDebugTarget;
import edu.buffalo.cse.jive.internal.debug.jdi.JDIDebugFactoryImpl;
import edu.buffalo.cse.jive.internal.debug.jdi.model.JDIModelFactoryImpl;
import edu.buffalo.cse.jive.model.IExecutionModel;
import edu.buffalo.cse.jive.model.IJiveProject;
import edu.buffalo.cse.jive.model.factory.IStaticModelFactory.IStaticModelDelegate;
/**
* Activator that controls the plug-in life cycle and provides utility methods.
*/
@SuppressWarnings("restriction")
public class JiveDebugPlugin extends Plugin
{
/**
* The unique identifier of the plug-in.
*/
public static final String PLUGIN_ID = "edu.buffalo.cse.jive.debug"; //$NON-NLS-1$
/**
* The shared instance of the plug-in.
*/
private static JiveDebugPlugin plugin;
public static IDebugTarget createDebugTarget(final ILaunch launch, final VirtualMachine vm,
final String name, final IProcess process, final boolean allowTerminate,
final boolean allowDisconnect, final boolean resume, final IJiveProject project)
{
return JDIDebugFactoryImpl.createDebugTarget(launch, vm, name, process, allowTerminate,
allowDisconnect, resume, project);
}
public static IStaticModelDelegate createStaticModelDelegate(final IExecutionModel model,
final IJiveProject project, final VirtualMachine vm, final IModelFilter filter)
{
final IStaticModelDelegate downstream = JiveDebugPlugin.getDefault().jdiModelFactory()
.createStaticModelDelegate(model, vm, filter);
final IStaticModelDelegate upstream = ASTFactory.createStaticModelDelegate(model, project,
filter.modelCache(), downstream);
return upstream;
}
/**
* Returns the shared instance of the JIVE core plug-in.
*
* @return the shared instance
*/
public static JiveDebugPlugin getDefault()
{
return JiveDebugPlugin.plugin;
}
public static void info(final String message)
{
JiveDebugPlugin.log(IStatus.INFO, message, null);
}
public static void info(final String message, final Throwable e)
{
JiveDebugPlugin.log(IStatus.INFO, message, e);
}
/**
* Logs a status object to the Eclipse error log.
*
* @param status
* the status object to record
*/
public static void log(final IStatus status)
{
JiveDebugPlugin.getDefault().getLog().log(status);
}
/**
* Logs a string to the Eclipse error log as an <code>IStatus.ERROR</code> object.
*
* @param message
* the message to be recorded
*/
public static void log(final String message)
{
JiveDebugPlugin.log(new Status(IStatus.ERROR, JiveDebugPlugin.PLUGIN_ID, IStatus.ERROR,
message, null));
}
/**
* Logs the message associated with a throwable object to the Eclipse error log as an
* <code>IStatus.ERROR</code> object.
*
* @param e
* the throwable object whose message is recorded
*/
public static void log(final Throwable e)
{
e.printStackTrace();
JiveDebugPlugin.log(new Status(IStatus.ERROR, JiveDebugPlugin.PLUGIN_ID, IStatus.ERROR, e
.getMessage(), e));
}
public static void warn(final String message)
{
JiveDebugPlugin.log(IStatus.WARNING, message);
}
public static void warn(final String message, final Throwable e)
{
JiveDebugPlugin.log(IStatus.WARNING, message, e);
}
private static void log(final int severity, final String message)
{
JiveDebugPlugin.log(severity, message, null);
}
private static void log(final int severity, final String message, final Throwable e)
{
JiveDebugPlugin.log(new Status(severity, "edu.buffalo.cse.jive.debug.core", severity, message,
e));
}
/**
* Constructs the JIVE core plug-in. This constructor is called by the Eclipse platform and should
* not be called by clients.
*
* @throws IllegalStateException
* if the plug-in has already been instantiated
*/
public JiveDebugPlugin()
{
if (JiveDebugPlugin.plugin != null)
{
// TODO Add log message and internationalize the string literal
throw new IllegalStateException("The JIVE core plug-in class already exists.");
}
ASTPluginProxy.setOwner(this);
}
public IJDIManager jdiManager(final IJiveDebugTarget owner)
{
return jdiModelFactory().jdiManager(owner);
}
@Override
public void start(final BundleContext context) throws Exception
{
super.start(context);
JiveDebugPlugin.plugin = this;
}
@Override
public void stop(final BundleContext context) throws Exception
{
JiveDebugPlugin.plugin = null;
super.stop(context);
}
private IJDIModelFactory jdiModelFactory()
{
return JDIModelFactoryImpl.INSTANCE;
}
} | epl-1.0 |
jmchilton/TINT | projects/TropixFiles/src/api/edu/umn/msi/tropix/files/NewFileMessageQueue.java | 1418 | package edu.umn.msi.tropix.files;
import java.io.Serializable;
import edu.umn.msi.tropix.grid.credentials.Credential;
import edu.umn.msi.tropix.messaging.AsyncMessage;
import edu.umn.msi.tropix.messaging.MessageRouting;
public interface NewFileMessageQueue {
String ROUTE = MessageRouting.QUEUE_PREFIX + "newfile";
public static class NewFileMessage implements Serializable {
private String objectId;
private String fileId;
private String parentId;
private String ownerId;
private Credential credential;
public Credential getCredential() {
return credential;
}
public void setCredential(final Credential credential) {
this.credential = credential;
}
@Deprecated
public String getOwnerId() {
return ownerId;
}
@Deprecated
public void setOwnerId(final String ownerId) {
this.ownerId = ownerId;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(final String objectId) {
this.objectId = objectId;
}
public String getFileId() {
return fileId;
}
public void setFileId(final String fileId) {
this.fileId = fileId;
}
public String getParentId() {
return parentId;
}
public void setParentId(final String parentId) {
this.parentId = parentId;
}
}
@AsyncMessage
void newFile(NewFileMessage message);
}
| epl-1.0 |
gengstrand/clojure-news-feed | server/feed3/src/main/java/info/glennengstrand/db/ParticipantDAO.java | 562 | package info.glennengstrand.db;
import org.skife.jdbi.v2.DBI;
import com.google.inject.Inject;
import info.glennengstrand.api.Participant;
public class ParticipantDAO extends RelationalDAO<Participant> {
public Participant fetchParticipant(Long id) {
return fetchSingle("call FetchParticipant(:id)", new ParticipantMapper(id), q -> q.bind("id", id));
}
public long upsertParticipant(String name) {
return upsert("call UpsertParticipant(:moniker)", q -> q.bind("moniker", name));
}
@Inject
public ParticipantDAO(DBI dbi) {
super(dbi);
}
}
| epl-1.0 |
jmini/markdowikitext | markdowikitext.commonmark/src/markdowikitext/commonmark/refspec/cases/EmphasisAndStrongEmphasis67.java | 585 | package markdowikitext.commonmark.refspec.cases;
import markdowikitext.commonmark.refspec.RefSpecCase;
public class EmphasisAndStrongEmphasis67 extends RefSpecCase {
public EmphasisAndStrongEmphasis67() {
super(createInput(), createOutput());
}
public static String createInput() {
StringBuilder sb = new StringBuilder();
sb.append("__foo _bar_ baz__");
return sb.toString();
}
public static String createOutput() {
StringBuilder sb = new StringBuilder();
sb.append("<p><strong>foo <em>bar</em> baz</strong></p>");
return sb.toString();
}
} | epl-1.0 |
rpau/AutoRefactor | samples/src/test/java/org/autorefactor/jdt/internal/ui/fix/all/samples_out/NoMalformedTreeExceptionSample.java | 1515 | /*
* AutoRefactor - Eclipse plugin to automatically refactor Java code bases.
*
* Copyright (C) 2014 Jean-Noël Rouvignac - initial API and implementation
*
* 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
* 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 under LICENSE-GNUGPL. If not, see
* <http://www.gnu.org/licenses/>.
*
*
* 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 under LICENSE-ECLIPSE, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.autorefactor.jdt.internal.ui.fix.all.samples_out;
public class NoMalformedTreeExceptionSample {
public void commentRefactoringsInteractsWithCodeRefactoring(Object o) {
if (o == null) {
System.out.println("null");
} else /* Convert to block comment */
if ("true".equals(o)) {
System.out.println("true");
}
}
}
| epl-1.0 |
sleshchenko/che | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/FileCleaner.java | 3827 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* 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:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.core.util;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.AbstractModule;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import org.eclipse.che.commons.lang.IoUtil;
import org.eclipse.che.commons.lang.Pair;
import org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Delete files and directories added with method {@link @addFile}. In environments with multiple
* class loaders, {@code FileCleaner} should be stopped if it isn't needed. In Codenvy environment
* {@code FileCleaner} is stopped automatically by {@link FileCleanerModule} otherwise need call
* method {@link #stop()} manually.
*
* @author andrew00x
*/
public class FileCleaner {
private static final Logger LOG = LoggerFactory.getLogger(FileCleaner.class);
/** Number of attempts to delete file or directory before start write log error messages. */
static int logAfterAttempts = 10;
private static ScheduledExecutorService exec =
Executors.newSingleThreadScheduledExecutor(
new ThreadFactoryBuilder()
.setNameFormat("FileCleaner")
.setUncaughtExceptionHandler(LoggingUncaughtExceptionHandler.getInstance())
.setDaemon(true)
.build());
static {
exec.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
clean();
}
},
30,
30,
TimeUnit.SECONDS);
}
private static ConcurrentLinkedQueue<Pair<File, Integer>> files = new ConcurrentLinkedQueue<>();
/** Registers new file or directory in FileCleaner. */
public static void addFile(File file) {
files.offer(Pair.of(file, 0));
}
/** Stops FileCleaner. */
public static void stop() {
exec.shutdownNow();
try {
exec.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
}
clean();
files.clear();
LOG.info("File cleaner is stopped");
}
private static void clean() {
Pair<File, Integer> pair;
final Set<Pair<File, Integer>> failToDelete = new HashSet<>();
while ((pair = files.poll()) != null) {
final File file = pair.first;
int deleteAttempts = pair.second;
if (file.exists()) {
if (!IoUtil.deleteRecursive(file)) {
failToDelete.add(Pair.of(file, ++deleteAttempts));
if (deleteAttempts > logAfterAttempts) {
LOG.error("Unable delete file '{}' after {} tries", file, deleteAttempts);
}
} else if (LOG.isDebugEnabled()) {
LOG.debug("Delete file '{}'", file);
}
}
}
if (!failToDelete.isEmpty()) {
files.addAll(failToDelete);
}
}
/** Guice module that stops FileCleaner when Guice container destroyed. */
public static class FileCleanerModule extends AbstractModule {
@Override
protected void configure() {
bind(Finalizer.class).asEagerSingleton();
}
}
/** Helper component that stops FileCleaner. */
static class Finalizer {
@PreDestroy
void stop() {
FileCleaner.stop();
}
}
private FileCleaner() {}
}
| epl-1.0 |
kyloth/serleena-cloud | src/test/java/com/kyloth/serleenacloud/persistence/jdbc/ElevationRectDaoIntegrationTest.java | 3640 | /******************************************************************************
* Copyright (c) 2015 Nicola Mometto
* 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:
* Nicola Mometto
* Antonio Cavestro
* Sebastiano Valle
* Gabriele Pozzan
******************************************************************************/
/**
* Name: ElevationRectDaoIntegrationTest.java
* Package: com.kyloth.serleenacloud.persistence
* Author: Nicola Mometto
*
* History:
* Version Programmer Changes
* 1.0.0 Nicola Mometto Creazione file e scrittura
* codice e documentazione Javadoc
*/
package com.kyloth.serleenacloud.persistence.jdbc;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import java.util.Iterator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import com.kyloth.serleenacloud.persistence.jdbc.JDBCDataSource;
import com.kyloth.serleenacloud.persistence.IElevationRectDao;
import com.kyloth.serleenacloud.datamodel.geometry.ElevationRect;
import com.kyloth.serleenacloud.datamodel.geometry.Rect;
import com.kyloth.serleenacloud.datamodel.geometry.Point;
/**
* Contiene test per la classe ElevationRectDao.
*
* @author Nicola Mometto <nicola.mometto@studenti.unipd.it>
* @version 1.0.0
*/
public class ElevationRectDaoIntegrationTest {
private static ApplicationContext context;
private static JDBCDataSource ds;
private static JdbcTemplate tpl;
private static IElevationRectDao ecd;
/**
* Inizializza i campi dati necessari alla conduzione dei test.
*/
@BeforeClass
public static void initialize() {
context = new ClassPathXmlApplicationContext("Spring-ModuleTest.xml");
ds = (JDBCDataSource) context.getBean("dataSource");
tpl = ds.getTpl();
String insert_1="INSERT INTO ElevationRect (Height, NWLongitude, NWLatitude, SELongitude, SELatitude) VALUES (2, 3.5, 15.77, 12.54, 4.18);";
String insert_2="INSERT INTO ElevationRect (Height, NWLongitude, NWLatitude, SELongitude, SELatitude) VALUES (4, 2.2, 16.18, 3.5, 14);";
String insert_3="INSERT INTO ElevationRect (Height, NWLongitude, NWLatitude, SELongitude, SELatitude) VALUES (1, 3.2, 10.01, 15.4, 12.3);";
tpl.update(insert_1);
tpl.update(insert_2);
tpl.update(insert_3);
ecd = ds.elevationRectDao();
}
/**
* Rilascia l'ApplicationContext per i test successivi.
*/
@AfterClass
public static void cleanUp() {
((ConfigurableApplicationContext)context).close();
}
/**
* Verifica che il metodo findAll restituisca gli ElevationRects
* la cui area di pertinenza intersechi quella fornita come parametro.
*/
@Test
public void testFindAll() {
Rect region = new Rect(new Point(16.18, 3.2), new Point(13.12, 4.9));
Iterable<ElevationRect> el = ecd.findAll(region);
Iterator<ElevationRect> i_el = el.iterator();
ElevationRect ec_1 = i_el.next();
assertTrue(ec_1.getHeight() == 2);
ElevationRect ec_2 = i_el.next();
assertTrue(ec_2.getHeight() == 4);
assertFalse(i_el.hasNext());
}
}
| epl-1.0 |
junit-team/junit-lambda | junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/TestInstancePreDestroyCallback.java | 2238 | /*
* Copyright 2015-2020 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package org.junit.jupiter.api.extension;
import static org.apiguardian.api.API.Status.STABLE;
import org.apiguardian.api.API;
/**
* {@code TestInstancePreDestroyCallback} defines the API for {@link Extension
* Extensions} that wish to process test instances <em>after</em> they have been
* used in tests but <em>before</em> they are destroyed.
*
* <p>Common use cases include releasing resources that have been created for
* the test instance, invoking custom clean-up methods on the test instance, etc.
*
* <p>Extensions that implement {@code TestInstancePreDestroyCallback} must be
* registered at the class level if the test class is configured with
* {@link org.junit.jupiter.api.TestInstance.Lifecycle @TestInstance(Lifecycle.PER_CLASS)}
* semantics. If the test class is configured with
* {@link org.junit.jupiter.api.TestInstance.Lifecycle @TestInstance(Lifecycle.PER_METHOD)}
* semantics, {@code TestInstancePreDestroyCallback} extensions may be registered
* at the class level or at the method level. In the latter case, the
* {@code TestInstancePreDestroyCallback} extension will only be applied to the
* test method for which it is registered.
*
* <h3>Constructor Requirements</h3>
*
* <p>Consult the documentation in {@link Extension} for details on constructor
* requirements.
*
* @since 5.6
* @see #preDestroyTestInstance(ExtensionContext)
* @see TestInstancePostProcessor
* @see TestInstanceFactory
* @see ParameterResolver
*/
@FunctionalInterface
@API(status = STABLE, since = "5.7")
public interface TestInstancePreDestroyCallback extends Extension {
/**
* Callback for processing a test instance before it is destroyed.
*
* @param context the current extension context; never {@code null}
* @see ExtensionContext#getTestInstance()
* @see ExtensionContext#getRequiredTestInstance()
*/
void preDestroyTestInstance(ExtensionContext context) throws Exception;
}
| epl-1.0 |
AchimHentschel/smarthome | bundles/core/org.eclipse.smarthome.core.thing/src/main/java/org/eclipse/smarthome/core/thing/internal/profiles/RawButtonToggleProfile.java | 2117 | /**
* Copyright (c) 2014-2017 by the respective copyright holders.
* 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.eclipse.smarthome.core.thing.internal.profiles;
import org.eclipse.smarthome.core.events.EventPublisher;
import org.eclipse.smarthome.core.items.Item;
import org.eclipse.smarthome.core.items.events.ItemEventFactory;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.thing.CommonTriggerEvents;
import org.eclipse.smarthome.core.thing.link.ItemChannelLink;
import org.eclipse.smarthome.core.thing.profiles.ProfileTypeUID;
import org.eclipse.smarthome.core.thing.profiles.TriggerProfile;
/**
* This profile allows a channel of the "system:rawbutton" type to be bound to an item.
*
* It reads the triggered events and uses the item's current state and toggles it once it detects that the
* button was pressed.
*
* @author Simon Kaufmann - initial contribution and API.
*
*/
public class RawButtonToggleProfile implements TriggerProfile {
public static final ProfileTypeUID UID = new ProfileTypeUID(ProfileTypeUID.SYSTEM_SCOPE, "rawbutton-toggle",
"Raw Button Toggle");
@Override
public void onTrigger(EventPublisher eventPublisher, ItemChannelLink link, String event, Item item) {
if (CommonTriggerEvents.PRESSED.equals(event)) {
if (item.getAcceptedCommandTypes().contains(OnOffType.class)) {
if (OnOffType.ON.equals(item.getStateAs(OnOffType.class))) {
eventPublisher.post(ItemEventFactory.createCommandEvent(link.getItemName(), OnOffType.OFF,
link.getLinkedUID().toString()));
} else {
eventPublisher.post(ItemEventFactory.createCommandEvent(link.getItemName(), OnOffType.ON,
link.getLinkedUID().toString()));
}
}
}
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/t24/ui/com.odcgroup.t24.version.editor/src/main/java/com/odcgroup/t24/version/editor/translation/command/VersionTranslationRemoveCommand.java | 3405 | package com.odcgroup.t24.version.editor.translation.command;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.Parameterization;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.core.expressions.IEvaluationContext;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.handlers.IHandlerService;
import com.odcgroup.t24.version.editor.VersionEditorActivator;
import com.odcgroup.t24.version.editor.ui.VersionMultiPageEditor;
import com.odcgroup.translation.ui.command.TranslationRemoveCommand;
import com.odcgroup.translation.ui.views.ITranslationModel;
/**
* @author atr
*/
public class VersionTranslationRemoveCommand extends TranslationRemoveCommand {
private static String REMOVE_COMMAND_ID = "com.odcgroup.t24.version.editor.translation.remove";
protected String getCommandId() {
return VersionTranslationRemoveCommand.REMOVE_COMMAND_ID;
}
@Override
protected void initializeTexts() {
setInheritedInformation("Translation inherited from the Domain");
setNotInheritedInformation("Local translation overriding the Domain one");
setNotInheritedName("Remove Local Translation");
setNotInheritedToolTip("Revert to Domain translation");
setStandardName("Remove Translation");
setStandardToolTip("Remove Translation");
}
@Override
public void execute(String newText) throws CoreException {
IEditorPart editorPart = getActiveEditorPart();
if (editorPart != null) {
// Extract useful parameters needed for the command
IWorkbenchPartSite site = editorPart.getSite();
// Invoke the command
IHandlerService handlerService = (IHandlerService) site.getService(IHandlerService.class);
ICommandService commandService = (ICommandService) site.getService(ICommandService.class);
if (editorPart instanceof VersionMultiPageEditor) {
VersionMultiPageEditor vEditor = (VersionMultiPageEditor) editorPart;
EditingDomain editingDomain = vEditor.getVersionFormEditor().getEditingDomain();
CommandStack commandStack = editingDomain.getCommandStack();
try {
// Get the command and assign values to parameters
Command command = commandService.getCommand(getCommandId());
ParameterizedCommand parmCommand = new ParameterizedCommand(command, new Parameterization[] {});
// Prepare the evaluation context
IEvaluationContext ctx = handlerService.getCurrentState();
ctx.addVariable("model", getModel());
ctx.addVariable("commandStack", commandStack);
ctx.addVariable("editingDomain", editingDomain);
// Execute the command
handlerService.executeCommandInContext(parmCommand, null, ctx);
} catch (Exception ex) {
IStatus status = new Status(IStatus.ERROR, VersionEditorActivator.PLUGIN_ID,
"Error while executing command to remove translation", ex);
throw new CoreException(status);
}
}
} else {
/** @TODO log warn no active editorPart, should never occur */
}
}
/**
* @param model
*/
public VersionTranslationRemoveCommand(ITranslationModel model) {
super(model);
}
}
| epl-1.0 |
blackberry/Eclipse-JDE | net.rim.ejde/src/net/rim/ejde/internal/ui/launchers/RunningFledgeLaunchShortcut.java | 1096 | /*
* Copyright (c) 2010-2012 Research In Motion Limited. All rights reserved.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License, Version 1.0,
* which accompanies this distribution and is available at
*
* http://www.eclipse.org/legal/epl-v10.html
*
*/
package net.rim.ejde.internal.ui.launchers;
import net.rim.ejde.internal.launching.IRunningFledgeLaunchConstants;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchManager;
/**
* @author dmeng
*
*/
public class RunningFledgeLaunchShortcut extends AbstractLaunchShortcut {
/*
* (non-Javadoc)
*
* @seeorg.eclipse.jdt.internal.debug.ui.launcher.JavaLaunchShortcut# getConfigurationType()
*/
protected ILaunchConfigurationType getConfigurationType() {
ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
return lm.getLaunchConfigurationType( IRunningFledgeLaunchConstants.LAUNCH_CONFIG_ID );
}
}
| epl-1.0 |
edgarmueller/emfstore-rest | bundles/org.eclipse.emf.emfstore.client.ui/src/org/eclipse/emf/emfstore/internal/client/ui/dialogs/merge/util/DefaultMergeLabelProvider.java | 1880 | /*******************************************************************************
* Copyright (c) 2012-2013 EclipseSource Muenchen GmbH 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:
* ovonwesen
******************************************************************************/
package org.eclipse.emf.emfstore.internal.client.ui.dialogs.merge.util;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.emfstore.internal.client.model.changeTracking.merging.util.MergeLabelProvider;
/**
* Default label provider for merges.
*
* @author ovonwesen
*
*/
public class DefaultMergeLabelProvider implements MergeLabelProvider {
private AdapterFactoryLabelProvider adapterFactory;
/**
* Default constructor.
*/
public DefaultMergeLabelProvider() {
adapterFactory = UIDecisionUtil.getAdapterFactory();
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.model.changeTracking.merging.util.MergeLabelProvider#getPriority()
*/
public int getPriority() {
return 10;
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.model.changeTracking.merging.util.MergeLabelProvider#getText(org.eclipse.emf.ecore.EObject)
*/
public String getText(EObject modelElement) {
return adapterFactory.getText(modelElement);
}
/**
*
* {@inheritDoc}
*
* @see org.eclipse.emf.emfstore.internal.client.model.changeTracking.merging.util.MergeLabelProvider#dispose()
*/
public void dispose() {
adapterFactory.dispose();
}
}
| epl-1.0 |
emigonza/POStest | src/com/jpos/POStest/FiscalPrinterPanel.java | 131927 | /*
* This software is provided "AS IS". The JavaPOS working group (including
* each of the Corporate members, contributors and individuals) MAKES NO
* REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. The JavaPOS working group shall not be liable for
* any damages suffered as a result of using, modifying or distributing this
* software or its derivatives. Permission to use, copy, modify, and distribute
* the software and its documentation for any purpose is hereby granted
*
* -----------------------------------------------------------------------------
* contribution of interface and implementation Bracci A. Sistemi Digitali s.r.l. Pisa (Italy)
*/
package com.jpos.POStest;
import javax.swing.*;
import jpos.events.OutputCompleteEvent;
import jpos.events.ErrorEvent;
import jpos.events.ErrorListener;
import java.awt.*;
import java.awt.event.*;
import jpos.FiscalPrinterConst;
import jpos.*;
import jpos.events.*;
public class FiscalPrinterPanel extends Component implements StatusUpdateListener,OutputCompleteListener,ErrorListener{
private static final long serialVersionUID = -1141207648205875965L;
protected MainButtonPanel mainButtonPanel;
private FiscalPrinter fiscalPrinter;
private String defaultLogicalName = "fiscalprinter";
private JCheckBox deviceEnabledCB;
private JCheckBox freezeEventsCB;
private JCheckBox doubleWidthCB;
private JCheckBox duplicateReceiptCB;
private JCheckBox asyncModeCB;
private JCheckBox checkTotalCB;
private JCheckBox flagWhenIdleCB;
private JCheckBox clearOutputForErrorCB;
private JList itemList;
private DefaultListModel itemListModel;
private JList propList;
private DefaultListModel propListModel;
private JComboBox paymantFormCombo;
private JComboBox vatIdCombo;
private JComboBox vatIdCombo_2;
private JComboBox adjustmentTypeCombo;
private JComboBox reportTypeCombo;
private JComboBox totalTypeCombo;
private JRadioButton firmwareRB;
private JRadioButton printerIDRB;
private JRadioButton currentTotalRB;
private JRadioButton grandTotalRB;
private JRadioButton mitVoidRB;
private JRadioButton fiscalRecRB;
private JRadioButton receiptNumberRB;
private JRadioButton refundRB;
private JRadioButton fiscalRecVoidRB;
private JRadioButton nonFiscalRecRB;
private JRadioButton descriptionLengthRB;
private JRadioButton zReportRB;
private JRadioButton dayTotalizerRB;
private JRadioButton grandTotalizerRB;
private JRadioButton currentRecTotalRB;
MethodListener methodListener = new MethodListener();
private JButton beginFiscalReceiptButton;
private JButton beginNonFiscalButton;
private JButton endNonFiscalButton;
private JButton printNormalButton;
private JButton printRecItemButton;
private JButton printRecItemAdjButton;
private JButton printRecRefundButton;
private JButton printRecSubTotalButton;
private JButton printRecTotalButton;
private JButton printDuplicateRecButton;
private JButton printRecVoidButton;
private JButton printRecRefundVoidButton;
private JButton printRecVoidItemButton;
private JButton endFiscalReceiptButton;
private JButton printReportButton;
private JButton printXReportButton;
private JButton printZReportButton;
private JButton setPrinterProp;
private JButton getDataButton;
private JButton getTotalizerButton;
private JButton getDateButton;
private JButton printPeriodicTotalReportButton;
private JButton printerStatusButton;
private JButton dayOpenedButton;
private JButton remainingFiscalMemoryButton;
private JButton showPropertyButton;
private JButton beginTrainingButton;
private JButton endTrainingButton;
private JButton clearOutPutButton;
private JButton getErrorLevelButton;
private JButton getPropListButton;
private JButton directIoButton;
private JButton getAdditionalHeaderButton;
private JButton getAdditionalTrailerButton;
private JButton resetPrinterButton;
private JButton clearFieldsButton;
private JButton getTrainingStateButton;
private JButton getCheckHealthButton;
private JButton getOutPutIdButton;
private JButton setVatTableButton;
private JButton clearOutButton;
private JButton clearErrorButton;
private JButton printRecMessageButton;
private JButton recSubTotalDiscountButton;
private JButton recSubTotalDiscountVoidButton;
private JTextField itemDescription;
private JTextField itemPrice;
private JTextField itemQuantity;
private JTextField itemUnitPrice;
private JTextField itemVatInfo;
private JTextField unitName;
private JTextField reportFrom;
private JTextField reportTo;
private JTextField additionalHeaderTxt;
private JTextField additionalTrailerTxt;
private JTextField dateTxt;
private JTextField headerTxt;
private JTextField trailerTxt;
private JTextField vatIdTxt;
private JTextField vatValueTxt;
private JTextField headerLineNumberTxt;
private JTextField itemAmountPercAdjTxt;
private JTextField directIoCommand;
private JTextField directIoData;
private JTextField directIoObject;
private JTextField checkHealthTxt;
private JTextField preLineTxt;
private JTextField postLineTxt;
private JTextField recMessageTxt;
private JTextArea nonFiscalTxt;
private JLabel label;
private long TOTAL=0;
private long amountFactorDecimal=1;
private int quantityFactorDecimal=1;
private int getDataType=jpos.FiscalPrinterConst.FPTR_GD_FIRMWARE;
private int adjustmentType=jpos.FiscalPrinterConst.FPTR_AT_AMOUNT_DISCOUNT;
private int reportType=jpos.FiscalPrinterConst.FPTR_RT_ORDINAL;
private String[] adjType={"Amount Discount","Amount Surcharge","Perc. Discount","Perc. Surcharge"};
private int numAdjType=4;
private int[] valuesGetData={0};
private String[] strGetData={""};
private java.util.Timer updateStatusTimer;
StatusTimerUpdateTask updateStatusTask;
private boolean ver_19_complient = false;
private boolean ver_18_complient = false;
public FiscalPrinterPanel() {
fiscalPrinter = new FiscalPrinter();
fiscalPrinter.addStatusUpdateListener(this);
fiscalPrinter.addErrorListener(this);
fiscalPrinter.addOutputCompleteListener(this);
updateStatusTimer = new java.util.Timer(true);
updateStatusTask = new StatusTimerUpdateTask();
updateStatusTimer.schedule(updateStatusTask, 200, 200);
}
public Component make() {
JPanel mainPanel = new JPanel(false);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainButtonPanel = new MainButtonPanel(methodListener,defaultLogicalName);
mainPanel.add(mainButtonPanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 30));
mainPanel.add(buttonPanel);
JPanel subPanel = new JPanel();
subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.X_AXIS));
JPanel propPanel = new JPanel();
propPanel.setLayout(new BoxLayout(propPanel, BoxLayout.Y_AXIS));
deviceEnabledCB = new JCheckBox("Device enabled");
propPanel.add(deviceEnabledCB);
freezeEventsCB = new JCheckBox("Freeze events");
propPanel.add(freezeEventsCB);
duplicateReceiptCB = new JCheckBox("Duplicate Receipt");
propPanel.add(duplicateReceiptCB);//
asyncModeCB = new JCheckBox("Async Mode");
propPanel.add(asyncModeCB);
checkTotalCB = new JCheckBox("Check Total");
propPanel.add(checkTotalCB);
flagWhenIdleCB = new JCheckBox("Flag When Idle");
propPanel.add(flagWhenIdleCB);
beginTrainingButton = new JButton("Begin Training");
beginTrainingButton.setMaximumSize(new Dimension(160,17));
beginTrainingButton.setPreferredSize(new Dimension(160,17));
beginTrainingButton.setActionCommand("beginTraining");
beginTrainingButton.addActionListener(methodListener);
beginTrainingButton.setAlignmentX(Component.TOP_ALIGNMENT);
beginTrainingButton.setEnabled(false);
propPanel.add(beginTrainingButton);
endTrainingButton = new JButton("End Training");
endTrainingButton.setMaximumSize(new Dimension(160,17));
endTrainingButton.setPreferredSize(new Dimension(160,17));
endTrainingButton.setActionCommand("endTraining");
endTrainingButton.addActionListener(methodListener);
endTrainingButton.setAlignmentX(Component.TOP_ALIGNMENT);
endTrainingButton.setEnabled(false);
propPanel.add(endTrainingButton);
clearOutButton = new JButton("Clear OutPut");
clearOutButton.setMaximumSize(new Dimension(160,17));
clearOutButton.setPreferredSize(new Dimension(160,17));
clearOutButton.setActionCommand("clearOut");
clearOutButton.addActionListener(methodListener);
clearOutButton.setAlignmentX(Component.TOP_ALIGNMENT);
clearOutButton.setEnabled(false);
propPanel.add(clearOutButton);
clearErrorButton = new JButton("Clear Error");
clearErrorButton.setMaximumSize(new Dimension(160,17));
clearErrorButton.setPreferredSize(new Dimension(160,17));
clearErrorButton.setActionCommand("clearError");
clearErrorButton.addActionListener(methodListener);
clearErrorButton.setAlignmentX(Component.TOP_ALIGNMENT);
clearErrorButton.setEnabled(false);
propPanel.add(clearErrorButton);
propPanel.add(Box.createVerticalGlue());
subPanel.add(propPanel);
deviceEnabledCB.setEnabled(false);
freezeEventsCB.setEnabled(false);
duplicateReceiptCB.setEnabled(false);
asyncModeCB.setEnabled(false);
checkTotalCB.setEnabled(false);
flagWhenIdleCB.setEnabled(false);
CheckBoxListener cbListener = new CheckBoxListener();
deviceEnabledCB.addItemListener(cbListener);
freezeEventsCB.addItemListener(cbListener);
duplicateReceiptCB.addItemListener(cbListener);
asyncModeCB.addItemListener(cbListener);
checkTotalCB.addItemListener(cbListener);
flagWhenIdleCB.addItemListener(cbListener);
JTabbedPane tabbedPane = new JTabbedPane();
// tabbedPane.setLayout(new BoxLayout(tabbedPane, BoxLayout.Y_AXIS));
FiscalPrinterSettingPanel fpt = new FiscalPrinterSettingPanel();
tabbedPane.addTab("Printer Setting", null, fpt.make(), "PrinterSetting");
FiscalReceiptPanel frp = new FiscalReceiptPanel();
tabbedPane.addTab("Fiscal Receipt", null, frp.make(), "FiscalReceipt");
NonFiscalPanel nfp = new NonFiscalPanel();
tabbedPane.addTab("Non Fiscal Printing", null, nfp.make(), "NonFiscalPriting");
FiscalPrinterFscReportPanel ffr=new FiscalPrinterFscReportPanel();
tabbedPane.addTab("Fiscal Report", null, ffr.make(), "FiscalReport");
FiscalPrinterStatusPanel fps=new FiscalPrinterStatusPanel();
tabbedPane.addTab("Fiscal Printer Status", null, fps.make(), "PrinterStatus");
DirectIOPanel dct=new DirectIOPanel();
tabbedPane.addTab("Direct IO", null, dct.make(), "directIO");
//DirectIOPanel
subPanel.add(tabbedPane);
subPanel.setAlignmentY(Component.TOP_ALIGNMENT);
mainPanel.add(subPanel);
mainPanel.add(Box.createVerticalGlue());
return mainPanel;
}
private void setEnableButtonTo(boolean param){
deviceEnabledCB.setEnabled(param);
freezeEventsCB.setEnabled(param);
duplicateReceiptCB.setEnabled(param);
asyncModeCB.setEnabled(param);
checkTotalCB.setEnabled(param);
flagWhenIdleCB.setEnabled(param);
beginFiscalReceiptButton.setEnabled(param);
printRecItemButton.setEnabled(param);
printRecItemAdjButton.setEnabled(param);
endFiscalReceiptButton.setEnabled(param);
printRecRefundButton.setEnabled(param);
printRecSubTotalButton.setEnabled(param);
printRecTotalButton.setEnabled(param);
printRecVoidButton.setEnabled(param);
printRecRefundVoidButton.setEnabled(param);
printRecVoidItemButton.setEnabled(param);
printReportButton.setEnabled(param);
printXReportButton.setEnabled(param);
printZReportButton.setEnabled(param);
printDuplicateRecButton.setEnabled(param);
beginNonFiscalButton.setEnabled(param);
endNonFiscalButton.setEnabled(param);
printNormalButton.setEnabled(param);
setPrinterProp.setEnabled(param);
paymantFormCombo.setEnabled(param);
vatIdCombo.setEnabled(param);
vatIdCombo_2.setEnabled(param);
getDataButton.setEnabled(param);
getDateButton.setEnabled(param);
getTotalizerButton.setEnabled(param);
showPropertyButton.setEnabled(param);
printPeriodicTotalReportButton.setEnabled(param);
printerStatusButton.setEnabled(param);
dayOpenedButton.setEnabled(param);
getErrorLevelButton.setEnabled(param);
getOutPutIdButton.setEnabled(param);
remainingFiscalMemoryButton.setEnabled(param);
getPropListButton.setEnabled(param);
directIoButton.setEnabled(param);
getAdditionalHeaderButton.setEnabled(param);
getAdditionalTrailerButton.setEnabled(param);
resetPrinterButton.setEnabled(param);
getTrainingStateButton.setEnabled(param);
getCheckHealthButton.setEnabled(param);
setVatTableButton.setEnabled(param);
clearOutButton.setEnabled(param);
clearErrorButton.setEnabled(param);
printRecMessageButton.setEnabled(param);
recSubTotalDiscountButton.setEnabled(param);
recSubTotalDiscountVoidButton.setEnabled(param);
}
public void errorOccurred(ErrorEvent errorEvent) {
String errorCodestr=String.valueOf(errorEvent.getErrorCode());
String errorExtstr=String.valueOf(errorEvent.getErrorCodeExtended());
String msg="Occurred Error : ("+errorCodestr+","+errorExtstr+")";
itemListModel.addElement(msg);
if(clearOutputForErrorCB.isSelected()){
errorEvent.setErrorResponse(jpos.JposConst.JPOS_ER_CLEAR);
}
}
public void outputCompleteOccurred(OutputCompleteEvent outputCompleteEvent) {
String msg="Completed Async Output N. : "+String.valueOf(outputCompleteEvent.getOutputID());
itemListModel.addElement(msg);
}
public void statusUpdateOccurred(StatusUpdateEvent sue) {
String msg = "Status Update Event: ";
switch(sue.getStatus()){
case FiscalPrinterConst.FPTR_SUE_COVER_OK:
msg += "Cover is OK\n";
break;
case FiscalPrinterConst.FPTR_SUE_COVER_OPEN:
msg += "Cover is Open\n";
break;
case FiscalPrinterConst.FPTR_SUE_JRN_EMPTY:
msg += "Jrn is Empty\n";
break;
case FiscalPrinterConst.FPTR_SUE_JRN_NEAREMPTY:
msg += "Jrn is NearEmpty\n";
break;
case FiscalPrinterConst.FPTR_SUE_JRN_PAPEROK:
msg += "Jrn is OK\n";
break;
case FiscalPrinterConst.FPTR_SUE_REC_EMPTY:
msg += "Rec is Empty\n";
break;
case FiscalPrinterConst.FPTR_SUE_REC_NEAREMPTY:
msg += "Rec is NearEmpty\n";
break;
case FiscalPrinterConst.FPTR_SUE_REC_PAPEROK:
msg += "Rec is OK\n";
break;
case jpos.JposConst.JPOS_S_IDLE:
msg += "printer is IDLE";
flagWhenIdleCB.setSelected(false);
break;
}
itemListModel.addElement(msg);
}
/** Listens to the method buttons. */
private String decodeErrorStation(int errStat){
String errStatSTR="UNKNOWN";
switch(errStat){
case jpos.FiscalPrinterConst.FPTR_S_JOURNAL:errStatSTR="JOURNAL";break;
case jpos.FiscalPrinterConst.FPTR_S_JOURNAL_RECEIPT:errStatSTR="JOURNAL RECEIPT";break;
case jpos.FiscalPrinterConst.FPTR_S_RECEIPT:errStatSTR="RECEIPT";break;
case jpos.FiscalPrinterConst.FPTR_S_SLIP:errStatSTR="SLIP";break;
}
return errStatSTR;
}
private String decodeErrorLevel(int errLev){
String errLevSTR="UNKNOWN";
switch(errLev){
case jpos.FiscalPrinterConst.FPTR_EL_NONE:errLevSTR="NONE";break;
case jpos.FiscalPrinterConst.FPTR_EL_FATAL:errLevSTR="FATAL";break;
case jpos.FiscalPrinterConst.FPTR_EL_RECOVERABLE:errLevSTR="RECOVERABLE";break;
case jpos.FiscalPrinterConst.FPTR_EL_BLOCKED:errLevSTR="BLOCKED";break;
}
return errLevSTR;
}
private String decodeDeviceState(int state){
String stateSTR="UNKNOWN";
switch(state){
case jpos.JposConst.JPOS_S_BUSY:stateSTR="BUSY";break;
case jpos.JposConst.JPOS_S_IDLE:stateSTR="IDLE";break;
case jpos.JposConst.JPOS_S_CLOSED:stateSTR="CLOSED";break;
case jpos.JposConst.JPOS_S_ERROR:stateSTR="ERROR";break;
}
return stateSTR;
}
private String decodeState(int state){
String stateSTR="UNKNOWN";
switch(state){
case jpos.FiscalPrinterConst.FPTR_PS_FISCAL_RECEIPT:stateSTR="FISCAL RECEIPT";break;
case jpos.FiscalPrinterConst.FPTR_PS_MONITOR:stateSTR="MONITOR";break;
case jpos.FiscalPrinterConst.FPTR_PS_REPORT:stateSTR="REPORT";break;
case jpos.FiscalPrinterConst.FPTR_PS_FISCAL_RECEIPT_ENDING:stateSTR="FISCAL RECEIPT ENDING";break;
case jpos.FiscalPrinterConst.FPTR_PS_FISCAL_RECEIPT_TOTAL:stateSTR="FISCAL RECEIPT TOTAL";break;
case jpos.FiscalPrinterConst.FPTR_PS_LOCKED:stateSTR="LOCKED";break;
case jpos.FiscalPrinterConst.FPTR_PS_NONFISCAL:stateSTR="NON FISCAL";break;
}
return stateSTR;
}
private String decodeCountryCode(int cc){
String countrySTR="Unknown";
switch(cc){
case jpos.FiscalPrinterConst.FPTR_CC_BRAZIL:countrySTR="BRAZIL";break;
case jpos.FiscalPrinterConst.FPTR_CC_BULGARIA:countrySTR="BULGARIA";break;
case jpos.FiscalPrinterConst.FPTR_CC_GREECE:countrySTR="GREECE";break;
case jpos.FiscalPrinterConst.FPTR_CC_HUNGARY:countrySTR="HUNGARY";break;
case jpos.FiscalPrinterConst.FPTR_CC_ITALY:countrySTR="ITALY";break;
case jpos.FiscalPrinterConst.FPTR_CC_POLAND:countrySTR="POLAND";break;
case jpos.FiscalPrinterConst.FPTR_CC_ROMANIA:countrySTR="ROMANIA";break;
case jpos.FiscalPrinterConst.FPTR_CC_RUSSIA:countrySTR="RUSSIA";break;
case jpos.FiscalPrinterConst.FPTR_CC_TURKEY:countrySTR="TURKEY";break;
}
countrySTR="Country : "+countrySTR;
return countrySTR;
}
private String decodeTypeMessage(int cc){
String typeMsg="Unknown";
switch(cc){
case jpos.FiscalPrinterConst.FPTR_MT_FREE_TEXT:typeMsg="FREE TEXT";break;
case jpos.FiscalPrinterConst.FPTR_MT_EMPTY_LINE:typeMsg="EMPTY LINE";break;
}
typeMsg="Type Message : "+typeMsg;
return typeMsg;
}
private int getTotalizerType(String[] strLab){
int totzType=jpos.FiscalPrinterConst.FPTR_GT_ITEM;
int index=totalTypeCombo.getSelectedIndex();
String str="";
switch(index){
case 0:totzType=jpos.FiscalPrinterConst.FPTR_GT_ITEM;
str="Item Totalizer: ";break;
case 1:totzType=jpos.FiscalPrinterConst.FPTR_GT_REFUND;
str="Refund Totalizer : ";break;
case 2:totzType=jpos.FiscalPrinterConst.FPTR_GT_ITEM_VOID;
str="Voided Item Totalizer : ";break;
case 3:totzType=jpos.FiscalPrinterConst.FPTR_GT_DISCOUNT;
str="Discount Totalizer : ";break;
case 4:totzType=jpos.FiscalPrinterConst.FPTR_GT_GROSS;
str="Gross Totalizer : ";break;
}
strLab[0]=str;
return totzType;
}
private void executeGetData()throws JposException{
String lblStr="Firmware Rel. : ";
valuesGetData[0]=0;strGetData[0]="";
try{
getDataType=jpos.FiscalPrinterConst.FPTR_GD_FIRMWARE;
if(printerIDRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_PRINTER_ID;
lblStr="Printer ID : ";
}else if(currentTotalRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_DAILY_TOTAL;
lblStr="Daily Total : ";
}else if(grandTotalRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_GRAND_TOTAL;
lblStr="Grand Total : ";
}else if(mitVoidRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_MID_VOID;
lblStr="N. of Voided Rec. : ";
}else if(fiscalRecRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_FISCAL_REC;
lblStr="N. of Daily Fiscal Rec. : ";
}else if(receiptNumberRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_RECEIPT_NUMBER;
lblStr="N. of Fiscal Rec. Printed : ";
}else if(refundRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_REFUND;
lblStr="Current Tot. of Refunds : ";
}else if(fiscalRecVoidRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_FISCAL_REC_VOID;
lblStr="N. of Daily Voided Fiscal Rec. : ";
}else if(nonFiscalRecRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_NONFISCAL_REC;
lblStr="N. of Daily Non Fiscal Rec. : ";
}else if(descriptionLengthRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_DESCRIPTION_LENGTH;
lblStr="Description Length : ";
}else if(zReportRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_Z_REPORT;
lblStr="Z Report : ";
}else if(currentRecTotalRB.isSelected()){
getDataType=jpos.FiscalPrinterConst.FPTR_GD_CURRENT_TOTAL;
lblStr="Current Rec. Total : ";
}
fiscalPrinter.getData(getDataType,valuesGetData,strGetData);
itemListModel.addElement(new String(lblStr+strGetData[0]));
}catch(JposException je) {
JOptionPane.showMessageDialog(null, "JPosException calling getData", "Failed", JOptionPane.ERROR_MESSAGE);
}
}
private void clearFields(){
itemQuantity.setText("");
itemPrice.setText("");
itemDescription.setText("");
itemUnitPrice.setText("");
itemVatInfo.setText("");
unitName.setText("");
reportFrom.setText("");
reportTo.setText("");
additionalHeaderTxt.setText("");
additionalTrailerTxt.setText("");
dateTxt.setText("");
headerTxt.setText("");
headerLineNumberTxt.setText("");
nonFiscalTxt.setText("");
itemAmountPercAdjTxt.setText("");
directIoCommand.setText("0");
directIoData.setText("");
directIoObject.setText("");
trailerTxt.setText("");
vatIdTxt.setText("");
vatValueTxt.setText("");
preLineTxt.setText("");
postLineTxt.setText("");
recMessageTxt.setText("");
if(vatIdCombo_2.isEnabled()){
vatValueTxt.setText((String)vatIdCombo_2.getSelectedItem());
}
checkHealthTxt.setText("");
}
class CheckBoxListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
try {
if (source == deviceEnabledCB){
if (e.getStateChange() == ItemEvent.DESELECTED){
fiscalPrinter.setDeviceEnabled(false);
endTrainingButton.setEnabled(false);
beginTrainingButton.setEnabled(false);
}else{
fiscalPrinter.setDeviceEnabled(true);
amountFactorDecimal=1;quantityFactorDecimal=1;
int temp=fiscalPrinter.getAmountDecimalPlace();
if(temp>0){
for(int i=1;i<=temp;i++)amountFactorDecimal=amountFactorDecimal*10;
}
temp=fiscalPrinter.getQuantityDecimalPlaces();
if(temp>0){
for(int i=1;i<=temp;i++)quantityFactorDecimal=quantityFactorDecimal*10;
}
endTrainingButton.setEnabled(true);
beginTrainingButton.setEnabled(true);
paymantFormCombo.removeAllItems();
if(fiscalPrinter.getCapPredefinedPaymentLines()){
String S=fiscalPrinter.getPredefinedPaymentLines(),str;
for(int i=0;i<S.length();i++){
str=S.substring(i, i+1);
if(!str.equals(","))paymantFormCombo.addItem(str);
}
}else{
paymantFormCombo.addItem("CASH");
}
vatIdCombo.removeAllItems();
vatIdCombo_2.removeAllItems();
if(fiscalPrinter.getCapHasVatTable()){
int nv=fiscalPrinter.getNumVatRates();
for(int i=1;i<=nv;i++){
vatIdCombo.addItem(String.valueOf(i));
vatIdCombo_2.addItem(String.valueOf(i));
}
}else{
vatIdCombo.addItem("0");
vatIdCombo_2.addItem("0");
}
}
}else if (source == freezeEventsCB){
if (e.getStateChange() == ItemEvent.DESELECTED){
fiscalPrinter.setFreezeEvents(false);
}else{
fiscalPrinter.setFreezeEvents(true);
}
}else if (source == duplicateReceiptCB){
if (e.getStateChange() == ItemEvent.DESELECTED){
fiscalPrinter.setDuplicateReceipt(false);
}else{
fiscalPrinter.setDuplicateReceipt(true);
}
}else if (source == asyncModeCB){
if (e.getStateChange() == ItemEvent.DESELECTED){
fiscalPrinter.setAsyncMode(false);
}else{
fiscalPrinter.setAsyncMode(true);
}
}else if (source == checkTotalCB){
if (e.getStateChange() == ItemEvent.DESELECTED){
fiscalPrinter.setCheckTotal(false);
}else{
fiscalPrinter.setCheckTotal(true);
}
} else if (source == flagWhenIdleCB){
if (e.getStateChange() == ItemEvent.DESELECTED){
fiscalPrinter.setFlagWhenIdle(false);
}else{
fiscalPrinter.setFlagWhenIdle(true);
}
}
} catch(JposException je) {
JOptionPane.showMessageDialog(null, "Exception in GetPrinter State\nException: " + je.getErrorCode()+"-"+je.getErrorCodeExtended(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("FiscalPrinterPanel: CheckBoxListener: Jpos Exception" + je.getErrorCode()+"-"+je.getErrorCodeExtended());
}
}
}
//Class MethodListner
class MethodListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
mainButtonPanel.action(ae);
String logicalName = mainButtonPanel.getLogicalName();
if(ae.getActionCommand().equals("open")){
try{
if(logicalName.equals("")){
logicalName = defaultLogicalName;
}
// fiscalPrinter.addStatusUpdateListener(this);
fiscalPrinter.open(logicalName);
deviceEnabledCB.setEnabled(false);
freezeEventsCB.setEnabled(true);
duplicateReceiptCB.setEnabled(true);
asyncModeCB.setEnabled(true);
checkTotalCB.setEnabled(true);
flagWhenIdleCB.setEnabled(true);
boolean dupRec=fiscalPrinter.getDuplicateReceipt();
if(dupRec)duplicateReceiptCB.doClick();
int version = fiscalPrinter.getDeviceServiceVersion();
if(version >= 1009000) {
ver_19_complient = true;
ver_18_complient = true;
}
if(version >= 1008000) {
ver_18_complient = true;
}
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Failed to open \""+logicalName+"\"\nException: "+ e.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("claim")){
try{
fiscalPrinter.claim(0);
paymantFormCombo.removeAllItems();
vatIdCombo.removeAllItems();
vatIdCombo_2.removeAllItems();
setEnableButtonTo(true);//button enabled
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Failed to claim \""+logicalName+"\"\nException: "+ e.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("release")){
try{
fiscalPrinter.release();
setEnableButtonTo(false);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Failed to release \""+logicalName+"\"\nException: "+ e.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("close")){
try{
fiscalPrinter.close();
setEnableButtonTo(false);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Failed to close \""+logicalName+"\"\nException: "+ e.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("clearOutPut")){
itemListModel.clear();
} else if(ae.getActionCommand().equals("info")){
try{
String ver = new Integer(fiscalPrinter.getDeviceServiceVersion()).toString();
String msg = "Service Description: " + fiscalPrinter.getDeviceServiceDescription();
msg = msg + "\nService Version: v"+ new Integer(ver.substring(0,1)) + "." + new Integer(ver.substring(1,4)) + "." + new Integer(ver.substring(4,7));
ver = new Integer(fiscalPrinter.getDeviceControlVersion()).toString();
msg += "\n\nControl Description: " + fiscalPrinter.getDeviceControlDescription();
msg += "\nControl Version: v"+ new Integer(ver.substring(0,1)) + "." + new Integer(ver.substring(1,4)) + "." + new Integer(ver.substring(4,7));
msg += "\n\nPhysical Device Name: " + fiscalPrinter.getPhysicalDeviceName();
msg += "\nPhysical Device Description: " + fiscalPrinter.getPhysicalDeviceDescription();
msg += "\n\nProperties:\n------------------------";
if(ver_18_complient)
{
msg += "\nCapStatisticsReporting: " + fiscalPrinter.getCapStatisticsReporting();
msg += "\nCapUpdateStatistics: " + fiscalPrinter.getCapUpdateStatistics();
}
else
{
msg += "\nCapStatisticsReporting: Service Object is not 1.8 complient";
msg += "\nCapUpdateStatistics: Service Object is not 1.8 complient";
}
if(ver_19_complient)
{
msg += "\nCapCompareFirmwareVersion: " + fiscalPrinter.getCapCompareFirmwareVersion();
msg += "\nCapUpdateFirmware: " + fiscalPrinter.getCapUpdateFirmware();
}
else
{
msg += "\nCapCompareFirmwareVersion: Service Object is not 1.9 complient";
msg += "\nCapUpdateFirmware: Service Object is not 1.9 complient";
}
msg += "\nCapPowerReporting: " + (fiscalPrinter.getCapPowerReporting() == JposConst.JPOS_PR_ADVANCED ? "Advanced" : (fiscalPrinter.getCapPowerReporting() == JposConst.JPOS_PR_STANDARD ? "Standard" : "None"));
JOptionPane.showMessageDialog(null, msg, "Info", JOptionPane.INFORMATION_MESSAGE);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Info\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("stats")) {
try{
StatisticsDialog dlg = new StatisticsDialog(fiscalPrinter);
dlg.setVisible(true);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Exception: "+ e.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
}
}else if(ae.getActionCommand().equals("firmware")) {
try{
FirmwareUpdateDlg dlg = new FirmwareUpdateDlg(fiscalPrinter);
dlg.setVisible(true);
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Exception: "+ e.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE);
}
}else if(ae.getActionCommand().equals("paymantFormCombo")){
try{
itemDescription.setText((String)paymantFormCombo.getSelectedItem());
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Exception in Payamant Form\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Exception " + e);
}
}else if(ae.getActionCommand().equals("vatIdCombo")){
try{
itemVatInfo.setText((String)vatIdCombo.getSelectedItem());
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Exception in Vat info\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Exception " + e);
}
} else if(ae.getActionCommand().equals("adjustmentTypeCombo")){
try{
String S=(String)adjustmentTypeCombo.getSelectedItem();
adjustmentType=jpos.FiscalPrinterConst.FPTR_AT_AMOUNT_DISCOUNT;
if(S.equals(adjType[1]))adjustmentType=jpos.FiscalPrinterConst.FPTR_AT_AMOUNT_SURCHARGE;
else if(S.equals(adjType[2]))adjustmentType=jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_DISCOUNT;
else if(S.equals(adjType[3]))adjustmentType=jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_SURCHARGE;
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Exception in adjustmentCombo\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Exception " + e);
}
}else if(ae.getActionCommand().equals("reportTypeCombo")){
try{
String S=(String)reportTypeCombo.getSelectedItem();
reportType=jpos.FiscalPrinterConst.FPTR_RT_ORDINAL;
if(S.equals("DATE"))reportType=jpos.FiscalPrinterConst.FPTR_RT_DATE;
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Exception in Reporttype\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Exception " + e);
}
} else if(ae.getActionCommand().equals("beginFiscalReceipt")){
try{
TOTAL=0;
fiscalPrinter.beginFiscalReceipt(true);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Begin Fiscal Receipt\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecItem")){
try{
String itDesc=itemDescription.getText();
String itPrice=itemPrice.getText();
String itQuantity=itemQuantity.getText();
String itUnitPrice=itemUnitPrice.getText();
String itVatInfo=itemVatInfo.getText();
String itUnitName=unitName.getText();
double dprice=Double.parseDouble(itPrice);
long price=(long)(dprice*amountFactorDecimal);
double dUnitPrice=Double.parseDouble(itUnitPrice);
long unitPrice=(long)(dUnitPrice*amountFactorDecimal);
int vatInfo=0;
if(itVatInfo.length()>0)vatInfo=Integer.parseInt(itVatInfo);
TOTAL=TOTAL+price;
double dquantity=Double.parseDouble(itQuantity);
int quantity=(int)(dquantity*quantityFactorDecimal);
String preL=preLineTxt.getText();if(preL.length()>0)fiscalPrinter.setPreLine(preL);
String postL=postLineTxt.getText();if(postL.length()>0)fiscalPrinter.setPostLine(postL);
clearFields();
fiscalPrinter.printRecItem(itDesc,price,quantity,vatInfo,unitPrice,itUnitName);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in printRecItem \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getData")){
try{
executeGetData();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetData\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("endFiscalReceipt")){
try{
fiscalPrinter.endFiscalReceipt(false);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in End Fiscal Receipt\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecItemAdj")){
try{
String itDesc=itemDescription.getText();
String itPrice=itemAmountPercAdjTxt.getText();
String itVatInfo=itemVatInfo.getText();
double dprice=Double.parseDouble(itPrice);
double kFactor=amountFactorDecimal;
if((adjustmentType==jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_DISCOUNT)||
(adjustmentType==jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_SURCHARGE))kFactor=1;
long price=(long)(dprice*kFactor);
int vatInfo=0;
if(itVatInfo.length()>0)vatInfo=Integer.parseInt(itVatInfo);
String preL=preLineTxt.getText();if(preL.length()>0)fiscalPrinter.setPreLine(preL);
fiscalPrinter.printRecItemAdjustment(adjustmentType,itDesc,price,vatInfo);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Begin Fiscal Receipt\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecRefund")){
try{
String itDesc=itemDescription.getText();
String itPrice=itemPrice.getText();
String itVatInfo=itemVatInfo.getText();
double dprice=Double.parseDouble(itPrice);
long price=(long)(dprice*amountFactorDecimal);
int vatInfo=0;
if(itVatInfo.length()>0)vatInfo=Integer.parseInt(itVatInfo);
String preL=preLineTxt.getText();if(preL.length()>0)fiscalPrinter.setPreLine(preL);
fiscalPrinter.printRecRefund(itDesc,price,vatInfo);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRecRefund\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecSubTotal")){
try{
String itPrice=itemPrice.getText();
double dprice=Double.parseDouble(itPrice);
long price=(long)(dprice*amountFactorDecimal);
String postL=postLineTxt.getText();if(postL.length()>0)fiscalPrinter.setPostLine(postL);
fiscalPrinter.printRecSubtotal(price);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Begin Fiscal Receipt\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecTotal")){
try{
String itDesc=itemDescription.getText();
String itPrice=itemPrice.getText();
double dprice=Double.parseDouble(itPrice);
long price=(long)(dprice*amountFactorDecimal);
long __Total=TOTAL;
if(price<TOTAL)TOTAL=TOTAL-price;
String postL=postLineTxt.getText();if(postL.length()>0)fiscalPrinter.setPostLine(postL);
String itAmountPerc=itemAmountPercAdjTxt.getText();
if(itAmountPerc.length()>0){
double ddprice=Double.parseDouble(itAmountPerc);
long erratedTotale=(long)(ddprice*amountFactorDecimal);
__Total=erratedTotale;
}
fiscalPrinter.printRecTotal(__Total,price,itDesc);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Print Receipt Total\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecVoid")){
try{
String itDesc=itemDescription.getText();
fiscalPrinter.printRecVoid(itDesc);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRecVoid \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecRefundVoid")){
try{
String itDesc=itemDescription.getText();
String itPrice=itemPrice.getText();
String itVatInfo=itemVatInfo.getText();
double dprice=Double.parseDouble(itPrice);
long price=(long)(dprice*amountFactorDecimal);
int vatInfo=0;
if(itVatInfo.length()>0)vatInfo=Integer.parseInt(itVatInfo);
fiscalPrinter.printRecRefundVoid(itDesc,price,vatInfo);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRefundVoid\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printRecMessage")){
try{
String itMsg=recMessageTxt.getText();
fiscalPrinter.printRecMessage(itMsg);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRecMessage \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("recSubTotalDiscount")){
try{
String itAmountPerc=itemAmountPercAdjTxt.getText();
double dprice=Double.parseDouble(itAmountPerc);
double kFactor=amountFactorDecimal;
if((adjustmentType==jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_DISCOUNT)||
(adjustmentType==jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_SURCHARGE))kFactor=1;
long price=(long)(dprice*kFactor);
String preL=preLineTxt.getText();if(preL.length()>0)fiscalPrinter.setPreLine(preL);
String itDesc=itemDescription.getText();
fiscalPrinter.printRecSubtotalAdjustment(adjustmentType,itDesc,price);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRecSubTotalDiscount \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("recSubTotalDiscountVoid")){
try{
String itAmountPerc=itemAmountPercAdjTxt.getText();
double dprice=Double.parseDouble(itAmountPerc);
double kFactor=amountFactorDecimal;
if((adjustmentType==jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_DISCOUNT)||
(adjustmentType==jpos.FiscalPrinterConst.FPTR_AT_PERCENTAGE_SURCHARGE))kFactor=1;
long price=(long)(dprice*kFactor);
String preL=preLineTxt.getText();if(preL.length()>0)fiscalPrinter.setPreLine(preL);
fiscalPrinter.printRecSubtotalAdjustVoid(adjustmentType,price);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRecSubTotalDiscount \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("printRecVoidItem")){
try{
String itDesc=itemDescription.getText();
String itPrice=itemPrice.getText();
String itQuantity=itemQuantity.getText();
String itVatInfo=itemVatInfo.getText();
String amountAdjTxt=itemAmountPercAdjTxt.getText();
double dprice=Double.parseDouble(itPrice);
long price=(long)(dprice*amountFactorDecimal);
double damount=Double.parseDouble(amountAdjTxt);
long amount=(long)(damount*amountFactorDecimal);
double dquantity=Double.parseDouble(itQuantity);
int quantity=(int)(dquantity*quantityFactorDecimal);
int vatInfo=0;
if(itVatInfo.length()>0)vatInfo=Integer.parseInt(itVatInfo);
fiscalPrinter.printRecVoidItem(itDesc,price,quantity,adjustmentType,amount,vatInfo);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintRecVoiItem\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printReport")){
try{
String repFrom=reportFrom.getText();
String repTo=reportTo.getText();
fiscalPrinter.printReport(reportType, repFrom,repTo);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Print Report\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printXReport")){
try{
fiscalPrinter.printXReport();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintXReport\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printZReport")){
try{
fiscalPrinter.printZReport();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PrintZReport\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printDuplicateRec")){
try{
fiscalPrinter.printDuplicateReceipt();
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Print Duplicate Receipt\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("setVatTable")){
try{
fiscalPrinter.setVatTable();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in SetVatTable\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("setPrinterProp")){
try{
String S= additionalHeaderTxt.getText();
if(S.length()>0)fiscalPrinter.setAdditionalHeader(S);
S= additionalTrailerTxt.getText();
if(S.length()>0)fiscalPrinter.setAdditionalTrailer(S);
S= dateTxt.getText();
if(S.length()>0)fiscalPrinter.setDate(S);
String SST=trailerTxt.getText();
String SS= headerTxt.getText();
if(SS.length()>0){
String s1=headerLineNumberTxt.getText();
int lineNumber=-1;
if(s1.length()>0)lineNumber=Integer.parseInt(s1);
if(lineNumber>0)fiscalPrinter.setHeaderLine(lineNumber,SS,doubleWidthCB.isSelected());
else JOptionPane.showMessageDialog(null, "Illegal Line Number","Exception", JOptionPane.ERROR_MESSAGE);
}
if(SST.length()>0){
String s1=headerLineNumberTxt.getText();
int lineNumber=-1;
if(s1.length()>0)lineNumber=Integer.parseInt(s1);
if(lineNumber>0)fiscalPrinter.setTrailerLine(lineNumber,SST,doubleWidthCB.isSelected());
else JOptionPane.showMessageDialog(null, "Illegal Line Number","Exception", JOptionPane.ERROR_MESSAGE);
}
String SvatId=vatIdTxt.getText();
String SvatValue=vatValueTxt.getText();
if(SvatId.length()>0){
int vatId=Integer.parseInt(SvatId);
fiscalPrinter.setVatValue( vatId,SvatValue);
}
String sckh=checkHealthTxt.getText();
if(sckh.length()>0){
int chk=Integer.parseInt(sckh);
fiscalPrinter.checkHealth(chk);
}
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Set Property\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("beginNonFiscal")){
try{
fiscalPrinter.beginNonFiscal();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Begin Non Fiscal\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("endNonFiscal")){
try{
fiscalPrinter.endNonFiscal();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in End Non Fiscal\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printNormal")){
try{
int station=jpos.FiscalPrinterConst.FPTR_S_RECEIPT;
String txt=nonFiscalTxt.getText();
fiscalPrinter.printNormal(station,txt);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Print Normalt\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("printPeriodicReport")){
try{
String repFrom=reportFrom.getText();
String repTo=reportTo.getText();
fiscalPrinter.printPeriodicTotalsReport(repFrom,repTo);
clearFields();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in PeriodicReport\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getDate")){
try{
String[] txt={""};
fiscalPrinter.getDate(txt);
itemListModel.addElement(new String("DATE : "+txt[0]));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetDate\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getErrorLevel")){
try{
int errState=fiscalPrinter.getErrorState();
itemListModel.addElement(new String("ERROR STATE : "+String.valueOf(errState)));
int errLev=fiscalPrinter.getErrorLevel();
String str=decodeErrorLevel(errLev);
itemListModel.addElement(new String("ERROR LEVEL : "+str));
int errId=fiscalPrinter.getErrorOutID();
itemListModel.addElement(new String("ERROR OUT ID : "+String.valueOf(errId)));
int errStat=fiscalPrinter.getErrorStation();
str=decodeErrorStation(errStat);
itemListModel.addElement(new String("ERROR STATION : "+str));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetPrinter Error Info\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getOutPutId")){
try{
int outId=fiscalPrinter.getOutputID();
itemListModel.addElement(new String("OUTPUT ID : "+String.valueOf(outId)));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Get OutputID Level\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("getTrainingState")){
try{
boolean traiMode=fiscalPrinter.getTrainingModeActive();
String str="FALSE";
if(traiMode)str="TRUE";
itemListModel.addElement(new String("TRAINING MODE ACTIVE : "+str));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetTraining State\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("printerStatus")){
try{
int tempstate=fiscalPrinter.getPrinterState();
String str=decodeState(tempstate);
itemListModel.addElement(new String("STATE : "+str));
tempstate=fiscalPrinter.getState();
str=decodeDeviceState(tempstate);
itemListModel.addElement(new String("DEVICE STATE : "+str));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetPrinter State\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("dayOpened")){
try{
String str;
boolean dayOpened=fiscalPrinter.getDayOpened();
if(dayOpened)str="TRUE";else str="FALSE";
itemListModel.addElement(new String("DAY OPENED : "+str));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetPrinter State\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("remainingFiscalMemory")){
try{
int remFiscMem=fiscalPrinter.getRemainingFiscalMemory();
itemListModel.addElement(new String("Rem. Fisc. Memory : "+String.valueOf(remFiscMem)));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in GetPrinter State\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("clearOut")){
try{
fiscalPrinter.clearOutput();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Clear Output\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("clearError")){
try{
fiscalPrinter.clearError();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Clear Error\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("showProperty")){
try{
String str;
boolean jrnEmpty=fiscalPrinter.getJrnEmpty();
if(jrnEmpty)str="TRUE";else str="FALSE";
itemListModel.addElement(new String("JrnEMPTY : "+str));
boolean jrnNearEnd=fiscalPrinter.getJrnNearEnd();
if(jrnNearEnd)str="TRUE";else str="FALSE";
itemListModel.addElement(new String("JrnNEAREND : "+str));
boolean recEmpty=fiscalPrinter.getRecEmpty();
if(recEmpty)str="TRUE";else str="FALSE";
itemListModel.addElement(new String("recEMPTY : "+str));
boolean recNearEnd=fiscalPrinter.getRecNearEnd();
if(recNearEnd)str="TRUE";else str="FALSE";
itemListModel.addElement(new String("recNEAREND : "+str));
if(fiscalPrinter.getCapHasVatTable()){
int nv=fiscalPrinter.getNumVatRates();
int[] v={0};
for(int i=1;i<=nv;i++){
fiscalPrinter.getVatEntry(i,0, v);
itemListModel.addElement(new String("Vat ID: "+String.valueOf(i)+" - Value : "+String.valueOf(v[0])));
}
}
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in ShowProperty\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getTotalizer")){
try{
String labStr;
String[] str={""},valStr={""};
if(grandTotalizerRB.isSelected()){
fiscalPrinter.setTotalizerType(jpos.FiscalPrinterConst.FPTR_TT_GRAND);
labStr="GRAND TOTAL - ";
}else{
fiscalPrinter.setTotalizerType(jpos.FiscalPrinterConst.FPTR_TT_DAY);
labStr="DAY TOTAL - ";
}
int totalizerType=getTotalizerType(str);
String tempVatid =(String)vatIdCombo_2.getSelectedItem();
int vatid=Integer.parseInt(tempVatid);
fiscalPrinter.getTotalizer(vatid, totalizerType,valStr);
itemListModel.addElement(new String(labStr+str[0]+valStr[0]));
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Get Totalizer\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
} else if(ae.getActionCommand().equals("beginTraining")){
try{
fiscalPrinter.beginTraining();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in BeginTraning\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("endTraining")){
try{
fiscalPrinter.endTraining();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Endtraning\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getPropList")){
try{
propListModel.clear();
int cc=fiscalPrinter.getCountryCode();
String s;
propListModel.addElement(decodeCountryCode(cc));
cc=fiscalPrinter.getDescriptionLength();
propListModel.addElement("Description Length : "+String.valueOf(cc));
cc=fiscalPrinter.getMessageLength();
propListModel.addElement("Message Length : "+String.valueOf(cc));
cc=fiscalPrinter.getNumHeaderLines();
propListModel.addElement("Num. Header Lines : "+String.valueOf(cc));
if(fiscalPrinter.getCapPredefinedPaymentLines()){
s=fiscalPrinter.getPredefinedPaymentLines();
propListModel.addElement("Pred. Payment Lines : "+s);
}else{
propListModel.addElement("Pred. Payment Lines : NOT Supported");
}
cc=fiscalPrinter.getQuantityDecimalPlaces();
propListModel.addElement("Quantity Dec. Places : "+String.valueOf(cc));
cc=fiscalPrinter.getQuantityLength();
propListModel.addElement("Quantity Length : "+String.valueOf(cc));
s=fiscalPrinter.getReservedWord();
propListModel.addElement("Reserved Word : "+s);
propListModel.addElement("********** Capability **********");
boolean b=fiscalPrinter.getCapAdditionalLines();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapAdditionalLines : "+s));
b=fiscalPrinter.getCapAmountAdjustment();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapAmountAdjustment : "+s));
b=fiscalPrinter.getCapAmountNotPaid();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapAmountNotPaid : "+s));
b=fiscalPrinter.getCapChangeDue();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapChangeDue : "+s));
b=fiscalPrinter.getCapCheckTotal();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapCheckTotal : "+s));
b=fiscalPrinter.getCapJrnEmptySensor();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapJrnEmptySensor : "+s));
b=fiscalPrinter.getCapJrnNearEndSensor();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapJrnNearEndSensor : "+s));
b=fiscalPrinter.getCapPredefinedPaymentLines();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapPredefinedPaymentLines : "+s));
b=fiscalPrinter.getCapRecEmptySensor();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapRecEmptySensor : "+s));
b=fiscalPrinter.getCapRecPresent();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapRecPresent : "+s));
b=fiscalPrinter.getCapReservedWord();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapReservedWord : "+s));
b=fiscalPrinter.getCapRemainingFiscalMemory();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapRemainingFiscalMemory : "+s));
b=fiscalPrinter.getCapSetHeader();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSetHeader : "+s));
b=fiscalPrinter.getCapSetPOSID();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSetPOSID : "+s));
b=fiscalPrinter.getCapSetTrailer();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSetTrailer : "+s));
b=fiscalPrinter.getCapSetVatTable();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSetVatTable : "+s));
b=fiscalPrinter.getCapSubAmountAdjustment();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSubAmountAdjustment : "+s));
b=fiscalPrinter.getCapSubPercentAdjustment();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSubPercentAdjustment : "+s));
b=fiscalPrinter.getCapSubtotal();if(b)s="TRUE";else s="FALSE";
propListModel.addElement(new String("CapSubtotal : "+s));
propListModel.addElement("--------------------------------");
if(fiscalPrinter.getDeviceEnabled()){
cc=fiscalPrinter.getMessageType();
propListModel.addElement("Message Type :"+decodeTypeMessage(cc));
cc=fiscalPrinter.getAmountDecimalPlace();
propListModel.addElement("Amount Dec. Places : "+String.valueOf(cc));
}else{
propListModel.addElement("For others properties enable device");
}
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in Get Property \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("directIoButton")){
try{
String s1=directIoCommand.getText();
String s2=directIoData.getText();
String s3=directIoObject.getText();
StringBuffer sb=new StringBuffer(s3);
int dC=0;
int[] dD={0};
try{
dC=Integer.parseInt(s1);
dD[0]=Integer.parseInt(s2);
clearFields();
} catch(Exception e){
JOptionPane.showMessageDialog(null, "Dati Errati \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
}
fiscalPrinter.directIO(dC, dD, sb);
directIoData.setText(String.valueOf(dD[0]));
directIoObject.setText(sb.toString());
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in DirectIO \nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getAdditionalHeader")){
try{
String s=fiscalPrinter.getAdditionalHeader();
propListModel.addElement("Additional Header : "+s);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in getAdditionalHeader\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("getAdditionalTrailer")){
try{
String s=fiscalPrinter.getAdditionalTrailer();
propListModel.addElement("Additional Trailer : "+s);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in getAdditionalTrailer\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("resetPrinter")){
try{
fiscalPrinter.resetPrinter();
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in resetPrinter\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}else if(ae.getActionCommand().equals("clearFieldsButton")){
clearFields();
}else if(ae.getActionCommand().equals("getCheckHealth")){
try{
String s=fiscalPrinter.getCheckHealthText();
propListModel.addElement("CheckHealthText : "+s);
}catch(JposException e){
JOptionPane.showMessageDialog(null, "Exception in getCheckHealth\nException: "+ e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
System.err.println("Jpos exception " + e);
}
}
try {
if(deviceEnabledCB.isSelected()){
deviceEnabledCB.setSelected(fiscalPrinter.getDeviceEnabled());
freezeEventsCB.setSelected(fiscalPrinter.getFreezeEvents());
}
} catch(JposException je) {
System.err.println("FiscalPrinterPanel: MethodListener: JposException");
}
}
}
// DirectIO Panel
class DirectIOPanel extends Component{
private static final long serialVersionUID = 9108485289446253369L;
public Component make(){
JPanel labelPanel = new JPanel();
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.Y_AXIS));
label = new JLabel("Number");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(80,17));
label.setPreferredSize(new Dimension(80,17));
labelPanel.add(label);
label = new JLabel("Data");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(80,17));
label.setPreferredSize(new Dimension(80,17));
labelPanel.add(label);
label = new JLabel("String");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(80,17));
label.setPreferredSize(new Dimension(80,17));
labelPanel.add(label);
label = new JLabel(" ");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(80,17));
label.setPreferredSize(new Dimension(80,17));
labelPanel.add(label);
JPanel dataPanel = new JPanel();
dataPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
dataPanel.setLayout(new BoxLayout(dataPanel, BoxLayout.Y_AXIS));
directIoCommand = new JTextField();
directIoCommand.setMaximumSize(new Dimension(80,18));
directIoCommand.setPreferredSize(new Dimension(80,18));
directIoCommand.setMinimumSize(new Dimension(80,18));
directIoCommand.setText("0");
directIoCommand.setAlignmentX(Component.LEFT_ALIGNMENT);
dataPanel.add(directIoCommand);
directIoData = new JTextField();
directIoData.setMaximumSize(new Dimension(160,18));
directIoData.setPreferredSize(new Dimension(160,18));
directIoData.setMinimumSize(new Dimension(160,18));
directIoData.setAlignmentX(Component.LEFT_ALIGNMENT);
dataPanel.add(directIoData);
directIoObject = new JTextField();
directIoObject.setMaximumSize(new Dimension(500,18));
directIoObject.setPreferredSize(new Dimension(500,18));
directIoObject.setMinimumSize(new Dimension(450,18));
directIoObject.setAlignmentX(Component.LEFT_ALIGNMENT);
dataPanel.add(directIoObject);
directIoButton = new JButton("Direct IO");
directIoButton.setMaximumSize(new Dimension(160,17));
directIoButton.setPreferredSize(new Dimension(160,17));
directIoButton.setActionCommand("directIoButton");
directIoButton.addActionListener(methodListener);
directIoButton.setAlignmentX(Component.LEFT_ALIGNMENT);
directIoButton.setEnabled(false);
dataPanel.add(directIoButton);
clearFieldsButton = new JButton("Clear Fields");
clearFieldsButton.setMaximumSize(new Dimension(160,17));
clearFieldsButton.setPreferredSize(new Dimension(160,17));
clearFieldsButton.setActionCommand("clearFieldsButton");
clearFieldsButton.addActionListener(methodListener);
clearFieldsButton.setAlignmentX(Component.LEFT_ALIGNMENT);
clearFieldsButton.setEnabled(true);
dataPanel.add(clearFieldsButton);
JPanel directIOPanel = new JPanel();
directIOPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
directIOPanel.setLayout(new BoxLayout(directIOPanel,BoxLayout.X_AXIS));
directIOPanel.add(labelPanel);
directIOPanel.add(dataPanel);
return directIOPanel;
}
}
//Non fiscalPrinting Panel
class NonFiscalPanel extends Component{
private static final long serialVersionUID = -8116838958814524668L;
public Component make() {
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
beginNonFiscalButton = new JButton("Begin Non Fiscal");
beginNonFiscalButton.setMaximumSize(new Dimension(160,17));
beginNonFiscalButton.setPreferredSize(new Dimension(160,17));
beginNonFiscalButton.setActionCommand("beginNonFiscal");
beginNonFiscalButton.addActionListener(methodListener);
beginNonFiscalButton.setAlignmentX(Component.TOP_ALIGNMENT);
beginNonFiscalButton.setEnabled(false);
buttonPanel.add(beginNonFiscalButton);
printNormalButton = new JButton("Print Normal");
printNormalButton.setMaximumSize(new Dimension(160,17));
printNormalButton.setPreferredSize(new Dimension(160,17));
printNormalButton.setActionCommand("printNormal");
printNormalButton.addActionListener(methodListener);
printNormalButton.setAlignmentX(Component.TOP_ALIGNMENT);
printNormalButton.setEnabled(false);
buttonPanel.add(printNormalButton);
endNonFiscalButton = new JButton("End Non Fiscal");
endNonFiscalButton.setMaximumSize(new Dimension(160,17));
endNonFiscalButton.setPreferredSize(new Dimension(160,17));
endNonFiscalButton.setActionCommand("endNonFiscal");
endNonFiscalButton.addActionListener(methodListener);
endNonFiscalButton.setAlignmentX(Component.TOP_ALIGNMENT);
endNonFiscalButton.setEnabled(false);
buttonPanel.add(endNonFiscalButton);
//Label Panel
JPanel itemLabelPanel = new JPanel();
itemLabelPanel.setLayout( new BoxLayout(itemLabelPanel, BoxLayout.Y_AXIS));
itemLabelPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
itemLabelPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Text");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
//Field Panel
JPanel itemFieldPanel = new JPanel();
itemFieldPanel.setLayout( new BoxLayout(itemFieldPanel, BoxLayout.Y_AXIS));
itemFieldPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
itemFieldPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
nonFiscalTxt = new JTextArea(50,40);
nonFiscalTxt.setMaximumSize(new Dimension(300,200));
nonFiscalTxt.setPreferredSize(new Dimension(300,200));
nonFiscalTxt.setMinimumSize(new Dimension(300,200));
itemFieldPanel.add(new JScrollPane(nonFiscalTxt),BorderLayout.CENTER);
JPanel nonFiscalControlPanel = new JPanel();
nonFiscalControlPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
nonFiscalControlPanel.setLayout(new BoxLayout(nonFiscalControlPanel,BoxLayout.X_AXIS));
nonFiscalControlPanel.add(buttonPanel);
nonFiscalControlPanel.add(itemLabelPanel);
nonFiscalControlPanel.add(itemFieldPanel);
return nonFiscalControlPanel;
}
}
//Fiscal Printer Setting
class FiscalPrinterSettingPanel extends Component{
private static final long serialVersionUID = 699060709578537513L;
public Component make() {
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
label = new JLabel("Additional Trailer");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Additional Header");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Date");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Header");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Trailer");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Line Number");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Vat ID");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Vat Value (% * 100)");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
label = new JLabel("Check Health");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
buttonPanel.add(label);
setPrinterProp = new JButton("Set Printer");
setPrinterProp.setMaximumSize(new Dimension(160,17));
setPrinterProp.setPreferredSize(new Dimension(160,17));
setPrinterProp.setActionCommand("setPrinterProp");
setPrinterProp.addActionListener(methodListener);
setPrinterProp.setAlignmentX(Component.TOP_ALIGNMENT);
setPrinterProp.setEnabled(false);
buttonPanel.add(setPrinterProp);
setVatTableButton = new JButton("Set VatTable");
setVatTableButton.setMaximumSize(new Dimension(160,17));
setVatTableButton.setPreferredSize(new Dimension(160,17));
setVatTableButton.setActionCommand("setVatTable");
setVatTableButton.addActionListener(methodListener);
setVatTableButton.setAlignmentX(Component.TOP_ALIGNMENT);
setVatTableButton.setEnabled(false);
buttonPanel.add(setVatTableButton);
//Fields Panel
JPanel itemFieldPanel = new JPanel();
itemFieldPanel.setLayout( new BoxLayout(itemFieldPanel, BoxLayout.Y_AXIS));
itemFieldPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
itemFieldPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
additionalTrailerTxt = new JTextField();
additionalTrailerTxt.setMaximumSize(new Dimension(160,18));
additionalTrailerTxt.setPreferredSize(new Dimension(160,18));
additionalTrailerTxt.setMinimumSize(new Dimension(160,18));
itemFieldPanel.add(additionalTrailerTxt);
additionalHeaderTxt = new JTextField();
additionalHeaderTxt.setMaximumSize(new Dimension(160,18));
additionalHeaderTxt.setPreferredSize(new Dimension(160,18));
additionalHeaderTxt.setMinimumSize(new Dimension(160,18));
itemFieldPanel.add(additionalHeaderTxt);
dateTxt = new JTextField();
dateTxt.setMaximumSize(new Dimension(160,18));
dateTxt.setPreferredSize(new Dimension(160,18));
dateTxt.setMinimumSize(new Dimension(160,18));
itemFieldPanel.add(dateTxt);
headerTxt = new JTextField();
headerTxt.setMaximumSize(new Dimension(160,18));
headerTxt.setPreferredSize(new Dimension(160,18));
headerTxt.setMinimumSize(new Dimension(160,18));
itemFieldPanel.add(headerTxt);
trailerTxt = new JTextField();
trailerTxt.setMaximumSize(new Dimension(160,18));
trailerTxt.setPreferredSize(new Dimension(160,18));
trailerTxt.setMinimumSize(new Dimension(160,18));
itemFieldPanel.add(trailerTxt);
headerLineNumberTxt = new JTextField();
headerLineNumberTxt.setMaximumSize(new Dimension(50,18));
headerLineNumberTxt.setPreferredSize(new Dimension(50,18));
headerLineNumberTxt.setMinimumSize(new Dimension(50,18));
itemFieldPanel.add(headerLineNumberTxt);
vatIdTxt = new JTextField();
vatIdTxt.setMaximumSize(new Dimension(50,18));
vatIdTxt.setPreferredSize(new Dimension(50,18));
vatIdTxt.setMinimumSize(new Dimension(50,18));
itemFieldPanel.add(vatIdTxt);
vatValueTxt = new JTextField();
vatValueTxt.setMaximumSize(new Dimension(50,18));
vatValueTxt.setPreferredSize(new Dimension(50,18));
vatValueTxt.setMinimumSize(new Dimension(50,18));
itemFieldPanel.add(vatValueTxt);
checkHealthTxt = new JTextField();
checkHealthTxt.setMaximumSize(new Dimension(50,18));
checkHealthTxt.setPreferredSize(new Dimension(50,18));
checkHealthTxt.setMinimumSize(new Dimension(50,18));
itemFieldPanel.add(checkHealthTxt);
label = new JLabel("");
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setMaximumSize(new Dimension(160,17));
label.setPreferredSize(new Dimension(160,17));
itemFieldPanel.add(label);
doubleWidthCB= new JCheckBox("Set Double Width");
doubleWidthCB.setMaximumSize(new Dimension(160,14));
doubleWidthCB.setPreferredSize(new Dimension(160,14));
doubleWidthCB.setMinimumSize(new Dimension(160,14));
doubleWidthCB.setAlignmentX(Component.CENTER_ALIGNMENT);
itemFieldPanel.add(doubleWidthCB);
JPanel propListPanel = new JPanel();
propListPanel.setLayout(new BoxLayout(propListPanel,BoxLayout.Y_AXIS));
propListPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Property : ");
label.setMaximumSize(new Dimension(160,17));
label.setAlignmentX(Component.CENTER_ALIGNMENT);
propListModel = new DefaultListModel();
propList = new JList(propListModel);
propList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
propList.setLayoutOrientation(JList.VERTICAL);
propList.setVisibleRowCount(7);
JScrollPane windowScrollPane = new JScrollPane(propList);
windowScrollPane.setMinimumSize(new Dimension( 200,250));
windowScrollPane.setPreferredSize(new Dimension(350,300));
windowScrollPane.setMaximumSize(new Dimension( 350,300));
propListPanel.add(label);
propListPanel.add(windowScrollPane);
getPropListButton = new JButton("Get Property");
getPropListButton.setMaximumSize(new Dimension(200,17));
getPropListButton.setPreferredSize(new Dimension(200,17));
getPropListButton.setActionCommand("getPropList");
getPropListButton.addActionListener(methodListener);
getPropListButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getPropListButton.setEnabled(false);
propListPanel.add(getPropListButton);
getAdditionalHeaderButton = new JButton("Get Additional Header");
getAdditionalHeaderButton.setMaximumSize(new Dimension(200,17));
getAdditionalHeaderButton.setPreferredSize(new Dimension(200,17));
getAdditionalHeaderButton.setActionCommand("getAdditionalHeader");
getAdditionalHeaderButton.addActionListener(methodListener);
getAdditionalHeaderButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getAdditionalHeaderButton.setEnabled(false);
propListPanel.add(getAdditionalHeaderButton);
getAdditionalTrailerButton = new JButton("Get Additional Trailer");
getAdditionalTrailerButton.setMaximumSize(new Dimension(200,17));
getAdditionalTrailerButton.setPreferredSize(new Dimension(200,17));
getAdditionalTrailerButton.setActionCommand("getAdditionalTrailer");
getAdditionalTrailerButton.addActionListener(methodListener);
getAdditionalTrailerButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getAdditionalTrailerButton.setEnabled(false);
propListPanel.add(getAdditionalTrailerButton);
getCheckHealthButton = new JButton("Get CheckHealth");
getCheckHealthButton.setMaximumSize(new Dimension(200,17));
getCheckHealthButton.setPreferredSize(new Dimension(200,17));
getCheckHealthButton.setActionCommand("getCheckHealth");
getCheckHealthButton.addActionListener(methodListener);
getCheckHealthButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getCheckHealthButton.setEnabled(false);
propListPanel.add(getCheckHealthButton);
JPanel fiscalPtrSettingControlPanel = new JPanel();
fiscalPtrSettingControlPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
fiscalPtrSettingControlPanel.setLayout(new BoxLayout(fiscalPtrSettingControlPanel,BoxLayout.X_AXIS));
fiscalPtrSettingControlPanel.add(buttonPanel);
fiscalPtrSettingControlPanel.add(itemFieldPanel);
fiscalPtrSettingControlPanel.add(propListPanel);
return fiscalPtrSettingControlPanel;
}
}
//Fiscal Receipt Panel
class FiscalReceiptPanel extends Component{
private static final long serialVersionUID = 1191991536139213593L;
public Component make() {
//Buttons Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
beginFiscalReceiptButton = new JButton("Begin Fiscal Receipt");
beginFiscalReceiptButton.setMaximumSize(new Dimension(160,17));
beginFiscalReceiptButton.setPreferredSize(new Dimension(160,17));
beginFiscalReceiptButton.setActionCommand("beginFiscalReceipt");
beginFiscalReceiptButton.addActionListener(methodListener);
beginFiscalReceiptButton.setAlignmentX(Component.TOP_ALIGNMENT);
beginFiscalReceiptButton.setEnabled(false);
buttonPanel.add(beginFiscalReceiptButton);
printRecItemButton = new JButton("Print Receipt Item");
printRecItemButton.setMaximumSize(new Dimension(160,17));
printRecItemButton.setPreferredSize(new Dimension(160,17));
printRecItemButton.setActionCommand("printRecItem");
printRecItemButton.addActionListener(methodListener);
printRecItemButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecItemButton.setEnabled(false);
buttonPanel.add(printRecItemButton);
printRecItemAdjButton = new JButton("Print Rec Adj Item");
printRecItemAdjButton.setMaximumSize(new Dimension(160,17));
printRecItemAdjButton.setPreferredSize(new Dimension(160,17));
printRecItemAdjButton.setActionCommand("printRecItemAdj");
printRecItemAdjButton.addActionListener(methodListener);
printRecItemAdjButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecItemAdjButton.setEnabled(false);
buttonPanel.add(printRecItemAdjButton);
printRecRefundButton = new JButton("Print Receipt Refund");
printRecRefundButton.setMaximumSize(new Dimension(160,17));
printRecRefundButton.setPreferredSize(new Dimension(160,17));
printRecRefundButton.setActionCommand("printRecRefund");
printRecRefundButton.addActionListener(methodListener);
printRecRefundButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecRefundButton.setEnabled(false);
buttonPanel.add(printRecRefundButton);
printRecRefundVoidButton = new JButton("Print RecRef. Void");
printRecRefundVoidButton.setMaximumSize(new Dimension(160,17));
printRecRefundVoidButton.setPreferredSize(new Dimension(160,17));
printRecRefundVoidButton.setActionCommand("printRecRefundVoid");
printRecRefundVoidButton.addActionListener(methodListener);
printRecRefundVoidButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecRefundVoidButton.setEnabled(false);
buttonPanel.add(printRecRefundVoidButton);
printRecTotalButton = new JButton("Print Receipt Total");
printRecTotalButton.setMaximumSize(new Dimension(160,17));
printRecTotalButton.setPreferredSize(new Dimension(160,17));
printRecTotalButton.setActionCommand("printRecTotal");
printRecTotalButton.addActionListener(methodListener);
printRecTotalButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecTotalButton.setEnabled(false);
buttonPanel.add(printRecTotalButton);
printRecSubTotalButton = new JButton("Print Receipt SubT.");
printRecSubTotalButton.setMaximumSize(new Dimension(160,17));
printRecSubTotalButton.setPreferredSize(new Dimension(160,17));
printRecSubTotalButton.setActionCommand("printRecSubTotal");
printRecSubTotalButton.addActionListener(methodListener);
printRecSubTotalButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecSubTotalButton.setEnabled(false);
buttonPanel.add(printRecSubTotalButton);
printRecVoidButton = new JButton("Print Receipt Void");
printRecVoidButton.setMaximumSize(new Dimension(160,17));
printRecVoidButton.setPreferredSize(new Dimension(160,17));
printRecVoidButton.setActionCommand("printRecVoid");
printRecVoidButton.addActionListener(methodListener);
printRecVoidButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecVoidButton.setEnabled(false);
buttonPanel.add(printRecVoidButton);
printRecVoidItemButton = new JButton("Print Rec. Void Item");
printRecVoidItemButton.setMaximumSize(new Dimension(160,17));
printRecVoidItemButton.setPreferredSize(new Dimension(160,17));
printRecVoidItemButton.setActionCommand("printRecVoidItem");
printRecVoidItemButton.addActionListener(methodListener);
printRecVoidItemButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecVoidItemButton.setEnabled(false);
buttonPanel.add(printRecVoidItemButton);
recSubTotalDiscountButton = new JButton("Rec. SubTotal Adj.");
recSubTotalDiscountButton.setMaximumSize(new Dimension(160,17));
recSubTotalDiscountButton.setPreferredSize(new Dimension(160,17));
recSubTotalDiscountButton.setActionCommand("recSubTotalDiscount");
recSubTotalDiscountButton.addActionListener(methodListener);
recSubTotalDiscountButton.setAlignmentX(Component.TOP_ALIGNMENT);
recSubTotalDiscountButton.setEnabled(false);
buttonPanel.add(recSubTotalDiscountButton);
recSubTotalDiscountVoidButton = new JButton("Rec. SubT. Adj. Void");
recSubTotalDiscountVoidButton.setMaximumSize(new Dimension(160,17));
recSubTotalDiscountVoidButton.setPreferredSize(new Dimension(160,17));
recSubTotalDiscountVoidButton.setActionCommand("recSubTotalDiscountVoid");
recSubTotalDiscountVoidButton.addActionListener(methodListener);
recSubTotalDiscountVoidButton.setAlignmentX(Component.TOP_ALIGNMENT);
recSubTotalDiscountVoidButton.setEnabled(false);
buttonPanel.add(recSubTotalDiscountVoidButton);
printRecMessageButton = new JButton("Print Rec. Message");
printRecMessageButton.setMaximumSize(new Dimension(160,17));
printRecMessageButton.setPreferredSize(new Dimension(160,17));
printRecMessageButton.setActionCommand("printRecMessage");
printRecMessageButton.addActionListener(methodListener);
printRecMessageButton.setAlignmentX(Component.TOP_ALIGNMENT);
printRecMessageButton.setEnabled(false);
buttonPanel.add(printRecMessageButton);
printDuplicateRecButton = new JButton("Duplicate Receipt");
printDuplicateRecButton.setMaximumSize(new Dimension(160,17));
printDuplicateRecButton.setPreferredSize(new Dimension(160,17));
printDuplicateRecButton.setActionCommand("printDuplicateRec");
printDuplicateRecButton.addActionListener(methodListener);
printDuplicateRecButton.setAlignmentX(Component.TOP_ALIGNMENT);
printDuplicateRecButton.setEnabled(false);
buttonPanel.add(printDuplicateRecButton);
endFiscalReceiptButton = new JButton("End Fiscal Receipt");
endFiscalReceiptButton.setMaximumSize(new Dimension(160,17));
endFiscalReceiptButton.setPreferredSize(new Dimension(160,17));
endFiscalReceiptButton.setActionCommand("endFiscalReceipt");
endFiscalReceiptButton.addActionListener(methodListener);
endFiscalReceiptButton.setAlignmentX(Component.TOP_ALIGNMENT);
endFiscalReceiptButton.setEnabled(false);
buttonPanel.add(endFiscalReceiptButton);
//Labels Panel
JPanel itemLabelPanel = new JPanel();
itemLabelPanel.setLayout( new BoxLayout(itemLabelPanel, BoxLayout.Y_AXIS));
itemLabelPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
itemLabelPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Receipt Message");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("PreLine Text");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("PostLine Text");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Description");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Price-Amount");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Quantity");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Unit Price");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Vat Info");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Unit Name");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Amount - Adj.");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
//Fields Panel
JPanel itemFieldPanel = new JPanel();
itemFieldPanel.setLayout( new BoxLayout(itemFieldPanel, BoxLayout.Y_AXIS));
itemFieldPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
itemFieldPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
recMessageTxt = new JTextField();
recMessageTxt.setMaximumSize(new Dimension(160,17));
recMessageTxt.setPreferredSize(new Dimension(160,17));
recMessageTxt.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(recMessageTxt);
preLineTxt = new JTextField();
preLineTxt.setMaximumSize(new Dimension(160,17));
preLineTxt.setPreferredSize(new Dimension(160,17));
preLineTxt.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(preLineTxt);
postLineTxt = new JTextField();
postLineTxt.setMaximumSize(new Dimension(160,17));
postLineTxt.setPreferredSize(new Dimension(160,17));
postLineTxt.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(postLineTxt);
itemDescription = new JTextField();
itemDescription.setMaximumSize(new Dimension(160,17));
itemDescription.setPreferredSize(new Dimension(160,17));
itemDescription.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(itemDescription);
itemPrice = new JTextField();
itemPrice.setMaximumSize(new Dimension(160,17));
itemPrice.setPreferredSize(new Dimension(160,17));
itemPrice.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(itemPrice);
itemQuantity = new JTextField();
itemQuantity.setMaximumSize(new Dimension(160,17));
itemQuantity.setPreferredSize(new Dimension(160,17));
itemQuantity.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(itemQuantity);
itemUnitPrice = new JTextField();
itemUnitPrice.setMaximumSize(new Dimension(160,17));
itemUnitPrice.setPreferredSize(new Dimension(160,17));
itemUnitPrice.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(itemUnitPrice);
itemVatInfo = new JTextField();
itemVatInfo.setMaximumSize(new Dimension(160,17));
itemVatInfo.setPreferredSize(new Dimension(160,17));
itemVatInfo.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(itemVatInfo);
unitName = new JTextField();
unitName.setMaximumSize(new Dimension(160,17));
unitName.setPreferredSize(new Dimension(160,17));
unitName.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(unitName);
itemAmountPercAdjTxt = new JTextField();
itemAmountPercAdjTxt.setMaximumSize(new Dimension(160,17));
itemAmountPercAdjTxt.setPreferredSize(new Dimension(160,17));
itemAmountPercAdjTxt.setMinimumSize(new Dimension(160,17));
itemFieldPanel.add(itemAmountPercAdjTxt);
//Combo Panel
JPanel comboPanel = new JPanel();
comboPanel.setLayout( new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
comboPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Payament Forms :");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setMaximumSize(new Dimension(130,22));
label.setPreferredSize(new Dimension(130,22));
comboPanel.add(label);
paymantFormCombo = new JComboBox();
paymantFormCombo.setMaximumSize(new Dimension(150,22));
paymantFormCombo.setPreferredSize(new Dimension(150,22));
paymantFormCombo.setAlignmentX(Component.CENTER_ALIGNMENT);
paymantFormCombo.setActionCommand("paymantFormCombo");
paymantFormCombo.addActionListener(methodListener);
paymantFormCombo.setEnabled(false);
comboPanel.add(paymantFormCombo);
label = new JLabel("Vat ID :");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setMaximumSize(new Dimension(130,22));
label.setPreferredSize(new Dimension(130,22));
comboPanel.add(label);
vatIdCombo = new JComboBox();
vatIdCombo.setMaximumSize(new Dimension(150,22));
vatIdCombo.setPreferredSize(new Dimension(150,22));
vatIdCombo.setAlignmentX(Component.CENTER_ALIGNMENT);
vatIdCombo.setActionCommand("vatIdCombo");
vatIdCombo.addActionListener(methodListener);
vatIdCombo.setEnabled(false);
comboPanel.add(vatIdCombo);
label = new JLabel("Adjustment Type :");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setMaximumSize(new Dimension(130,22));
label.setPreferredSize(new Dimension(130,22));
comboPanel.add(label);
adjustmentTypeCombo = new JComboBox();
adjustmentTypeCombo.setMaximumSize(new Dimension(150,22));
adjustmentTypeCombo.setPreferredSize(new Dimension(150,22));
adjustmentTypeCombo.setAlignmentX(Component.CENTER_ALIGNMENT);
adjustmentTypeCombo.setActionCommand("adjustmentTypeCombo");
adjustmentTypeCombo.addActionListener(methodListener);
// adjustmentTypeCombo.setFont(new Font(null,Font.PLAIN,10));
adjustmentTypeCombo.setEnabled(true);
for(int i=0;i<numAdjType;i++)adjustmentTypeCombo.addItem(adjType[i]);
comboPanel.add(adjustmentTypeCombo);
JPanel fiscalReceiptControlPanel = new JPanel();
fiscalReceiptControlPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
fiscalReceiptControlPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
fiscalReceiptControlPanel.setLayout(new BoxLayout(fiscalReceiptControlPanel,BoxLayout.X_AXIS));
fiscalReceiptControlPanel.add(buttonPanel);
fiscalReceiptControlPanel.add(itemLabelPanel);
fiscalReceiptControlPanel.add(itemFieldPanel);
fiscalReceiptControlPanel.add(comboPanel);
return fiscalReceiptControlPanel;
}
}
//Fiscal Printer Fiscal Report Panel
class FiscalPrinterFscReportPanel extends Component{
private static final long serialVersionUID = 8226960362715736598L;
public Component make() {
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
printReportButton = new JButton("Print Report");
printReportButton.setMaximumSize(new Dimension(160,17));
printReportButton.setPreferredSize(new Dimension(160,17));
printReportButton.setActionCommand("printReport");
printReportButton.addActionListener(methodListener);
printReportButton.setAlignmentX(Component.TOP_ALIGNMENT);
printReportButton.setEnabled(false);
buttonPanel.add(printReportButton);
printXReportButton = new JButton("Print X Report");
printXReportButton.setMaximumSize(new Dimension(160,17));
printXReportButton.setPreferredSize(new Dimension(160,17));
printXReportButton.setActionCommand("printXReport");
printXReportButton.addActionListener(methodListener);
printXReportButton.setAlignmentX(Component.TOP_ALIGNMENT);
printXReportButton.setEnabled(false);
buttonPanel.add(printXReportButton);
printZReportButton = new JButton("Print Z Report");
printZReportButton.setMaximumSize(new Dimension(160,17));
printZReportButton.setPreferredSize(new Dimension(160,17));
printZReportButton.setActionCommand("printZReport");
printZReportButton.addActionListener(methodListener);
printZReportButton.setAlignmentX(Component.TOP_ALIGNMENT);
printZReportButton.setEnabled(false);
buttonPanel.add(printZReportButton);
printPeriodicTotalReportButton = new JButton("Print Periodic Report");
printPeriodicTotalReportButton.setMaximumSize(new Dimension(160,17));
printPeriodicTotalReportButton.setPreferredSize(new Dimension(160,17));
printPeriodicTotalReportButton.setActionCommand("printPeriodicReport");
printPeriodicTotalReportButton.addActionListener(methodListener);
printPeriodicTotalReportButton.setAlignmentX(Component.TOP_ALIGNMENT);
printPeriodicTotalReportButton.setEnabled(false);
buttonPanel.add(printPeriodicTotalReportButton);
//Labels Panel
JPanel itemLabelPanel = new JPanel();
itemLabelPanel.setLayout( new BoxLayout(itemLabelPanel, BoxLayout.Y_AXIS));
itemLabelPanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
itemLabelPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Report From :");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
label = new JLabel("Report To :");
label.setAlignmentX(Component.RIGHT_ALIGNMENT);
label.setMaximumSize(new Dimension(110,17));
label.setPreferredSize(new Dimension(110,17));
itemLabelPanel.add(label);
//Fields Panel
JPanel itemFieldPanel = new JPanel();
itemFieldPanel.setLayout( new BoxLayout(itemFieldPanel, BoxLayout.Y_AXIS));
itemFieldPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
itemFieldPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
reportFrom = new JTextField();
reportFrom.setMaximumSize(new Dimension(130,17));
reportFrom.setPreferredSize(new Dimension(130,17));
reportFrom.setMinimumSize(new Dimension(130,17));
itemFieldPanel.add(reportFrom);
reportTo = new JTextField();
reportTo.setMaximumSize(new Dimension(130,17));
reportTo.setPreferredSize(new Dimension(130,17));
reportTo.setMinimumSize(new Dimension(130,17));
itemFieldPanel.add(reportTo);
//Combo Panel
JPanel comboPanel = new JPanel();
comboPanel.setLayout( new BoxLayout(comboPanel, BoxLayout.Y_AXIS));
comboPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
comboPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Report Type :");
label.setAlignmentX(Component.CENTER_ALIGNMENT);
label.setMaximumSize(new Dimension(110,22));
label.setPreferredSize(new Dimension(110,22));
comboPanel.add(label);
reportTypeCombo = new JComboBox();
reportTypeCombo.setMaximumSize(new Dimension(110,22));
reportTypeCombo.setPreferredSize(new Dimension(110,22));
reportTypeCombo.setAlignmentX(Component.CENTER_ALIGNMENT);
reportTypeCombo.setActionCommand("reportTypeCombo");
reportTypeCombo.addActionListener(methodListener);
reportTypeCombo.setFont(new Font(null,Font.PLAIN,10));
reportTypeCombo.setEnabled(true);
reportTypeCombo.addItem("ORDINAL");
reportTypeCombo.addItem("DATE");
comboPanel.add(reportTypeCombo);
JPanel fiscalPtrFscReportControlPanel = new JPanel();
fiscalPtrFscReportControlPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
fiscalPtrFscReportControlPanel.setLayout(new BoxLayout(fiscalPtrFscReportControlPanel,BoxLayout.X_AXIS));
fiscalPtrFscReportControlPanel.add(buttonPanel);
fiscalPtrFscReportControlPanel.add(itemLabelPanel);
fiscalPtrFscReportControlPanel.add(itemFieldPanel);
fiscalPtrFscReportControlPanel.add(reportTypeCombo);
return fiscalPtrFscReportControlPanel;
}
}
//Fiscal Printer Status Panel
class FiscalPrinterStatusPanel extends Component{
private static final long serialVersionUID = 8878274840702299074L;
public Component make() {
//List Items Panel
JPanel itemListPanel = new JPanel();
itemListPanel.setLayout(new BoxLayout(itemListPanel,BoxLayout.Y_AXIS));
itemListPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
label = new JLabel("Text Output: ");
label.setMaximumSize(new Dimension(160,17));
label.setAlignmentX(Component.CENTER_ALIGNMENT);
itemListPanel.add(label);
itemListModel = new DefaultListModel();
itemList = new JList(itemListModel);
itemList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
itemList.setLayoutOrientation(JList.VERTICAL);
itemList.setVisibleRowCount(7);
JScrollPane windowScrollPane = new JScrollPane(itemList);
windowScrollPane.setMinimumSize(new Dimension( 200,250));
windowScrollPane.setPreferredSize(new Dimension(350,300));
windowScrollPane.setMaximumSize(new Dimension( 350,300));
itemListPanel.add(windowScrollPane);
clearOutPutButton = new JButton("Clear Text Output");
clearOutPutButton.setMaximumSize(new Dimension(160,17));
clearOutPutButton.setPreferredSize(new Dimension(160,17));
clearOutPutButton.setActionCommand("clearOutPut");
clearOutPutButton.addActionListener(methodListener);
clearOutPutButton.setAlignmentX(Component.CENTER_ALIGNMENT);
clearOutPutButton.setEnabled(true);
itemListPanel.add(clearOutPutButton);
resetPrinterButton = new JButton("Reset Printer");
resetPrinterButton.setMaximumSize(new Dimension(160,17));
resetPrinterButton.setPreferredSize(new Dimension(160,17));
resetPrinterButton.setActionCommand("resetPrinter");
resetPrinterButton.addActionListener(methodListener);
resetPrinterButton.setAlignmentX(Component.CENTER_ALIGNMENT);
resetPrinterButton.setEnabled(false);
itemListPanel.add(resetPrinterButton);
clearOutputForErrorCB= new JCheckBox("Clear output for Error Event");
clearOutputForErrorCB.setAlignmentX(Component.CENTER_ALIGNMENT);
itemListPanel.add(clearOutputForErrorCB);
//dataPanel
JPanel dataPanel = new JPanel();
dataPanel.setLayout(new BoxLayout(dataPanel,BoxLayout.Y_AXIS));
dataPanel.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
ButtonGroup bg=new ButtonGroup();
firmwareRB=new JRadioButton("Firmware Release Number");//firmware
bg.add(firmwareRB);dataPanel.add(firmwareRB);firmwareRB.doClick();
printerIDRB=new JRadioButton("Printer's Fiscal ID");
bg.add(printerIDRB);dataPanel.add(printerIDRB);
currentRecTotalRB=new JRadioButton("Current Receipt Total");
bg.add(currentRecTotalRB);dataPanel.add(currentRecTotalRB);
currentTotalRB=new JRadioButton("Daily Total");
bg.add(currentTotalRB);dataPanel.add(currentTotalRB);
grandTotalRB=new JRadioButton("Fiscal Printer's Grand Total");
bg.add(grandTotalRB);dataPanel.add(grandTotalRB);
mitVoidRB=new JRadioButton("Total Number of Voided Receipts");
bg.add(mitVoidRB);dataPanel.add(mitVoidRB);
fiscalRecRB=new JRadioButton("N. of Daily Fiscal Sales Receipts");
bg.add(fiscalRecRB);dataPanel.add(fiscalRecRB);
receiptNumberRB=new JRadioButton("N. of Fiscal Receipts Printed");
bg.add(receiptNumberRB);dataPanel.add(receiptNumberRB);
refundRB=new JRadioButton("Current Total of Refunds");
bg.add(refundRB);dataPanel.add(refundRB);
fiscalRecVoidRB=new JRadioButton("N. of Daily Voided Fiscal Sales Receipt");
bg.add(fiscalRecVoidRB);dataPanel.add(fiscalRecVoidRB);
nonFiscalRecRB=new JRadioButton("N. of Daily Non Fiscal Sales Receipts");
bg.add(nonFiscalRecRB);dataPanel.add(nonFiscalRecRB);
descriptionLengthRB=new JRadioButton("Description Length");
bg.add(descriptionLengthRB);dataPanel.add(descriptionLengthRB);
zReportRB=new JRadioButton("Z Report");
bg.add(zReportRB);dataPanel.add(zReportRB);
getDataButton = new JButton("GetData");
getDataButton.setMaximumSize(new Dimension(160,17));
getDataButton.setPreferredSize(new Dimension(160,17));
getDataButton.setActionCommand("getData");
getDataButton.addActionListener(methodListener);
getDataButton.setAlignmentX(Component.TOP_ALIGNMENT);
getDataButton.setEnabled(false);
dataPanel.add(getDataButton);
//dataPanelBis
JPanel dataPanelBis = new JPanel();
dataPanelBis.setLayout(new BoxLayout(dataPanelBis,BoxLayout.Y_AXIS));
dataPanelBis.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
ButtonGroup bgbis=new ButtonGroup();
dayTotalizerRB=new JRadioButton("Daily Totalizer");
dayTotalizerRB.setAlignmentX(Component.CENTER_ALIGNMENT);
bgbis.add(dayTotalizerRB);dataPanelBis.add(dayTotalizerRB);dayTotalizerRB.doClick();
grandTotalizerRB=new JRadioButton("Grand Totalizer");
grandTotalizerRB.setAlignmentX(Component.CENTER_ALIGNMENT);
bgbis.add(grandTotalizerRB);dataPanelBis.add(grandTotalizerRB);
totalTypeCombo = new JComboBox();
totalTypeCombo.setMaximumSize(new Dimension(160,22));
totalTypeCombo.setPreferredSize(new Dimension(160,22));
totalTypeCombo.setAlignmentX(Component.CENTER_ALIGNMENT);
totalTypeCombo.setActionCommand("totalTypeCombo");
// totalTypeCombo.setFont(new Font(null,Font.PLAIN,10));
totalTypeCombo.setEnabled(true);
totalTypeCombo.addItem("Item Totalizer");totalTypeCombo.addItem("Refund Totalizer");
totalTypeCombo.addItem("Voided Item Totalizer");totalTypeCombo.addItem("Discount Totalizer");
totalTypeCombo.addItem("Gross Totalizer");
dataPanelBis.add(totalTypeCombo);
vatIdCombo_2 = new JComboBox();
vatIdCombo_2.setMaximumSize(new Dimension(150,22));
vatIdCombo_2.setPreferredSize(new Dimension(150,22));
vatIdCombo_2.setAlignmentX(Component.CENTER_ALIGNMENT);
vatIdCombo_2.setActionCommand("vatIdCombo_2");
vatIdCombo_2.addActionListener(methodListener);
vatIdCombo_2.setEnabled(false);
dataPanelBis.add(vatIdCombo_2);
dataPanelBis.add(Box.createVerticalStrut(17));
getTotalizerButton = new JButton("GetTotalizer");
getTotalizerButton.setMaximumSize(new Dimension(160,17));
getTotalizerButton.setPreferredSize(new Dimension(160,17));
getTotalizerButton.setActionCommand("getTotalizer");
getTotalizerButton.addActionListener(methodListener);
getTotalizerButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getTotalizerButton.setEnabled(false);
dataPanelBis.add(getTotalizerButton);
getDateButton = new JButton("Get Date");
getDateButton.setMaximumSize(new Dimension(160,17));
getDateButton.setPreferredSize(new Dimension(160,17));
getDateButton.setActionCommand("getDate");
getDateButton.addActionListener(methodListener);
getDateButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getDateButton.setEnabled(false);
dataPanelBis.add(getDateButton);
getTrainingStateButton = new JButton("Get Training Mode");
getTrainingStateButton.setMaximumSize(new Dimension(160,17));
getTrainingStateButton.setPreferredSize(new Dimension(160,17));
getTrainingStateButton.setActionCommand("getTrainingState");
getTrainingStateButton.addActionListener(methodListener);
getTrainingStateButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getTrainingStateButton.setEnabled(false);
dataPanelBis.add(getTrainingStateButton);
getErrorLevelButton = new JButton("Get Error Info");
getErrorLevelButton.setMaximumSize(new Dimension(160,17));
getErrorLevelButton.setPreferredSize(new Dimension(160,17));
getErrorLevelButton.setActionCommand("getErrorLevel");
getErrorLevelButton.addActionListener(methodListener);
getErrorLevelButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getErrorLevelButton.setEnabled(false);
dataPanelBis.add(getErrorLevelButton);
getOutPutIdButton = new JButton("Get Output ID");
getOutPutIdButton.setMaximumSize(new Dimension(160,17));
getOutPutIdButton.setPreferredSize(new Dimension(160,17));
getOutPutIdButton.setActionCommand("getOutPutId");
getOutPutIdButton.addActionListener(methodListener);
getOutPutIdButton.setAlignmentX(Component.CENTER_ALIGNMENT);
getOutPutIdButton.setEnabled(false);
dataPanelBis.add(getOutPutIdButton);
printerStatusButton = new JButton("Get Printer Status");
printerStatusButton.setMaximumSize(new Dimension(160,17));
printerStatusButton.setPreferredSize(new Dimension(160,17));
printerStatusButton.setActionCommand("printerStatus");
printerStatusButton.addActionListener(methodListener);
printerStatusButton.setAlignmentX(Component.CENTER_ALIGNMENT);
printerStatusButton.setEnabled(false);
dataPanelBis.add(printerStatusButton);
dayOpenedButton = new JButton("Get Day Opened");
dayOpenedButton.setMaximumSize(new Dimension(160,17));
dayOpenedButton.setPreferredSize(new Dimension(160,17));
dayOpenedButton.setActionCommand("dayOpened");
dayOpenedButton.addActionListener(methodListener);
dayOpenedButton.setAlignmentX(Component.CENTER_ALIGNMENT);
dayOpenedButton.setEnabled(false);
dataPanelBis.add(dayOpenedButton);
remainingFiscalMemoryButton = new JButton("Get Rem. Fiscal Memory");
remainingFiscalMemoryButton.setMaximumSize(new Dimension(160,17));
remainingFiscalMemoryButton.setPreferredSize(new Dimension(160,17));
remainingFiscalMemoryButton.setActionCommand("remainingFiscalMemory");
remainingFiscalMemoryButton.addActionListener(methodListener);
remainingFiscalMemoryButton.setAlignmentX(Component.CENTER_ALIGNMENT);
remainingFiscalMemoryButton.setEnabled(false);
dataPanelBis.add(remainingFiscalMemoryButton);
showPropertyButton = new JButton("Show Other Property");
showPropertyButton.setMaximumSize(new Dimension(160,17));
showPropertyButton.setPreferredSize(new Dimension(160,17));
showPropertyButton.setActionCommand("showProperty");
showPropertyButton.addActionListener(methodListener);
showPropertyButton.setAlignmentX(Component.CENTER_ALIGNMENT);
showPropertyButton.setEnabled(false);
dataPanelBis.add(showPropertyButton);
JPanel fiscalPtrStatusControlPanel = new JPanel();
fiscalPtrStatusControlPanel.setBorder(BorderFactory.createEmptyBorder(10,10,5,5));
fiscalPtrStatusControlPanel.setLayout(new BoxLayout(fiscalPtrStatusControlPanel,BoxLayout.X_AXIS));
fiscalPtrStatusControlPanel.add(itemListPanel);
fiscalPtrStatusControlPanel.add(dataPanel);
fiscalPtrStatusControlPanel.add(dataPanelBis);
return fiscalPtrStatusControlPanel;
}
}
private class StatusTimerUpdateTask extends java.util.TimerTask{
public void run(){
if(fiscalPrinter != null){
mainButtonPanel.currentStatus.setText(MainButtonPanel.getStatusString(fiscalPrinter.getState()));
}
}
}
}
| epl-1.0 |