repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
BretJohnson/autorest
AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/AutoRestSwaggerBATFileService.java
746
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ package fixtures.bodyfile; /** * The interface for AutoRestSwaggerBATFileService class. */ public interface AutoRestSwaggerBATFileService { /** * Gets the URI used as the base for all cloud service requests. * @return The BaseUri value. */ String getBaseUri(); /** * Gets the Files object to access its operations. * @return the files value. */ Files getFiles(); }
mit
xygdev/XYG_ALB2B
src/com/xinyiglass/springSample/entity/FuncVO.java
4250
package com.xinyiglass.springSample.entity; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.beans.factory.FactoryBean; import org.springframework.jdbc.core.RowMapper; @SuppressWarnings("rawtypes") public class FuncVO implements FactoryBean,RowMapper<FuncVO>, Cloneable{ private Long functionId; private String functionCode; private String functionName; private String functionHref; private String description; private Long iconId; private String iconCode; private Long createdBy; private java.util.Date creationDate; private Long lastUpdatedBy; private java.util.Date lastUpdateDate; private Long lastUpdateLogin; //GET&SET Method public Long getFunctionId() { return functionId; } public void setFunctionId(Long functionId) { this.functionId = functionId; } public String getFunctionCode() { return functionCode; } public void setFunctionCode(String functionCode) { this.functionCode = functionCode; } public String getFunctionName() { return functionName; } public void setFunctionName(String functionName) { this.functionName = functionName; } public String getFunctionHref() { return functionHref; } public void setFunctionHref(String functionHref) { this.functionHref = functionHref; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getIconId() { return iconId; } public void setIconId(Long iconId) { this.iconId = iconId; } public String getIconCode() { return iconCode; } public void setIconCode(String iconCode) { this.iconCode = iconCode; } public Long getCreatedBy() { return createdBy; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } public java.util.Date getCreationDate() { return creationDate; } public void setCreationDate(java.util.Date creationDate) { this.creationDate = creationDate; } public Long getLastUpdatedBy() { return lastUpdatedBy; } public void setLastUpdatedBy(Long lastUpdatedBy) { this.lastUpdatedBy = lastUpdatedBy; } public java.util.Date getLastUpdateDate() { return lastUpdateDate; } public void setLastUpdateDate(java.util.Date lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } public Long getLastUpdateLogin() { return lastUpdateLogin; } public void setLastUpdateLogin(Long lastUpdateLogin) { this.lastUpdateLogin = lastUpdateLogin; } @Override public Object clone() { FuncVO funcVO = null; try{ funcVO = (FuncVO)super.clone(); }catch(CloneNotSupportedException e) { e.printStackTrace(); } return funcVO; } @Override public FuncVO mapRow(ResultSet rs, int rowNum) throws SQLException { FuncVO func = new FuncVO(); func.setFunctionId(rs.getLong("function_id")); func.setFunctionCode(rs.getString("function_code")); func.setFunctionName(rs.getString("function_name")); func.setFunctionHref(rs.getString("function_href")); func.setDescription(rs.getObject("description")==null?null:rs.getString("description")); func.setIconId(rs.getLong("icon_id")); func.setIconCode(rs.getString("icon_code")); func.setCreatedBy(rs.getLong("created_by")); func.setCreationDate(rs.getDate("creation_date")); func.setLastUpdatedBy(rs.getLong("last_updated_by")); func.setLastUpdateDate(rs.getDate("last_update_date")); func.setLastUpdateLogin(rs.getLong("last_update_login")); return func; } @Override public Object getObject() throws Exception { // TODO Auto-generated method stub return null; } @Override public Class getObjectType() { // TODO Auto-generated method stub return null; } @Override public boolean isSingleton() { // TODO Auto-generated method stub return false; } }
mit
pandu1990/AndroidRemote
src/com/pandu/remotemouse/Help.java
750
package com.pandu.remotemouse; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Help extends Dialog{ public Help(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.help); setTitle("Help"); Button but = (Button) findViewById(R.id.bCloseDialog); but.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub dismiss(); } }); } }
mit
ernieyu/simple-feed-parser
src/test/java/com/ernieyu/feedparser/LiveFeedTestSuite.java
4870
package com.ernieyu.feedparser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.InputStream; import java.net.URL; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.ernieyu.feedparser.Feed; import com.ernieyu.feedparser.FeedParser; import com.ernieyu.feedparser.FeedParserFactory; import com.ernieyu.feedparser.FeedType; import com.ernieyu.feedparser.Item; /** * Test case using live feeds. */ public class LiveFeedTestSuite { private final static String BBC_WORLD_NEWS = "http://feeds.bbci.co.uk/news/world/rss.xml"; private final static String NYT_WORLD_NEWS = "http://feeds.nytimes.com/nyt/rss/World"; private final static String USGS_QUAKE_ATOM = "http://earthquake.usgs.gov/earthquakes/catalogs/1hour-M1.xml"; private final static String USGS_QUAKE_RSS = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs1hour-M1.xml"; private final static Logger LOG = Logger.getLogger(LiveFeedTestSuite.class.getName()); private FeedParser feedParser; @Before public void setUp() throws Exception { feedParser = FeedParserFactory.newParser(); } @After public void tearDown() throws Exception { feedParser = null; } /** Test using BBC world news RSS feed. */ @Test public void testBBCNewsRss() { try { // Open input stream for test feed. URL url = new URL(BBC_WORLD_NEWS); InputStream inStream = url.openConnection().getInputStream(); // Parse feed. Feed feed = feedParser.parse(inStream); assertEquals("feed name", "rss", feed.getName()); assertEquals("feed type", FeedType.RSS_2_0, feed.getType()); assertEquals("feed title", "BBC News - World", feed.getTitle()); List<Item> itemList = feed.getItemList(); LOG.log(Level.INFO, "item count = " + itemList.size()); assertTrue("item count", itemList.size() > 0); } catch (Exception ex) { fail(ex.getMessage()); } } /** Test using NY Times world news RSS feed. */ @Test public void testNYTimesRss() { try { // Open input stream for test feed. URL url = new URL(NYT_WORLD_NEWS); InputStream inStream = url.openConnection().getInputStream(); // Parse feed. Feed feed = feedParser.parse(inStream); assertEquals("feed name", "rss", feed.getName()); assertEquals("feed type", FeedType.RSS_2_0, feed.getType()); assertEquals("feed title", "NYT > World", feed.getTitle()); List<Item> itemList = feed.getItemList(); LOG.log(Level.INFO, "item count = " + itemList.size()); assertTrue("item count", itemList.size() > 0); } catch (Exception ex) { fail(ex.getMessage()); } } /** Test using USGS earthquakes Atom feed. */ @Test public void testUSGSQuakesAtom() { try { // Open input stream for test feed. URL url = new URL(USGS_QUAKE_ATOM); InputStream inStream = url.openConnection().getInputStream(); // Parse feed. Feed feed = feedParser.parse(inStream); assertEquals("feed name", "feed", feed.getName()); assertEquals("feed type", FeedType.ATOM_1_0, feed.getType()); assertEquals("feed title", "USGS M 1+ Earthquakes", feed.getTitle()); List<Item> itemList = feed.getItemList(); LOG.log(Level.INFO, "item count = " + itemList.size()); assertTrue("item count", itemList.size() > 0); } catch (Exception ex) { fail(ex.getMessage()); } } /** Test using USGS earthquakes RSS feed. */ @Test public void testUSGSQuakesRss() { try { // Open input stream for test feed. URL url = new URL(USGS_QUAKE_RSS); InputStream inStream = url.openConnection().getInputStream(); // Parse feed. Feed feed = feedParser.parse(inStream); assertEquals("feed name", "rss", feed.getName()); assertEquals("feed type", FeedType.RSS_2_0, feed.getType()); assertEquals("feed title", "USGS M 1+ Earthquakes", feed.getTitle()); List<Item> itemList = feed.getItemList(); LOG.log(Level.INFO, "item count = " + itemList.size()); assertTrue("item count", itemList.size() > 0); } catch (Exception ex) { fail(ex.getMessage()); } } }
mit
bmariesan/iStudent
src/main/java/ro/ubb/samples/structural/facade/point/Client.java
558
package ro.ubb.samples.structural.facade.point; public class Client { public static void main(String[] args) { // 3. Client uses the Facade Line lineA = new Line(new Point(2, 4), new Point(5, 7)); lineA.move(-2, -4); System.out.println( "after move: " + lineA ); lineA.rotate(45); System.out.println( "after rotate: " + lineA ); Line lineB = new Line( new Point(2, 1), new Point(2.866, 1.5)); lineB.rotate(30); System.out.println("30 degrees to 60 degrees: " + lineB); } }
mit
Simmarith/userMan
src/com/simmarith/sqlCon/Permission.java
2289
package com.simmarith.sqlCon; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; public class Permission extends DbEntity { // Properties private String name = null; private String description = null; // Getter and Setter public String getName() { if (this.name == null) { this.name = this.fetchProperty("name"); } return name; } public void setName(String name) { this.name = name; } public String getDescription() { if (this.description == null) { this.description = this.fetchProperty("description"); } return description; } public void setDescription(String description) { this.description = description; } // Methods public static ArrayList<Permission> getAllPermissions() { SqlConnection con = SqlConnection.getInstance(); ArrayList<Permission> allPermissions = new ArrayList<>(); ResultSet res = con.sql("Select id from user"); try { while (res.next()) { allPermissions .add(new Permission(Long.toString(res.getLong(1)))); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return allPermissions; } public void persist() { if (this.getId() == null) { ResultSet res = this.con.sql(String.format( "insert into %s (name, description) values ('%s', '%s')", this.tableName, this.getName(), this.getDescription())); try { res.next(); this.setId(Long.toString(res.getLong(1))); return; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.con.sql(String.format("update %s set name = '%s', description = '%s' where id = %s", this.tableName, this.getName(), this.getDescription(), this.getId())); } // Constructors public Permission() { super("permission"); } public Permission(String id) { this(); this.setId(id); } }
mit
ignaciotcrespo/frutilla
java/src/test/java/org/frutilla/examples/FrutillaExamplesWithAnnotationTest.java
1278
package org.frutilla.examples; import org.frutilla.annotations.Frutilla; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertTrue; /** * Examples using Frutilla with annotations. */ @RunWith(value = org.frutilla.FrutillaTestRunner.class) public class FrutillaExamplesWithAnnotationTest { @Frutilla( Given = "a test with Frutilla annotations", When = "it fails", Then = { "it shows the test description in the stacktrace", "and in the logs" } ) @Test public void testFailed() { // assertTrue(false); } @Frutilla( Given = "a test with Frutilla annotations", When = "it fails due to error", Then = { "it shows the test description in the stacktrace", "and in the logs" } ) @Test public void testError() { // throw new RuntimeException("forced error"); } @Frutilla( Given = "a test with Frutilla annotations", When = "it passes", Then = "it shows the test description in the logs" ) @Test public void testPassed() { assertTrue(true); } }
mit
FloThinksPi/Catalyst-PresetSwitcher
Server/src/com/cccrps/gui/GuiManager.java
11468
package com.cccrps.gui; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.HeadlessException; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemColor; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.net.UnknownHostException; import java.util.prefs.Preferences; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingConstants; import org.apache.commons.io.IOUtils; import com.cccrps.main.Main; import com.cccrps.main.SimpleUpdater; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class GuiManager { private JFrame frmCccrps; /** * Create the application. * @throws FileNotFoundException */ public GuiManager() throws FileNotFoundException { } public JFrame getFrame(){ return frmCccrps; } /** * Initialize the contents of the frame. * @throws FileNotFoundException * @throws UnknownHostException * @wbp.parser.entryPoint */ public void initialize() throws FileNotFoundException, UnknownHostException { frmCccrps = new JFrame(); Image icon = new ImageIcon(this.getClass().getResource("/images/icon.png")).getImage(); frmCccrps.setIconImage(icon); frmCccrps.addWindowListener(new WindowAdapter() { public void windowOpened(WindowEvent e){ final Preferences prefs; prefs = Preferences.userNodeForPackage(this.getClass()); boolean isminimized=Boolean.parseBoolean(prefs.get("checkbminimized", "")); System.out.println(isminimized); if(isminimized){ System.out.println("Minimizing"); frmCccrps.setExtendedState(Frame.ICONIFIED); } System.out.println("WindowOpened"); } @Override public void windowClosing(WindowEvent e){ frmCccrps.setVisible(false); displayTrayIcon(); } public void windowClosed(WindowEvent e){} public void windowIconified(WindowEvent e){ frmCccrps.setVisible(false); displayTrayIcon(); } public void windowDeiconified(WindowEvent e){} public void windowActivated(WindowEvent e){ System.out.println("windowActivated"); } public void windowDeactivated(WindowEvent e){} }); final Preferences prefs; prefs = Preferences.userNodeForPackage(this.getClass()); frmCccrps.setResizable(false); frmCccrps.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frmCccrps.setTitle("CRP"); frmCccrps.setBounds(100, 100, 240, 310); JPanel panel = new JPanel(); frmCccrps.getContentPane().add(panel, BorderLayout.NORTH); JLabel lblNewLabel = new JLabel("Catalyst Remote Profile Server"); panel.add(lblNewLabel); JDesktopPane desktopPane = new JDesktopPane(); desktopPane.setBackground(SystemColor.menu); frmCccrps.getContentPane().add(desktopPane, BorderLayout.CENTER); final JCheckBox chckbxStartMinimized = new JCheckBox("Start Minimized"); chckbxStartMinimized.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { prefs.put("checkbminimized", String.valueOf(chckbxStartMinimized.isSelected())); } }); chckbxStartMinimized.setHorizontalAlignment(SwingConstants.CENTER); chckbxStartMinimized.setBounds(10, 80, 212, 25); desktopPane.add(chckbxStartMinimized); boolean isminimized=Boolean.parseBoolean(prefs.get("checkbminimized", "")); System.out.println(isminimized); if(isminimized){ System.out.println("Minimizing"); chckbxStartMinimized.setSelected(true); frmCccrps.setExtendedState(Frame.ICONIFIED); } JButton btnCloseServer = new JButton("Shutdown Server"); btnCloseServer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); btnCloseServer.setBounds(10, 177, 212, 30); desktopPane.add(btnCloseServer); JButton btnStartOnWindows = new JButton("Website(Instructions & About)"); btnStartOnWindows.setForeground(new Color(255, 0, 0)); btnStartOnWindows.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { java.awt.Desktop.getDesktop().browse(new URI("http://goo.gl/uihUNy")); } catch (IOException | URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); btnStartOnWindows.setBounds(10, 28, 212, 43); desktopPane.add(btnStartOnWindows); JLabel lblIp = new JLabel(""); lblIp.setText("IP: "+InetAddress.getLocalHost().getHostAddress()); lblIp.setHorizontalAlignment(SwingConstants.CENTER); lblIp.setBounds(10, 148, 210, 16); desktopPane.add(lblIp); final JCheckBox checkBoxAutoStart = new JCheckBox("Autostart"); checkBoxAutoStart.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if(checkBoxAutoStart.isSelected()){ JOptionPane.showMessageDialog(null,"!Warning, if ServerFile(.jar) gets moved , Autostart has to be applied again!"); } } }); checkBoxAutoStart.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent arg0) { prefs.put("autostart", String.valueOf(checkBoxAutoStart.isSelected())); String targetpath = "C:\\Users\\"+System.getProperty("user.name")+"\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\CRPServerAutostarter.bat"; if(checkBoxAutoStart.isSelected()){ Writer writer = null; try { writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(targetpath), "utf-8")); File f = new File(System.getProperty("java.class.path")); File dir = f.getAbsoluteFile().getParentFile(); String path = dir.toString(); writer.write("start /min javaw -jar \""+path+"\\"+f.getName()+"\""); } catch (IOException ex) { // report } finally { try {writer.close();} catch (Exception ex) {} } }else{ try{ File file = new File(targetpath); file.delete(); }catch(Exception e){ e.printStackTrace(); } } } }); if(Boolean.parseBoolean(prefs.get("autostart", ""))){ checkBoxAutoStart.setSelected(true); }else{ checkBoxAutoStart.setSelected(false); } checkBoxAutoStart.setHorizontalAlignment(SwingConstants.CENTER); checkBoxAutoStart.setBounds(10, 110, 212, 25); desktopPane.add(checkBoxAutoStart); JLabel lblVersion = new JLabel("Version Undefined"); lblVersion.setHorizontalAlignment(SwingConstants.CENTER); lblVersion.setBounds(41, 0, 154, 16); lblVersion.setText("Version: "+Main.getVersion()); desktopPane.add(lblVersion); JButton btnCheckForUpdates = new JButton("Check For Updates"); btnCheckForUpdates.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { int NewVersion=Integer.parseInt(IOUtils.toString(new URL("https://flothinkspi.github.io/Catalyst-PresetSwitcher/version.json")).replace("\n", "").replace("\r", "")); if(NewVersion>Integer.parseInt(Main.getVersion())){ int dialogResult = JOptionPane.showConfirmDialog (null, "Update found from "+Main.getVersion()+" to "+NewVersion+" ,Update now ?","CRPServer Updater",JOptionPane.YES_NO_OPTION); if(dialogResult == JOptionPane.YES_OPTION){ String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath(); String decodedPath = URLDecoder.decode(path, "UTF-8"); System.out.println(decodedPath); SimpleUpdater.update(new URL("https://flothinkspi.github.io/Catalyst-PresetSwitcher/download/CRPServer.jar"),new File(decodedPath) , "updated"); System.exit(0); } }else{ JOptionPane.showConfirmDialog (null, "No Updates , You have the latest CRPServer(Version:"+Main.getVersion()+")","CRPServer Updater",JOptionPane.PLAIN_MESSAGE); } } catch (NumberFormatException | HeadlessException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); btnCheckForUpdates.setBounds(10, 213, 212, 30); desktopPane.add(btnCheckForUpdates); frmCccrps.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { frmCccrps.setExtendedState(Frame.ICONIFIED); } }); } public void displayTrayIcon(){ final TrayIcon trayIcon; if (SystemTray.isSupported()) { final SystemTray tray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/icon.gif")); PopupMenu popup = new PopupMenu(); trayIcon = new TrayIcon(image, "CCCRPS", popup); trayIcon.setImageAutoSize(true); //trayIcon.addMouseListener(mouseListener); MenuItem defaultItem = new MenuItem("Stop Server"); defaultItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); popup.add(defaultItem); trayIcon.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) { frmCccrps.setVisible(true); frmCccrps.setState ( Frame.NORMAL ); tray.remove(trayIcon); } } }); try { tray.add(trayIcon); } catch (AWTException e) { System.err.println("TrayIcon could not be added."); } } else { System.err.println("System tray is currently not supported."); } } }
mit
bhlshrf/IR
src/finalir/DataStructure/CoreLabel.java
726
package finalir; public class CoreLabel{ String word; String lemma; int position; public CoreLabel setWord(String s){ word = s; return this; } public String word(){ return word; } public CoreLabel setBeginPosition(int t){ position = t; return this; } public int beginPosition(){ return position; } public CoreLabel setLemma(String s){ lemma = s; return this; } public String lemma(){ return lemma; } public CoreLabel(){} public CoreLabel(String w,String l,int p){ word = w; lemma = l; position = p; } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/termstore/requests/StoreCollectionResponse.java
752
// Template Source: BaseEntityCollectionResponse.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.termstore.requests; import com.microsoft.graph.termstore.models.Store; import com.microsoft.graph.http.BaseCollectionResponse; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Store Collection Response. */ public class StoreCollectionResponse extends BaseCollectionResponse<Store> { }
mit
iyubinest/Bonzai
app/src/main/java/co/iyubinest/bonzai/App.java
1212
/** * Copyright (C) 2017 Cristian Gomez Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.iyubinest.bonzai; import android.app.Application; import android.support.annotation.VisibleForTesting; import com.facebook.stetho.Stetho; public class App extends Application { private AppComponent component; @Override public void onCreate() { super.onCreate(); Stetho.initializeWithDefaults(this); component = DaggerAppComponent.builder().appModule(new AppModule(this)).build(); } public AppComponent component() { return component; } @VisibleForTesting public void setComponent(AppComponent component) { this.component = component; } }
mit
AvaliaSystems/Samba
Samba-build/Samba-tests/src/test/java/io/avalia/samba/IluTest.java
1243
package io.avalia.samba; import org.junit.Assert; import static org.junit.Assert.assertNotNull; import org.junit.Test; /** * *** IMPORTANT WARNING : DO NOT EDIT THIS FILE *** * * This file is used to specify what you have to implement. To check your work, * we will run our own copy of the automated tests. If you change this file, * then you will introduce a change of specification!!! * * @author Olivier Liechti */ public class IluTest { @Test public void anIluShouldMakeBum() { IInstrument ilu = new Ilu(); String sound = ilu.play(); Assert.assertEquals("bum", sound); } @Test public void anIluShouldBeDarkYellow() { IInstrument ilu = new Ilu(); String color = ilu.getColor(); Assert.assertEquals("dark yellow", color); } @Test public void anIluShouldLouderThanATrumpetAndAFluteCombined() { IInstrument trumpet = new Trumpet(); IInstrument flute = new Flute(); IInstrument ilu = new Ilu(); int trumpetVolume = trumpet.getSoundVolume(); int fluteVolume = flute.getSoundVolume(); int trumpetAndFluteVolumeCombined = fluteVolume + trumpetVolume; int iluVolume = ilu.getSoundVolume(); Assert.assertTrue(iluVolume > trumpetAndFluteVolumeCombined); } }
mit
trc492/Frc2015RecycleRush
code/WPILibJ/Victor.java
3781
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008-2012. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj; import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType; import edu.wpi.first.wpilibj.communication.UsageReporting; import edu.wpi.first.wpilibj.livewindow.LiveWindow; /** * VEX Robotics Victor 888 Speed Controller * * The Vex Robotics Victor 884 Speed Controller can also be used with this * class but may need to be calibrated per the Victor 884 user manual. */ public class Victor extends SafePWM implements SpeedController { /** * Common initialization code called by all constructors. * * Note that the Victor uses the following bounds for PWM values. These values were determined * empirically and optimized for the Victor 888. These values should work reasonably well for * Victor 884 controllers also but if users experience issues such as asymmetric behaviour around * the deadband or inability to saturate the controller in either direction, calibration is recommended. * The calibration procedure can be found in the Victor 884 User Manual available from VEX Robotics: * http://content.vexrobotics.com/docs/ifi-v884-users-manual-9-25-06.pdf * * - 2.027ms = full "forward" * - 1.525ms = the "high end" of the deadband range * - 1.507ms = center of the deadband range (off) * - 1.49ms = the "low end" of the deadband range * - 1.026ms = full "reverse" */ private void initVictor() { setBounds(2.027, 1.525, 1.507, 1.49, 1.026); setPeriodMultiplier(PeriodMultiplier.k2X); setRaw(m_centerPwm); setZeroLatch(); LiveWindow.addActuator("Victor", getChannel(), this); UsageReporting.report(tResourceType.kResourceType_Victor, getChannel()); } /** * Constructor. * * @param channel The PWM channel that the Victor is attached to. 0-9 are on-board, 10-19 are on the MXP port */ public Victor(final int channel) { super(channel); initVictor(); } /** * Set the PWM value. * * @deprecated For compatibility with CANJaguar * * The PWM value is set using a range of -1.0 to 1.0, appropriately * scaling the value for the FPGA. * * @param speed The speed to set. Value should be between -1.0 and 1.0. * @param syncGroup The update group to add this Set() to, pending UpdateSyncGroup(). If 0, update immediately. */ public void set(double speed, byte syncGroup) { setSpeed(speed); Feed(); } /** * Set the PWM value. * * The PWM value is set using a range of -1.0 to 1.0, appropriately * scaling the value for the FPGA. * * @param speed The speed value between -1.0 and 1.0 to set. */ public void set(double speed) { setSpeed(speed); Feed(); } /** * Get the recently set value of the PWM. * * @return The most recently set value for the PWM between -1.0 and 1.0. */ public double get() { return getSpeed(); } /** * Write out the PID value as seen in the PIDOutput base object. * * @param output Write out the PWM value as was found in the PIDController */ public void pidWrite(double output) { set(output); } }
mit
mizool/mizool
technology/aws/src/main/java/com/github/mizool/technology/aws/dynamodb/ZonedDateTimeConverter.java
605
package com.github.mizool.technology.aws.dynamodb; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter; public class ZonedDateTimeConverter implements DynamoDBTypeConverter<String, ZonedDateTime> { @Override public String convert(ZonedDateTime object) { return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(object); } @Override public ZonedDateTime unconvert(String object) { return ZonedDateTime.parse(object, DateTimeFormatter.ISO_ZONED_DATE_TIME); } }
mit
Syynth/libcfg
src/com/syynth/libcfg/Config.java
4160
package com.syynth.libcfg; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import java.io.File; import java.io.IOException; import java.util.HashMap; /** * @author syynth * @since 2/18/14 */ public class Config { private final Document config; private final File file; /** * Create a Config document with the file located at <code>name</code>. * @param name */ public Config(String name) { Document cfg; file = new File(name); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); cfg = builder.parse(file); } catch (ParserConfigurationException | SAXException | IOException ex) { cfg = null; } config = cfg; } public boolean getBoolean(String name) { return Boolean.parseBoolean(getProperty(name)); } public boolean getBoolean(String group, String name) { return Boolean.parseBoolean(getProperty(group, name)); } public int getInt(String name) { return Integer.parseInt(getProperty(name)); } public int getInt(String group, String name) { return Integer.parseInt(getProperty(group, name)); } public float getFloat(String name) { return Float.parseFloat(getProperty(name)); } public float getFloat(String group, String name) { return Float.parseFloat(getProperty(group, name)); } public double getDouble(String name) { return Double.parseDouble(getProperty(name)); } public double getDouble(String group, String name) { return Double.parseDouble(getProperty(group, name)); } public String getProperty(String property) { return getProperty("global", property); } public String getProperty(String group, String property) { if (config != null) { return ""; } XPathFactory factory = XPathFactory.newInstance(); XPath path = factory.newXPath(); try { return (String) path.evaluate("//propertyGroup[@name='" + group + "']/property[@name='" + property + "']/text()", config, XPathConstants.STRING); } catch (XPathExpressionException ex) { return ""; } } public HashMap<String, String> getPropertyGroup(String groupName) { HashMap<String, String> group = new HashMap<>(); if (config == null) { return group; } try { XPathFactory factory = XPathFactory.newInstance(); XPath path = factory.newXPath(); NodeList nl = (NodeList) path.evaluate("//propertyGroup[@name='" + groupName + "']/property", config, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); ++i) { Element n = (Element) nl.item(i); group.put(n.getAttribute("name"), n.getTextContent()); } } catch (XPathExpressionException ignored) {} return group; } public boolean setProperty(String group, String name, String value) { XPathFactory factory = XPathFactory.newInstance(); XPathExpression xpr; XPath xpath = factory.newXPath(); try { xpr = xpath.compile("//propertyGroup[@name='" + group + "']/property[@name='" + name + "']/text()"); Node n = (Node) xpr.evaluate(config, XPathConstants.NODE); n.setNodeValue(value); return new XmlDocumentWriter().write(config, file); } catch (XPathExpressionException ex) { return false; } } private static class XmlDocumentWriter { public boolean write(Document doc, File file) { TransformerFactory factory = TransformerFactory.newInstance(); try { Transformer transformer = factory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (TransformerException e) { e.printStackTrace(); return false; } return true; } } }
mit
neolfdev/dlscxx
java_core_src/src/cn/org/rapid_framework/page/impl/ListPage.java
1198
package cn.org.rapid_framework.page.impl; import java.util.List; import cn.org.rapid_framework.page.Page; import cn.org.rapid_framework.page.PageRequest; /** * 处理List的分页 * @author badqiu * @see BasePage */ @Deprecated public class ListPage extends Page { /** * 构建ListPage对象,完成List数据的分页处理 * * @param elements List数据源 * @param pageNumber 当前页编码,从1开始,如果传的值为Integer.MAX_VALUE表示获取最后一页。 * 如果你不知道最后一页编码,传Integer.MAX_VALUE即可。如果当前页超过总页数,也表示最后一页。 * 这两种情况将重新更改当前页的页码,为最后一页编码。 * @param pageSize 每一页显示的条目数 */ public ListPage(List elements, int pageNumber, int pageSize){ super(pageNumber,pageSize,elements.size()); List subList = ((List)elements).subList(getThisPageFirstElementNumber() - 1, getThisPageLastElementNumber()); setResult(subList); } public ListPage(List elements, PageRequest p){ this(elements,p.getPageNumber(),p.getPageSize()); } }
mit
syd711/callete
callete-api/src/main/java/callete/api/services/music/streams/StreamMetaDataProvider.java
648
package callete.api.services.music.streams; /** * Implementing classes retrieve the meta data information * about a stream, such as artist, station name, track name... */ public interface StreamMetaDataProvider { /** * Returns the name of the artist that is currently played. */ String getArtist(); /** * Returns the name of the stream. */ String getName(); /** * Returns the name of the stream. */ String getTitle(); /** * Returns the URL the stream is streamed from. */ String getStreamUrl(); /** * Returns false in the case that the stream is not playable. */ boolean isAvailable(); }
mit
rebroad/multibit
src/test/java/org/multibit/store/ReplayableBlockStoreTest.java
5156
/** * Copyright 2012 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.store; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.StoredBlock; public class ReplayableBlockStoreTest { @Test public void testBasicStorage() throws Exception { File temporaryBlockStore = File.createTempFile("ReplayableBlockStore-testBasicStorage", null, null); System.out.println(temporaryBlockStore.getAbsolutePath()); temporaryBlockStore.deleteOnExit(); NetworkParameters networkParameters = NetworkParameters.unitTests(); Address toAddress1 = new ECKey().toAddress(networkParameters); Address toAddress2 = new ECKey().toAddress(networkParameters); ReplayableBlockStore store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, true); // Check the first block in a new store is the genesis block. StoredBlock genesis = store.getChainHead(); assertEquals(networkParameters.genesisBlock, genesis.getHeader()); // Build a new block. StoredBlock block1 = genesis.build(genesis.getHeader().createNextBlock(toAddress1).cloneAsHeader()); store.put(block1); store.setChainHead(block1); // Check we can get it back out again if we rebuild the store object. store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, false); StoredBlock block1reborn = store.get(block1.getHeader().getHash()); assertEquals(block1, block1reborn); // Check the chain head was stored correctly also. assertEquals(block1, store.getChainHead()); // Build another block. StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(toAddress2).cloneAsHeader()); store.put(block2); store.setChainHead(block2); // Check we can get it back out again if we rebuild the store object. store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, false); StoredBlock block2reborn = store.get(block2.getHeader().getHash()); assertEquals(block2, block2reborn); // Check the chain head was stored correctly also. assertEquals(block2, store.getChainHead()); } @Test public void testChainheadToPastTruncates() throws Exception { // this functionality is used in blockchain replay File temporaryBlockStore = File.createTempFile("ReplayableBlockStore-testReplay", null, null); System.out.println(temporaryBlockStore.getAbsolutePath()); temporaryBlockStore.deleteOnExit(); NetworkParameters networkParameters = NetworkParameters.unitTests(); Address toAddress1 = new ECKey().toAddress(networkParameters); Address toAddress2 = new ECKey().toAddress(networkParameters); ReplayableBlockStore store = new ReplayableBlockStore(networkParameters, temporaryBlockStore, true); // Check the first block in a new store is the genesis block. StoredBlock genesis = store.getChainHead(); assertEquals(networkParameters.genesisBlock, genesis.getHeader()); // Build a new block. StoredBlock block1 = genesis.build(genesis.getHeader().createNextBlock(toAddress1).cloneAsHeader()); store.put(block1); store.setChainHead(block1); // remember the size of the blockstore after adding the first block long blockSizeAfterFirstBlockAdded = temporaryBlockStore.length(); System.out.println("blockSizeAfterFirstBlockAdded = " + blockSizeAfterFirstBlockAdded); // Build another block. StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(toAddress2).cloneAsHeader()); store.put(block2); store.setChainHead(block2); long blockSizeAfterSecondBlockAdded = temporaryBlockStore.length(); System.out.println("blockSizeAfterSecondBlockAdded = " + blockSizeAfterSecondBlockAdded); store.setChainHeadAndTruncate(block1); long blockSizeAfterSetChainHeadAndTruncate = temporaryBlockStore.length(); System.out.println("blockSizeAfterSetChainHeadAndTruncate = " + blockSizeAfterSetChainHeadAndTruncate); assertEquals("setChainHeadAndTruncate did not roll back blockstore", blockSizeAfterFirstBlockAdded, blockSizeAfterSetChainHeadAndTruncate); } }
mit
ahabra/funj
src/main/java/com/tek271/funj/Transformer.java
653
package com.tek271.funj; import com.google.common.annotations.Beta; import java.util.List; import static com.google.common.collect.Lists.newArrayList; @Beta public class Transformer { private List<StepFunction> steps = newArrayList(); public static Transformer create() { return new Transformer(); } public Transformer addSteps(StepFunction... steps) { this.steps.addAll(newArrayList(steps)); return this; } @SuppressWarnings("unchecked") public <IN, OUT> List<OUT> apply(Iterable<IN> iterable) { List<?> in = newArrayList(iterable); for (StepFunction step: steps) { in = step.apply(in); } return (List<OUT>) in; } }
mit
ProjectTestificate/SrgLib
src/main/java/net/techcable/srglib/mappings/ImmutableMappings.java
7965
package net.techcable.srglib.mappings; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.UnaryOperator; import javax.annotation.Nullable; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableBiMap; import net.techcable.srglib.FieldData; import net.techcable.srglib.JavaType; import net.techcable.srglib.MethodData; import net.techcable.srglib.SrgLib; import net.techcable.srglib.utils.ImmutableMaps; import static com.google.common.base.Preconditions.*; import static java.util.Objects.*; public final class ImmutableMappings implements Mappings { private final ImmutableBiMap<JavaType, JavaType> classes; private final ImmutableBiMap<MethodData, MethodData> methods; private final ImmutableBiMap<FieldData, FieldData> fields; /* package */ static final ImmutableMappings EMPTY = new ImmutableMappings(ImmutableBiMap.of(), ImmutableBiMap.of(), ImmutableBiMap.of()); private ImmutableMappings( ImmutableBiMap<JavaType, JavaType> classes, ImmutableBiMap<MethodData, MethodData> methods, ImmutableBiMap<FieldData, FieldData> fields ) { this.classes = requireNonNull(classes, "Null types"); this.methods = requireNonNull(methods, "Null methods"); this.fields = requireNonNull(fields, "Null fields"); } @Override public JavaType getNewClass(JavaType original) { checkArgument(original.isReferenceType(), "Type isn't a reference type: %s", original); return classes.getOrDefault(requireNonNull(original), original); } @Override public MethodData getNewMethod(MethodData original) { MethodData result = methods.get(requireNonNull(original)); if (result != null) { return result; } else { return original.mapTypes(this::getNewType); } } @Override public FieldData getNewField(FieldData original) { FieldData result = fields.get(requireNonNull(original)); if (result != null) { return result; } else { return original.mapTypes(this::getNewType); } } @Override public Set<JavaType> classes() { return classes.keySet(); } @Override public Set<MethodData> methods() { return methods.keySet(); } @Override public Set<FieldData> fields() { return fields.keySet(); } @Override public ImmutableMappings snapshot() { return this; } @Nullable private ImmutableMappings inverted; @Override public ImmutableMappings inverted() { ImmutableMappings inverted = this.inverted; return inverted != null ? inverted : (this.inverted = invert0()); } private ImmutableMappings invert0() { ImmutableMappings inverted = new ImmutableMappings(this.classes.inverse(), this.methods.inverse(), this.fields.inverse()); inverted.inverted = this; return inverted; } public static ImmutableMappings copyOf( Map<JavaType, JavaType> originalClasses, Map<MethodData, String> methodNames, Map<FieldData, String> fieldNames ) { ImmutableBiMap<JavaType, JavaType> classes = ImmutableBiMap.copyOf(originalClasses); // Defensive copy to an ImmutableBiMap // No consistency check needed since we're building type-information from scratch ImmutableBiMap.Builder<MethodData, MethodData> methods = ImmutableBiMap.builder(); ImmutableBiMap.Builder<FieldData, FieldData> fields = ImmutableBiMap.builder(); methodNames.forEach((originalData, newName) -> { MethodData newData = originalData .mapTypes((oldType) -> oldType.mapClass(oldClass -> classes.getOrDefault(oldClass, oldClass))) .withName(newName); methods.put(originalData, newData); }); fieldNames.forEach((originalData, newName) -> { FieldData newData = FieldData.create( originalData.getDeclaringType().mapClass(oldClass -> classes.getOrDefault(oldClass, oldClass)), newName ); fields.put(originalData, newData); }); return new ImmutableMappings( ImmutableBiMap.copyOf(classes), methods.build(), fields.build() ); } /** * Create new ImmutableMappings with the specified data. * <p> * NOTE: {@link #copyOf(Map, Map, Map)} may be preferable, * as it automatically remaps method signatures for you. * </p> * * @param classes the class data mappings * @param methods the method data mappings * @param fields the field data mappings * @throws IllegalArgumentException if any of the types in the fields or methods don't match the type data * @return immutable mappings with the specified data */ public static ImmutableMappings create( ImmutableBiMap<JavaType, JavaType> classes, ImmutableBiMap<MethodData, MethodData> methods, ImmutableBiMap<FieldData, FieldData> fields ) { ImmutableMappings result = new ImmutableMappings(classes, methods, fields); SrgLib.checkConsistency(result); return result; } public static ImmutableMappings copyOf(Mappings other) { if (other instanceof ImmutableMappings) { return (ImmutableMappings) other; } else if (other instanceof SimpleMappings) { return other.snapshot(); } else { return create( ImmutableMaps.createBiMap(other.classes(), other::getNewType), ImmutableMaps.createBiMap(other.methods(), other::getNewMethod), ImmutableMaps.createBiMap(other.fields(), other::getNewField) ); } } @Override public void forEachClass(BiConsumer<JavaType, JavaType> action) { classes.forEach(action); } @Override public void forEachMethod(BiConsumer<MethodData, MethodData> action) { methods.forEach(action); } @Override public void forEachField(BiConsumer<FieldData, FieldData> action) { fields.forEach(action); } @Override public int hashCode() { return classes.hashCode() ^ methods.hashCode() ^ fields.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj == null) { return false; } else if (obj.getClass() == ImmutableMappings.class) { return this.classes.equals(((ImmutableMappings) obj).classes) && this.methods.equals(((ImmutableMappings) obj).methods) && this.fields.equals(((ImmutableMappings) obj).fields); } else if (obj instanceof Mappings) { return this.equals(((Mappings) obj).snapshot()); } else { return false; } } @Override public String toString() { return MoreObjects.toStringHelper(Mappings.class) .add("classes", ImmutableMaps.joinToString( classes, (original, renamed) -> String.format(" %s = %s", original.getName(), renamed.getName()), "\n", "{", "}" )) .add("methods", ImmutableMaps.joinToString( methods, (original, renamed) -> String.format(" %s = %s", original, renamed), "\n", "{\n", "\n}" )) .add("fields", ImmutableMaps.joinToString( fields, (original, renamed) -> String.format(" %s = %s", original, renamed), "\n", "{\n", "\n}" )) .toString(); } }
mit
p-ja/javabeginner2017
workshop/src/eu/sii/pl/SiiFrame.java
4015
package eu.sii.pl; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * */ public class SiiFrame extends JFrame { private JLabel loginLabel; private JTextField login; private JLabel passwordLabel; private JPasswordField password; private JButton okButton; public SiiFrame(String title) throws HeadlessException { super(title); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDimensionAndPosition(); buildContent(); } private void setDimensionAndPosition() { setMinimumSize(new Dimension(400, 200)); setLocationRelativeTo(null); } private void buildContent() { // Create components createComponents(); // Configure components configureField(login); configureField(password); // Place components placeComponents(); } private void placeComponents() { // Create panel GridBagLayout layout = new GridBagLayout(); JPanel contentPane = new JPanel(layout); contentPane.setBackground(new Color(196, 196, 255)); contentPane.setPreferredSize(new Dimension(300, 100)); // Add components contentPane.add(loginLabel); contentPane.add(login); contentPane.add(passwordLabel); contentPane.add(password); contentPane.add(okButton); GridBagConstraints c = new GridBagConstraints(); c.weightx = 1.0; c.fill = GridBagConstraints.BOTH; c.gridwidth = GridBagConstraints.RELATIVE; layout.setConstraints(loginLabel, c); layout.setConstraints(passwordLabel, c); c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 4.0; layout.setConstraints(login, c); layout.setConstraints(password, c); layout.setConstraints(okButton, c); getRootPane().setContentPane(contentPane); } private void createComponents() { // Login label loginLabel = new JLabel("Login"); // Login field login = createLoginField(); // Password label passwordLabel = new JLabel("Password"); // Password field password = new JPasswordField(); // OK button okButton = createOkButton(); } private JButton createOkButton() { JButton button = new JButton("OK"); button.setEnabled(false); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog dialog = new JDialog(SiiFrame.this, "Login Action", true); dialog.setLocationRelativeTo(SiiFrame.this); dialog.add(new Label("Hello " + login.getText())); dialog.setMinimumSize(new Dimension(300, 200)); dialog.setVisible(true); } }); return button; } private JTextField createLoginField() { JTextField field = new JTextField(); field.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { validateInput(); } @Override public void removeUpdate(DocumentEvent e) { validateInput(); } @Override public void changedUpdate(DocumentEvent e) { validateInput(); } }); return field; } private void validateInput() { if (login.getText().length() <= 0) { okButton.setEnabled(false); } else { okButton.setEnabled(true); } } private void configureField(Component field) { Dimension size = field.getSize(); size.setSize(100, size.getHeight()); field.setMinimumSize(size); } }
mit
An-Huynh/Destroy-All-Baddies
src/main/java/dab/common/entity/attributes/Direction.java
279
package dab.common.entity.attributes; /** * Enumerable for the possible directions a player will be going. * Players will either being going left, right, up, down, or even * nowhere at all. * * @author Eli Irvin */ public enum Direction { LEFT, UP, RIGHT, DOWN, NONE; }
mit
ufabdyop/coralapiserver
src/main/java/edu/utah/nanofab/coralapiserver/core/EnableRequest.java
518
package edu.utah.nanofab.coralapiserver.core; public class EnableRequest { private String item; private String member; public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getMember() { return member; } public void setMember(String member) { this.member = member; } public String getProject() { return project; } public void setProject(String project) { this.project = project; } private String project; }
mit
whaph/analysis-model
src/test/java/edu/hm/hafner/analysis/parser/LinuxKernelOutputParserTest.java
8907
package edu.hm.hafner.analysis.parser; import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.Issue; import edu.hm.hafner.analysis.Issues; import edu.hm.hafner.analysis.Priority; import static edu.hm.hafner.analysis.assertj.IssuesAssert.*; import static edu.hm.hafner.analysis.assertj.SoftAssertions.*; /** * Tests the class {@link LinuxKernelOutputParser}. * * @author Benedikt Spranger */ public class LinuxKernelOutputParserTest extends ParserTester { /** * Parse a kernel log file. */ @Test public void testWarningsParser() { Issues<Issue> warnings = new LinuxKernelOutputParser().parse(openFile()); assertThat(warnings).hasSize(26); assertSoftly(softly -> { softly.assertThat(warnings.get(0)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: RSDP 0x00000000000F68D0 000014 (v00 BOCHS )") .hasFileName("Nil"); softly.assertThat(warnings.get(1)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: RSDT 0x0000000007FE18DC 000030 (v01 BOCHS BXPCRSDT 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(2)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: FACP 0x0000000007FE17B8 000074 (v01 BOCHS BXPCFACP 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(3)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: DSDT 0x0000000007FE0040 001778 (v01 BOCHS BXPCDSDT 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(4)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: FACS 0x0000000007FE0000 000040") .hasFileName("Nil"); softly.assertThat(warnings.get(5)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: APIC 0x0000000007FE182C 000078 (v01 BOCHS BXPCAPIC 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(6)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: HPET 0x0000000007FE18A4 000038 (v01 BOCHS BXPCHPET 00000001 BXPC 00000001)") .hasFileName("Nil"); softly.assertThat(warnings.get(7)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: 1 ACPI AML tables successfully acquired and loaded") .hasFileName("Nil"); softly.assertThat(warnings.get(8)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("kworker/u2:0 (32) used greatest stack depth: 14256 bytes left") .hasFileName("Nil"); softly.assertThat(warnings.get(9)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("kworker/u2:0 (26) used greatest stack depth: 13920 bytes left") .hasFileName("Nil"); softly.assertThat(warnings.get(10)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("acpi PNP0A03:00: fail to add MMCONFIG information, can't access extended PCI configuration space under this bridge.") .hasFileName("Nil"); softly.assertThat(warnings.get(11)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: Enabled 3 GPEs in block 00 to 0F") .hasFileName("Nil"); softly.assertThat(warnings.get(12)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("ACPI: PCI Interrupt Link [LNKC] enabled at IRQ 11") .hasFileName("Nil"); softly.assertThat(warnings.get(13)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("mdev (949) used greatest stack depth: 13888 bytes left") .hasFileName("Nil"); softly.assertThat(warnings.get(14)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: WARNING") .hasFileName("Nil"); softly.assertThat(warnings.get(15)) .hasPriority(Priority.NORMAL) .hasCategory("WARNING") .hasLineStart(26) .hasLineEnd(26) .hasMessage("WARNING in kaboom_init()") .hasFileName("/home/bene/work/rtl/test-description/tmp/linux-stable-rt/drivers/misc/kaboom.c"); softly.assertThat(warnings.get(16)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: ERR") .hasFileName("Nil"); softly.assertThat(warnings.get(17)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: CRIT") .hasFileName("Nil"); softly.assertThat(warnings.get(18)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: ALERT") .hasFileName("Nil"); softly.assertThat(warnings.get(19)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("KABOOM: kaboom_init: EMERG") .hasFileName("Nil"); softly.assertThat(warnings.get(20)) .hasPriority(Priority.HIGH) .hasCategory("BUG") .hasLineStart(39) .hasLineEnd(39) .hasMessage("BUG in ()") .hasFileName("/home/bene/work/rtl/test-description/tmp/linux-stable-rt/drivers/misc/kaboom.c"); softly.assertThat(warnings.get(21)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("sysrq: SysRq : Emergency Sync") .hasFileName("Nil"); softly.assertThat(warnings.get(22)) .hasPriority(Priority.LOW) .hasCategory("Kernel Output") .hasLineStart(0) .hasLineEnd(0) .hasMessage("sysrq: SysRq : Emergency Remount R/O") .hasFileName("Nil"); }); } @Override protected String getWarningsFile() { return "kernel.log"; } }
mit
ktisha/TheRPlugin
src/com/jetbrains/ther/lexer/TheRTokenTypes.java
12305
package com.jetbrains.ther.lexer; import com.google.common.collect.ImmutableMap; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.TokenSet; import com.jetbrains.ther.psi.TheRElementType; //deprecated // DO NOT USE public class TheRTokenTypes { /* * There are five types of constants: integer, logical, numeric, complex and string. */ // integer constants public static final IElementType INTEGER_LITERAL = new TheRElementType("INTEGER_LITERAL"); // logical constants public static final IElementType TRUE_KEYWORD = new TheRElementType("TRUE_KEYWORD"); public static final IElementType FALSE_KEYWORD = new TheRElementType("FALSE_KEYWORD"); // numeric constants public static final IElementType NUMERIC_LITERAL = new TheRElementType("NUMERIC_LITERAL"); // complex constants public static final IElementType COMPLEX_LITERAL = new TheRElementType("COMPLEX_LITERAL"); // string constants public static final IElementType STRING_LITERAL = new TheRElementType("STRING_LITERAL"); /* * In addition, there are four special constants */ public static final IElementType NULL_KEYWORD = new TheRElementType("NULL_KEYWORD"); // empty object public static final IElementType INF_KEYWORD = new TheRElementType("INF_KEYWORD"); // infinity public static final IElementType NAN_KEYWORD = new TheRElementType("NAN_KEYWORD"); // not-a-number in the IEEE floating point calculus (results of the operations respectively 1/0 and 0/0, for instance). public static final IElementType NA_KEYWORD = new TheRElementType("NA_KEYWORD"); // absent (“Not Available”) data values /* The following identifiers have a special meaning and cannot be used for object names if else repeat while function for in next break TRUE FALSE NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_ ... ..1 ..2 etc. */ // keywords public static final IElementType NA_INTEGER_KEYWORD = new TheRElementType("NA_INTEGER_KEYWORD"); public static final IElementType NA_REAL_KEYWORD = new TheRElementType("NA_REAL_KEYWORD"); public static final IElementType NA_COMPLEX_KEYWORD = new TheRElementType("NA_COMPLEX_KEYWORD"); public static final IElementType NA_CHARACTER_KEYWORD = new TheRElementType("NA_CHARACTER_KEYWORD"); public static final IElementType TRIPLE_DOTS = new TheRElementType("TRIPLE_DOTS"); public static final IElementType IF_KEYWORD = new TheRElementType("IF_KEYWORD"); public static final IElementType ELSE_KEYWORD = new TheRElementType("ELSE_KEYWORD"); public static final IElementType REPEAT_KEYWORD = new TheRElementType("REPEAT_KEYWORD"); public static final IElementType WHILE_KEYWORD = new TheRElementType("WHILE_KEYWORD"); public static final IElementType FUNCTION_KEYWORD = new TheRElementType("FUNCTION_KEYWORD"); public static final IElementType FOR_KEYWORD = new TheRElementType("FOR_KEYWORD"); public static final IElementType IN_KEYWORD = new TheRElementType("IN_KEYWORD"); public static final IElementType NEXT_KEYWORD = new TheRElementType("NEXT_KEYWORD"); public static final IElementType BREAK_KEYWORD = new TheRElementType("BREAK_KEYWORD"); /* R contains a number of operators. They are listed in the table below. - Minus, can be unary or binary + Plus, can be unary or binary ! Unary not ~ Tilde, used for model formulae, can be either unary or binary ? Help : Sequence, binary (in model formulae: interaction) * Multiplication, binary / Division, binary ^ Exponentiation, binary %x% Special binary operators, x can be replaced by any valid name %% Modulus, binary %/% Integer divide, binary %*% Matrix product, binary %o% Outer product, binary %x% Kronecker product, binary %in% Matching operator, binary (in model formulae: nesting) < Less than, binary > Greater than, binary == Equal to, binary >= Greater than or equal to, binaryChapter 3: Evaluation of expressions 11 <= Less than or equal to, binary & And, binary, vectorized && And, binary, not vectorized | Or, binary, vectorized || Or, binary, not vectorized <- Left assignment, binary -> Right assignment, binary $ List subset, binary */ public static final IElementType MINUS = new TheRElementType("MINUS"); // - public static final IElementType PLUS = new TheRElementType("PLUS"); // + public static final IElementType NOT = new TheRElementType("NOT"); // ! public static final IElementType TILDE = new TheRElementType("TILDE"); // ~ public static final IElementType HELP = new TheRElementType("HELP"); // ? public static final IElementType COLON = new TheRElementType("COLON"); // : public static final IElementType MULT = new TheRElementType("MULT"); // * public static final IElementType DIV = new TheRElementType("DIV"); // / public static final IElementType EXP = new TheRElementType("EXP"); // ^ public static final IElementType MODULUS = new TheRElementType("MODULUS"); // %% public static final IElementType INT_DIV = new TheRElementType("INT_DIV"); // %/% public static final IElementType MATRIX_PROD = new TheRElementType("MATRIX_PROD"); // %*% public static final IElementType OUTER_PROD = new TheRElementType("OUTER_PROD"); // %o% public static final IElementType MATCHING = new TheRElementType("MATCHING"); // %in% public static final IElementType KRONECKER_PROD = new TheRElementType("MATCHING"); // %x% public static final IElementType INFIX_OP = new TheRElementType("INFIX_OP"); // %{character}+% public static final IElementType LT = new TheRElementType("LT"); // < public static final IElementType GT = new TheRElementType("GT"); // > public static final IElementType EQEQ = new TheRElementType("EQEQ"); // == public static final IElementType GE = new TheRElementType("GE"); // >= public static final IElementType LE = new TheRElementType("LE"); // <= public static final IElementType AND = new TheRElementType("AND"); // & public static final IElementType ANDAND = new TheRElementType("ANDAND"); // && public static final IElementType OR = new TheRElementType("OR"); // | public static final IElementType OROR = new TheRElementType("OROR"); // || public static final IElementType LEFT_ASSIGN = new TheRElementType("LEFT_ASSIGN"); // <- public static final IElementType RIGHT_ASSIGN = new TheRElementType("RIGHT_ASSIGN"); // -> public static final IElementType LIST_SUBSET = new TheRElementType("LIST_SUBSET"); // $ public static final IElementType TICK = new TheRElementType("TICK"); // ` public static final IElementType AT = new TheRElementType("AT"); // @ public static final IElementType DOUBLECOLON = new TheRElementType("DOUBLECOLON"); // :: public static final IElementType TRIPLECOLON = new TheRElementType("TRIPLECOLON"); // ::: public static final IElementType NOTEQ = new TheRElementType("NOTEQ"); // != public static final IElementType RIGHT_COMPLEX_ASSING = new TheRElementType("RIGHT_COMPLEX_ASSING"); // ->> public static final IElementType LEFT_COMPLEX_ASSING = new TheRElementType("LEFT_COMPLEX_ASSING"); // <<- public static final IElementType LPAR = new TheRElementType("LPAR"); // ( public static final IElementType RPAR = new TheRElementType("RPAR"); // ) public static final IElementType LBRACKET = new TheRElementType("LBRACKET"); // [ public static final IElementType LDBRACKET = new TheRElementType("LDBRACKET"); // [[ public static final IElementType RBRACKET = new TheRElementType("RBRACKET"); // ] public static final IElementType RDBRACKET = new TheRElementType("RDBRACKET"); // ]] public static final IElementType LBRACE = new TheRElementType("LBRACE"); // { public static final IElementType RBRACE = new TheRElementType("RBRACE"); // } public static final IElementType COMMA = new TheRElementType("COMMA"); // , public static final IElementType DOT = new TheRElementType("DOT"); // . public static final IElementType EQ = new TheRElementType("EQ"); // = public static final IElementType SEMICOLON = new TheRElementType("SEMICOLON"); // ; public static final IElementType UNDERSCORE = new TheRElementType("UNDERSCORE"); // _ public static final IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER; public static final IElementType IDENTIFIER = new TheRElementType("IDENTIFIER"); public static final IElementType LINE_BREAK = new TheRElementType("LINE_BREAK"); public static final IElementType SPACE = new TheRElementType("SPACE"); public static final IElementType TAB = new TheRElementType("TAB"); public static final IElementType FORMFEED = new TheRElementType("FORMFEED"); public static final IElementType END_OF_LINE_COMMENT = new TheRElementType("END_OF_LINE_COMMENT"); public static final TokenSet RESERVED_WORDS = TokenSet .create(IF_KEYWORD, ELSE_KEYWORD, REPEAT_KEYWORD, WHILE_KEYWORD, FUNCTION_KEYWORD, FOR_KEYWORD, IN_KEYWORD, NEXT_KEYWORD, BREAK_KEYWORD); public static final TokenSet ASSIGNMENTS = TokenSet.create(LEFT_ASSIGN, LEFT_COMPLEX_ASSING, RIGHT_ASSIGN, RIGHT_COMPLEX_ASSING, EQ); public static final TokenSet LEFT_ASSIGNMENTS = TokenSet.create(LEFT_ASSIGN, LEFT_COMPLEX_ASSING, EQ); public static final TokenSet RIGHT_ASSIGNMENTS = TokenSet.create(RIGHT_ASSIGN, RIGHT_COMPLEX_ASSING); public static final TokenSet OPERATORS = TokenSet .create(MINUS, PLUS, NOT, TILDE, HELP, COLON, MULT, DIV, EXP, MODULUS, INT_DIV, MATRIX_PROD, OUTER_PROD, MATCHING, KRONECKER_PROD, INFIX_OP, LT, GT, EQEQ, GE, LE, AND, ANDAND, OR, OROR, LEFT_ASSIGN, RIGHT_ASSIGN, LIST_SUBSET, AT, TICK); public static final TokenSet KEYWORDS = TokenSet.create(NA_INTEGER_KEYWORD, NA_REAL_KEYWORD, NA_COMPLEX_KEYWORD, NA_CHARACTER_KEYWORD, TRIPLE_DOTS, IF_KEYWORD, ELSE_KEYWORD, REPEAT_KEYWORD, WHILE_KEYWORD, FUNCTION_KEYWORD, FOR_KEYWORD, IN_KEYWORD, NEXT_KEYWORD, BREAK_KEYWORD); public static final TokenSet STATEMENT_START_TOKENS = TokenSet.create(IF_KEYWORD, WHILE_KEYWORD, FOR_KEYWORD, REPEAT_KEYWORD, BREAK_KEYWORD, NEXT_KEYWORD, LBRACE, FUNCTION_KEYWORD, HELP); public static final TokenSet COMPARISON_OPERATIONS = TokenSet.create(LT, GT, EQEQ, GE, LE, NOTEQ, MATCHING); public static final TokenSet NA_KEYWORDS = TokenSet.create(NA_KEYWORD, NA_CHARACTER_KEYWORD, NA_COMPLEX_KEYWORD, NA_INTEGER_KEYWORD, NA_REAL_KEYWORD); public static final TokenSet ADDITIVE_OPERATIONS = TokenSet.create(PLUS, MINUS); public static final TokenSet MULTIPLICATIVE_OPERATIONS = TokenSet.create(MULT, DIV, INT_DIV, MATRIX_PROD, KRONECKER_PROD, OUTER_PROD); public static final TokenSet POWER_OPERATIONS = TokenSet.create(EXP, MODULUS); public static final TokenSet UNARY_OPERATIONS = TokenSet.create(PLUS, MINUS, TILDE, NOT); public static final TokenSet EQUALITY_OPERATIONS = TokenSet.create(EQEQ, NOTEQ); public static final TokenSet OR_OPERATIONS = TokenSet.create(OR, OROR); public static final TokenSet AND_OPERATIONS = TokenSet.create(AND, ANDAND); public static final TokenSet SPECIAL_CONSTANTS = TokenSet.create(NA_KEYWORD, NAN_KEYWORD, INF_KEYWORD, NULL_KEYWORD, TRUE_KEYWORD, FALSE_KEYWORD); public static final TokenSet WHITESPACE_OR_LINEBREAK = TokenSet.create(SPACE, TAB, FORMFEED, LINE_BREAK); public static final TokenSet WHITESPACE = TokenSet.create(SPACE, TAB, FORMFEED); public static final TokenSet OPEN_BRACES = TokenSet.create(LBRACKET, LDBRACKET, LBRACE, LPAR); public static final TokenSet CLOSE_BRACES = TokenSet.create(RBRACKET, RDBRACKET, RBRACE, RPAR); public static final TokenSet OPEN_BRACKETS = TokenSet.create(LBRACKET, LDBRACKET); public static final ImmutableMap<IElementType, IElementType> BRACKER_PAIRS = ImmutableMap.<IElementType, IElementType>builder().put(LBRACKET, RBRACKET).put(LDBRACKET, RDBRACKET).build(); public static final TokenSet NAMESPACE_ACCESS = TokenSet.create(DOUBLECOLON, TRIPLECOLON); }
mit
abeatte/launchpad
src/main/java/com/artbeatte/launchpad/LaunchpadConfiguration.java
1603
package com.artbeatte.launchpad; import com.google.common.collect.ImmutableMap; import io.dropwizard.Configuration; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.db.DataSourceFactory; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.Map; /** * @author art.beatte * @version 7/14/15 */ public class LaunchpadConfiguration extends Configuration { @Valid @NotNull private DataSourceFactory database = new DataSourceFactory(); @NotNull private Map<String, Map<String, String>> viewRendererConfiguration = Collections.emptyMap(); @JsonProperty("database") public DataSourceFactory getDataSourceFactory() { return database; } @JsonProperty("database") public void setDataSourceFactory(DataSourceFactory dataSourceFactory) { this.database = dataSourceFactory; } @JsonProperty("viewRendererConfiguration") public Map<String, Map<String, String>> getViewRendererConfiguration() { return viewRendererConfiguration; } @JsonProperty("viewRendererConfiguration") public void setViewRendererConfiguration(Map<String, Map<String, String>> viewRendererConfiguration) { ImmutableMap.Builder<String, Map<String, String>> builder = ImmutableMap.builder(); for (Map.Entry<String, Map<String, String>> entry : viewRendererConfiguration.entrySet()) { builder.put(entry.getKey(), ImmutableMap.copyOf(entry.getValue())); } this.viewRendererConfiguration = builder.build(); } }
mit
edwardinubuntu/PetBook
PetLove/src/main/java/com/edinubuntu/petlove/fragment/MarketSuggestionFragment.java
6305
package com.edinubuntu.petlove.fragment; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.actionbarsherlock.app.SherlockFragment; import com.activeandroid.query.Select; import com.edinubuntu.petlove.PetLove; import com.edinubuntu.petlove.R; import com.edinubuntu.petlove.adapter.MarketSuggestionsPagerAdapter; import com.edinubuntu.petlove.object.Event; import com.edinubuntu.petlove.object.Pet; import com.edinubuntu.petlove.object.Record; import com.edinubuntu.petlove.object.User; import com.edinubuntu.petlove.util.manager.DisplayTextManager; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Created by edward_chiang on 13/10/4. */ public class MarketSuggestionFragment extends SherlockFragment { private List<Record> recordList; private Map<String, String> queryMap; private ViewPager suggestionsViewPager; private MarketSuggestionsPagerAdapter marketSuggestionsPagerAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_market_suggestion, container, false); suggestionsViewPager = (ViewPager)rootView.findViewById(R.id.market_record_content_pager); marketSuggestionsPagerAdapter = new MarketSuggestionsPagerAdapter(getFragmentManager()); suggestionsViewPager.setAdapter(marketSuggestionsPagerAdapter); Button choicePetButton = (Button)rootView.findViewById(R.id.market_record_pick_button); choicePetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getSherlockActivity()) .setTitle(getSherlockActivity().getString(R.string.market_suggestion_choice_title)) .setMessage(getSherlockActivity().getString(R.string.market_suggestion_choice_message)) .setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Record currentRecord = recordList.get(suggestionsViewPager.getCurrentItem()); // Save record to pet Pet adaptPet = new Pet(); adaptPet.setName(currentRecord.getName()); adaptPet.setProfile(currentRecord); // Get Current Player Profile User currentPlayer = new Select().from(User.class).where("Type = '" + User.Type.PLAYER + "'").executeSingle(); adaptPet.setOwner(currentPlayer); adaptPet.save(); Event adaptEvent = new Event(Event.Action.PET_ADAPT_SUCCESS); adaptEvent.setMessage(getString(R.string.event_message_pet_name_begin) + adaptPet.getName() + getString(R.string.event_message_pet_name_end) ); adaptEvent.save(); // Finish and back getSherlockActivity().setResult(Activity.RESULT_OK, new Intent()); getSherlockActivity().finish(); } }) .setNegativeButton(getString(R.string.dialog_no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } }); return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); new Event(Event.Action.VISIT_MARKET_SUGGESTIONS).save(); StringBuffer whereBuffer = new StringBuffer(); if (queryMap != null) { Iterator it = queryMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); whereBuffer.append(pairs.getKey() + "= '"+pairs.getValue()+"'"); if (it.hasNext()) { whereBuffer.append(" and "); } } recordList = new Select().from(Record.class) .where(whereBuffer.toString()) .orderBy("RANDOM()") .limit(10) .execute(); Log.d(PetLove.TAG, "Number suggest :" + recordList.size()); Log.d(PetLove.TAG, "We suggest :" + recordList.toString()); marketSuggestionsPagerAdapter.setRecords(recordList); marketSuggestionsPagerAdapter.notifyDataSetChanged(); new AlertDialog.Builder(getSherlockActivity()) .setTitle(getString(R.string.alert_suit_title) + DisplayTextManager.newInstance(getSherlockActivity()).getType(queryMap.get("Type"))) .setMessage(getString(R.string.alert_suit_message_1) + recordList.size() + getString(R.string.alert_suit_message_2)) .setPositiveButton(getString(R.string.dialog_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } } public void setQueryMap(Map<String, String> queryMap) { this.queryMap = queryMap; } }
mit
bing-ads-sdk/BingAds-Java-SDK
src/test/java/com/microsoft/bingads/v12/api/test/entities/criterions/adgroup/profile/BulkAdGroupProfileCriterionWriteTests.java
691
package com.microsoft.bingads.v12.api.test.entities.criterions.adgroup.profile; import org.junit.runner.RunWith; import org.junit.runners.Suite; import com.microsoft.bingads.v12.api.test.entities.criterions.adgroup.profile.write.*; @RunWith(Suite.class) @Suite.SuiteClasses({ BulkAdGroupCompanyNameCriterionWriteProfileIdTest.class, BulkAdGroupCompanyNameCriterionWriteProfileTest.class, BulkAdGroupIndustryCriterionWriteProfileIdTest.class, BulkAdGroupIndustryCriterionWriteProfileTest.class, BulkAdGroupJobFunctionCriterionWriteProfileIdTest.class, BulkAdGroupJobFunctionCriterionWriteProfileTest.class, }) public class BulkAdGroupProfileCriterionWriteTests { }
mit
Samuel-Oliveira/Java_CTe
src/main/java/br/com/swconsultoria/cte/schema_300/evPrestDesacordo/TUFSemEX.java
2329
// // Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802 // Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem. // Gerado em: 2019.09.22 às 07:50:03 PM BRT // package br.com.swconsultoria.cte.schema_300.evPrestDesacordo; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Classe Java de TUF_sem_EX. * * <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe. * <p> * <pre> * &lt;simpleType name="TUF_sem_EX"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;whiteSpace value="preserve"/> * &lt;enumeration value="AC"/> * &lt;enumeration value="AL"/> * &lt;enumeration value="AM"/> * &lt;enumeration value="AP"/> * &lt;enumeration value="BA"/> * &lt;enumeration value="CE"/> * &lt;enumeration value="DF"/> * &lt;enumeration value="ES"/> * &lt;enumeration value="GO"/> * &lt;enumeration value="MA"/> * &lt;enumeration value="MG"/> * &lt;enumeration value="MS"/> * &lt;enumeration value="MT"/> * &lt;enumeration value="PA"/> * &lt;enumeration value="PB"/> * &lt;enumeration value="PE"/> * &lt;enumeration value="PI"/> * &lt;enumeration value="PR"/> * &lt;enumeration value="RJ"/> * &lt;enumeration value="RN"/> * &lt;enumeration value="RO"/> * &lt;enumeration value="RR"/> * &lt;enumeration value="RS"/> * &lt;enumeration value="SC"/> * &lt;enumeration value="SE"/> * &lt;enumeration value="SP"/> * &lt;enumeration value="TO"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "TUF_sem_EX", namespace = "http://www.portalfiscal.inf.br/cte") @XmlEnum public enum TUFSemEX { AC, AL, AM, AP, BA, CE, DF, ES, GO, MA, MG, MS, MT, PA, PB, PE, PI, PR, RJ, RN, RO, RR, RS, SC, SE, SP, TO; public String value() { return name(); } public static TUFSemEX fromValue(String v) { return valueOf(v); } }
mit
rudidudi/Trusis
src/trusis/config/personaggi/Trusis.java
1137
package trusis.config.personaggi; import java.util.ArrayList; import java.util.List; import trusis.config.personaggi.define.Personaggio; import trusis.config.personaggi.define.stdPersonaggio; import trusis.config.poteri.UccisioneNotturna; import trusis.config.poteri.define.Potere; public class Trusis extends stdPersonaggio { private String nome="Trusis"; private String fazione="Cattivi"; private boolean vivo=true; private boolean killable=true; private List<Personaggio> conoscenti = new ArrayList<Personaggio>(); public Trusis(List<Potere> listPoteri) { setPoteri(listPoteri); } public Trusis() { UccisioneNotturna uccisioneNotturna = new UccisioneNotturna(); List<Potere> poteriTrusis = new ArrayList<Potere>(); poteriTrusis.add(uccisioneNotturna); setter(poteriTrusis); } private void setter(List<Potere> poteri) { setNome(nome); setFazione(fazione); setVivo(vivo); setKillable(killable); setPoteri(poteri); setConoscenti(conoscenti); } }
mit
elucent/ModTweaker
src/main/java/modtweaker/mods/botania/handlers/Apothecary.java
3285
package modtweaker.mods.botania.handlers; import minetweaker.MineTweakerAPI; import minetweaker.api.item.IIngredient; import minetweaker.api.item.IItemStack; import com.blamejared.mtlib.helpers.LogHelper; import com.blamejared.mtlib.utils.BaseListAddition; import com.blamejared.mtlib.utils.BaseListRemoval; import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; import vazkii.botania.api.BotaniaAPI; import vazkii.botania.api.recipe.RecipePetals; import vazkii.botania.common.item.block.ItemBlockSpecialFlower; import java.util.LinkedList; import java.util.List; import static com.blamejared.mtlib.helpers.InputHelper.toObjects; import static com.blamejared.mtlib.helpers.InputHelper.toStack; import static com.blamejared.mtlib.helpers.InputHelper.*; import static com.blamejared.mtlib.helpers.StackHelper.matches; @ZenClass("mods.botania.Apothecary") public class Apothecary { protected static final String name = "Botania Petal"; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @ZenMethod public static void addRecipe(IItemStack output, IIngredient[] input) { MineTweakerAPI.apply(new Add(new RecipePetals(toStack(output), toObjects(input)))); } @ZenMethod public static void addRecipe(String output, IIngredient[] input) { addRecipe(toIItemStack(ItemBlockSpecialFlower.ofType(output)), input); } private static class Add extends BaseListAddition<RecipePetals> { public Add(RecipePetals recipe) { super("Botania Petal", BotaniaAPI.petalRecipes); recipes.add(recipe); } @Override public String getRecipeInfo(RecipePetals recipe) { return LogHelper.getStackDescription(recipe.getOutput()); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @ZenMethod public static void removeRecipe(IIngredient output) { // Get list of existing recipes, matching with parameter LinkedList<RecipePetals> result = new LinkedList<>(); for(RecipePetals entry : BotaniaAPI.petalRecipes) { if(entry != null && entry.getOutput() != null && matches(output, toIItemStack(entry.getOutput()))) { result.add(entry); } } // Check if we found the recipes and apply the action if(!result.isEmpty()) { MineTweakerAPI.apply(new Remove(result)); } else { LogHelper.logWarning(String.format("No %s Recipe found for %s. Command ignored!", Apothecary.name, output.toString())); } } @ZenMethod public static void removeRecipe(String output) { removeRecipe(toIItemStack(ItemBlockSpecialFlower.ofType(output))); } private static class Remove extends BaseListRemoval<RecipePetals> { public Remove(List<RecipePetals> recipes) { super(Apothecary.name, BotaniaAPI.petalRecipes, recipes); } @Override public String getRecipeInfo(RecipePetals recipe) { return LogHelper.getStackDescription(recipe.getOutput()); } } }
mit
TeamRedFox/PointOfSale
src/database_comm/DatabaseConnection.java
2148
package database_comm; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.sun.scenario.Settings; import config.ProgramSettings; public class DatabaseConnection { static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; static final String USER = "sa"; static final String PASS = "brianbrian"; //Debug localhost string //static final String connectionUrl = "jdbc:sqlserver://150.250.147.167:1433;DatabaseName=REDFOX;user=sa;password=brianbrian;"; //Debug online string //String connectionUrl = "jdbc:sqlserver://rbmsdemo.dyndns.org:1433;DatabaseName=REDFOX;user=brian;password=brianbrian;"; private Connection connection; private Statement statement; public DatabaseConnection() throws SQLException { try { //I don't know what this line really does //No touch Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Connecting to database..."); connection = DriverManager.getConnection(getConnectionUrl()); statement = connection.createStatement(); } private String getConnectionUrl() { return "jdbc:sqlserver://" + ProgramSettings.getProperty("database_server_name") + ":" + ProgramSettings.getProperty("database_port") + ";DatabaseName=" + ProgramSettings.getProperty("database_name") + ";user=" + ProgramSettings.getProperty("database_username") + ";password=" + ProgramSettings.getProperty("database_password") + ";"; //String s = "jdbc:sqlserver://rbmsdemo.dyndns.org:1433;DatabaseName=REDFOX;user=brian;password=brianbrian;"; } //Executes and returns results from a given query public ResultSet executeQuery(String query) throws SQLException { return statement.executeQuery(query); } //Executes a SQL statement, returns true it successful public boolean execute(String sql) throws SQLException { return statement.execute(sql); } //Close all connections in this object public void close() throws SQLException { statement.close(); connection.close(); } }
mit
badoualy/kotlogram
tl/src/main/java/com/github/badoualy/telegram/tl/api/request/TLRequestMessagesAddChatUser.java
3599
package com.github.badoualy.telegram.tl.api.request; import com.github.badoualy.telegram.tl.TLContext; import com.github.badoualy.telegram.tl.api.TLAbsInputUser; import com.github.badoualy.telegram.tl.api.TLAbsUpdates; import com.github.badoualy.telegram.tl.core.TLMethod; import com.github.badoualy.telegram.tl.core.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.github.badoualy.telegram.tl.StreamUtils.readInt; import static com.github.badoualy.telegram.tl.StreamUtils.readTLObject; import static com.github.badoualy.telegram.tl.StreamUtils.writeInt; import static com.github.badoualy.telegram.tl.StreamUtils.writeTLObject; import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID; import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32; /** * @author Yannick Badoual yann.badoual@gmail.com * @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a> */ public class TLRequestMessagesAddChatUser extends TLMethod<TLAbsUpdates> { public static final int CONSTRUCTOR_ID = 0xf9a0aa09; protected int chatId; protected TLAbsInputUser userId; protected int fwdLimit; private final String _constructor = "messages.addChatUser#f9a0aa09"; public TLRequestMessagesAddChatUser() { } public TLRequestMessagesAddChatUser(int chatId, TLAbsInputUser userId, int fwdLimit) { this.chatId = chatId; this.userId = userId; this.fwdLimit = fwdLimit; } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public TLAbsUpdates deserializeResponse(InputStream stream, TLContext context) throws IOException { final TLObject response = readTLObject(stream, context); if (response == null) { throw new IOException("Unable to parse response"); } if (!(response instanceof TLAbsUpdates)) { throw new IOException( "Incorrect response type, expected " + getClass().getCanonicalName() + ", found " + response .getClass().getCanonicalName()); } return (TLAbsUpdates) response; } @Override public void serializeBody(OutputStream stream) throws IOException { writeInt(chatId, stream); writeTLObject(userId, stream); writeInt(fwdLimit, stream); } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public void deserializeBody(InputStream stream, TLContext context) throws IOException { chatId = readInt(stream); userId = readTLObject(stream, context, TLAbsInputUser.class, -1); fwdLimit = readInt(stream); } @Override public int computeSerializedSize() { int size = SIZE_CONSTRUCTOR_ID; size += SIZE_INT32; size += userId.computeSerializedSize(); size += SIZE_INT32; return size; } @Override public String toString() { return _constructor; } @Override public int getConstructorId() { return CONSTRUCTOR_ID; } public int getChatId() { return chatId; } public void setChatId(int chatId) { this.chatId = chatId; } public TLAbsInputUser getUserId() { return userId; } public void setUserId(TLAbsInputUser userId) { this.userId = userId; } public int getFwdLimit() { return fwdLimit; } public void setFwdLimit(int fwdLimit) { this.fwdLimit = fwdLimit; } }
mit
anphetamina/GG-well-trade
app/proguard5.3.1/src/proguard/GPL.java
6530
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2016 Eric Lafortune @ GuardSquare * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard; import java.io.*; import java.util.*; /** * This class checks and prints out information about the GPL. * * @author Eric Lafortune */ public class GPL { /** * Prints out a note about the GPL if ProGuard is linked against unknown * code. */ public static void check() { ByteArrayOutputStream out = new ByteArrayOutputStream(); new Exception().printStackTrace(new PrintStream(out)); LineNumberReader reader = new LineNumberReader( new InputStreamReader( new ByteArrayInputStream(out.toByteArray()))); Set unknownPackageNames = unknownPackageNames(reader); if (unknownPackageNames.size() > 0) { String uniquePackageNames = uniquePackageNames(unknownPackageNames); System.out.println("ProGuard is released under the GNU General Public License. You therefore"); System.out.println("must ensure that programs that link to it ("+uniquePackageNames+"...)"); System.out.println("carry the GNU General Public License as well. Alternatively, you can"); System.out.println("apply for an exception with the author of ProGuard."); } } /** * Returns a set of package names from the given stack trace. */ private static Set unknownPackageNames(LineNumberReader reader) { Set packageNames = new HashSet(); try { while (true) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith("at ")) { line = line.substring(2).trim(); line = trimSuffix(line, '('); line = trimSuffix(line, '.'); line = trimSuffix(line, '.'); if (line.length() > 0 && !isKnown(line)) { packageNames.add(line); } } } } catch (IOException ex) { // We'll just stop looking for more names. } return packageNames; } /** * Returns a comma-separated list of package names from the set, excluding * any subpackages of packages in the set. */ private static String uniquePackageNames(Set packageNames) { StringBuffer buffer = new StringBuffer(); Iterator iterator = packageNames.iterator(); while (iterator.hasNext()) { String packageName = (String)iterator.next(); if (!containsPrefix(packageNames, packageName)) { buffer.append(packageName).append(", "); } } return buffer.toString(); } /** * Returns a given string without the suffix, as defined by the given * separator. */ private static String trimSuffix(String string, char separator) { int index = string.lastIndexOf(separator); return index < 0 ? "" : string.substring(0, index); } /** * Returns whether the given set contains a prefix of the given name. */ private static boolean containsPrefix(Set set, String name) { int index = 0; while (!set.contains(name.substring(0, index))) { index = name.indexOf('.', index + 1); if (index < 0) { return false; } } return true; } /** * Returns whether the given package name has been granted an exception * against the GPL linking clause, by the copyright holder of ProGuard. * This method is not legally binding, but of course the actual license is. * Please contact the copyright holder if you would like an exception for * your code as well. */ private static boolean isKnown(String packageName) { return packageName.startsWith("java") || packageName.startsWith("sun.reflect") || packageName.startsWith("proguard") || packageName.startsWith("org.apache.tools.ant") || packageName.startsWith("org.apache.tools.maven") || packageName.startsWith("org.gradle") || packageName.startsWith("org.codehaus.groovy") || packageName.startsWith("org.eclipse") || packageName.startsWith("org.netbeans") || packageName.startsWith("com.android") || packageName.startsWith("com.sun.kvem") || packageName.startsWith("net.certiv.proguarddt") || packageName.startsWith("groovy") || packageName.startsWith("scala") || packageName.startsWith("sbt") || packageName.startsWith("xsbt") || packageName.startsWith("eclipseme"); } public static void main(String[] args) { LineNumberReader reader = new LineNumberReader( new InputStreamReader(System.in)); Set unknownPackageNames = unknownPackageNames(reader); if (unknownPackageNames.size() > 0) { String uniquePackageNames = uniquePackageNames(unknownPackageNames); System.out.println(uniquePackageNames); } } }
mit
carlvine500/jedis
src/main/java/redis/clients/jedis/BinaryJedis.java
126814
package redis.clients.jedis; import static redis.clients.jedis.Protocol.toByteArray; import java.io.Closeable; import java.net.URI; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import redis.clients.jedis.BinaryClient.LIST_POSITION; import redis.clients.jedis.commands.*; import redis.clients.jedis.exceptions.InvalidURIException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.params.set.SetParams; import redis.clients.jedis.params.sortedset.ZAddParams; import redis.clients.jedis.params.sortedset.ZIncrByParams; import redis.clients.util.JedisByteHashMap; import redis.clients.util.JedisURIHelper; import redis.clients.util.SafeEncoder; public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands, AdvancedBinaryJedisCommands, BinaryScriptingCommands, Closeable { protected Client client = null; protected Transaction transaction = null; protected Pipeline pipeline = null; public BinaryJedis() { client = new Client(); } public BinaryJedis(final String host) { URI uri = URI.create(host); if (uri.getScheme() != null && uri.getScheme().equals("redis")) { initializeClientFromURI(uri); } else { client = new Client(host); } } public BinaryJedis(final String host, final int port) { client = new Client(host, port); } public BinaryJedis(final String host, final int port, final int timeout) { client = new Client(host, port); client.setConnectionTimeout(timeout); client.setSoTimeout(timeout); } public BinaryJedis(final String host, final int port, final int connectionTimeout, final int soTimeout) { client = new Client(host, port); client.setConnectionTimeout(connectionTimeout); client.setSoTimeout(soTimeout); } public BinaryJedis(final JedisShardInfo shardInfo) { client = new Client(shardInfo.getHost(), shardInfo.getPort()); client.setConnectionTimeout(shardInfo.getConnectionTimeout()); client.setSoTimeout(shardInfo.getSoTimeout()); client.setPassword(shardInfo.getPassword()); client.setDb(shardInfo.getDb()); } public BinaryJedis(URI uri) { initializeClientFromURI(uri); } public BinaryJedis(final URI uri, final int timeout) { initializeClientFromURI(uri); client.setConnectionTimeout(timeout); client.setSoTimeout(timeout); } public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout) { initializeClientFromURI(uri); client.setConnectionTimeout(connectionTimeout); client.setSoTimeout(soTimeout); } private void initializeClientFromURI(URI uri) { if (!JedisURIHelper.isValid(uri)) { throw new InvalidURIException(String.format( "Cannot open Redis connection due invalid URI. %s", uri.toString())); } client = new Client(uri.getHost(), uri.getPort()); String password = JedisURIHelper.getPassword(uri); if (password != null) { client.auth(password); client.getStatusCodeReply(); } int dbIndex = JedisURIHelper.getDBIndex(uri); if (dbIndex > 0) { client.select(dbIndex); client.getStatusCodeReply(); client.setDb(dbIndex); } } @Override public String ping() { checkIsInMultiOrPipeline(); client.ping(); return client.getStatusCodeReply(); } /** * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 * GB). * <p> * Time complexity: O(1) * @param key * @param value * @return Status code reply */ @Override public String set(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); client.set(key, value); return client.getStatusCodeReply(); } /** * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 * GB). * @param key * @param value * @param params * @return Status code reply */ public String set(final byte[] key, final byte[] value, final SetParams params) { checkIsInMultiOrPipeline(); client.set(key, value, params); return client.getStatusCodeReply(); } /** * Get the value of the specified key. If the key does not exist the special value 'nil' is * returned. If the value stored at key is not a string an error is returned because GET can only * handle string values. * <p> * Time complexity: O(1) * @param key * @return Bulk reply */ @Override public byte[] get(final byte[] key) { checkIsInMultiOrPipeline(); client.get(key); return client.getBinaryBulkReply(); } /** * Ask the server to silently close the connection. */ @Override public String quit() { checkIsInMultiOrPipeline(); client.quit(); String quitReturn = client.getStatusCodeReply(); client.disconnect(); return quitReturn; } /** * Test if the specified keys exist. The command returns the number of keys existed Time * complexity: O(N) * @param keys * @return Integer reply, specifically: an integer greater than 0 if one or more keys existed 0 if * none of the specified keys existed */ public Long exists(final byte[]... keys) { checkIsInMultiOrPipeline(); client.exists(keys); return client.getIntegerReply(); } /** * Test if the specified key exists. The command returns "1" if the key exists, otherwise "0" is * returned. Note that even keys set with an empty string as value will return "1". Time * complexity: O(1) * @param key * @return Boolean reply, true if the key exists, otherwise false */ @Override public Boolean exists(final byte[] key) { checkIsInMultiOrPipeline(); client.exists(key); return client.getIntegerReply() == 1; } /** * Remove the specified keys. If a given key does not exist no operation is performed for this * key. The command returns the number of keys removed. Time complexity: O(1) * @param keys * @return Integer reply, specifically: an integer greater than 0 if one or more keys were removed * 0 if none of the specified key existed */ @Override public Long del(final byte[]... keys) { checkIsInMultiOrPipeline(); client.del(keys); return client.getIntegerReply(); } @Override public Long del(final byte[] key) { checkIsInMultiOrPipeline(); client.del(key); return client.getIntegerReply(); } /** * Return the type of the value stored at key in form of a string. The type can be one of "none", * "string", "list", "set". "none" is returned if the key does not exist. Time complexity: O(1) * @param key * @return Status code reply, specifically: "none" if the key does not exist "string" if the key * contains a String value "list" if the key contains a List value "set" if the key * contains a Set value "zset" if the key contains a Sorted Set value "hash" if the key * contains a Hash value */ @Override public String type(final byte[] key) { checkIsInMultiOrPipeline(); client.type(key); return client.getStatusCodeReply(); } /** * Delete all the keys of the currently selected DB. This command never fails. * @return Status code reply */ @Override public String flushDB() { checkIsInMultiOrPipeline(); client.flushDB(); return client.getStatusCodeReply(); } /** * Returns all the keys matching the glob-style pattern as space separated strings. For example if * you have in the database the keys "foo" and "foobar" the command "KEYS foo*" will return * "foo foobar". * <p> * Note that while the time complexity for this operation is O(n) the constant times are pretty * low. For example Redis running on an entry level laptop can scan a 1 million keys database in * 40 milliseconds. <b>Still it's better to consider this one of the slow commands that may ruin * the DB performance if not used with care.</b> * <p> * In other words this command is intended only for debugging and special operations like creating * a script to change the DB schema. Don't use it in your normal code. Use Redis Sets in order to * group together a subset of objects. * <p> * Glob style patterns examples: * <ul> * <li>h?llo will match hello hallo hhllo * <li>h*llo will match hllo heeeello * <li>h[ae]llo will match hello and hallo, but not hillo * </ul> * <p> * Use \ to escape special chars if you want to match them verbatim. * <p> * Time complexity: O(n) (with n being the number of keys in the DB, and assuming keys and pattern * of limited length) * @param pattern * @return Multi bulk reply */ @Override public Set<byte[]> keys(final byte[] pattern) { checkIsInMultiOrPipeline(); client.keys(pattern); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Return a randomly selected key from the currently selected DB. * <p> * Time complexity: O(1) * @return Singe line reply, specifically the randomly selected key or an empty string is the * database is empty */ @Override public byte[] randomBinaryKey() { checkIsInMultiOrPipeline(); client.randomKey(); return client.getBinaryBulkReply(); } /** * Atomically renames the key oldkey to newkey. If the source and destination name are the same an * error is returned. If newkey already exists it is overwritten. * <p> * Time complexity: O(1) * @param oldkey * @param newkey * @return Status code repy */ @Override public String rename(final byte[] oldkey, final byte[] newkey) { checkIsInMultiOrPipeline(); client.rename(oldkey, newkey); return client.getStatusCodeReply(); } /** * Rename oldkey into newkey but fails if the destination key newkey already exists. * <p> * Time complexity: O(1) * @param oldkey * @param newkey * @return Integer reply, specifically: 1 if the key was renamed 0 if the target key already exist */ @Override public Long renamenx(final byte[] oldkey, final byte[] newkey) { checkIsInMultiOrPipeline(); client.renamenx(oldkey, newkey); return client.getIntegerReply(); } /** * Return the number of keys in the currently selected database. * @return Integer reply */ @Override public Long dbSize() { checkIsInMultiOrPipeline(); client.dbSize(); return client.getIntegerReply(); } /** * Set a timeout on the specified key. After the timeout the key will be automatically deleted by * the server. A key with an associated timeout is said to be volatile in Redis terminology. * <p> * Voltile keys are stored on disk like the other keys, the timeout is persistent too like all the * other aspects of the dataset. Saving a dataset containing expires and stopping the server does * not stop the flow of time as Redis stores on disk the time when the key will no longer be * available as Unix time, and not the remaining seconds. * <p> * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire * set. It is also possible to undo the expire at all turning the key into a normal key using the * {@link #persist(byte[]) PERSIST} command. * <p> * Time complexity: O(1) * @see <a href="http://redis.io/commands/expire">Expire Command</a> * @param key * @param seconds * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since * the key already has an associated timeout (this may happen only in Redis versions &lt; * 2.1.3, Redis &gt;= 2.1.3 will happily update the timeout), or the key does not exist. */ @Override public Long expire(final byte[] key, final int seconds) { checkIsInMultiOrPipeline(); client.expire(key, seconds); return client.getIntegerReply(); } /** * EXPIREAT works exctly like {@link #expire(byte[], int) EXPIRE} but instead to get the number of * seconds representing the Time To Live of the key as a second argument (that is a relative way * of specifing the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of * seconds elapsed since 1 Gen 1970). * <p> * EXPIREAT was introduced in order to implement the Append Only File persistence mode so that * EXPIRE commands are automatically translated into EXPIREAT commands for the append only file. * Of course EXPIREAT can also used by programmers that need a way to simply specify that a given * key should expire at a given time in the future. * <p> * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire * set. It is also possible to undo the expire at all turning the key into a normal key using the * {@link #persist(byte[]) PERSIST} command. * <p> * Time complexity: O(1) * @see <a href="http://redis.io/commands/expire">Expire Command</a> * @param key * @param unixTime * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since * the key already has an associated timeout (this may happen only in Redis versions &lt; * 2.1.3, Redis &gt;= 2.1.3 will happily update the timeout), or the key does not exist. */ @Override public Long expireAt(final byte[] key, final long unixTime) { checkIsInMultiOrPipeline(); client.expireAt(key, unixTime); return client.getIntegerReply(); } /** * The TTL command returns the remaining time to live in seconds of a key that has an * {@link #expire(byte[], int) EXPIRE} set. This introspection capability allows a Redis client to * check how many seconds a given key will continue to be part of the dataset. * @param key * @return Integer reply, returns the remaining time to live in seconds of a key that has an * EXPIRE. If the Key does not exists or does not have an associated expire, -1 is * returned. */ @Override public Long ttl(final byte[] key) { checkIsInMultiOrPipeline(); client.ttl(key); return client.getIntegerReply(); } /** * Select the DB with having the specified zero-based numeric index. For default every new client * connection is automatically selected to DB 0. * @param index * @return Status code reply */ @Override public String select(final int index) { checkIsInMultiOrPipeline(); client.select(index); String statusCodeReply = client.getStatusCodeReply(); client.setDb(index); return statusCodeReply; } /** * Move the specified key from the currently selected DB to the specified destination DB. Note * that this command returns 1 only if the key was successfully moved, and 0 if the target key was * already there or if the source key was not found at all, so it is possible to use MOVE as a * locking primitive. * @param key * @param dbIndex * @return Integer reply, specifically: 1 if the key was moved 0 if the key was not moved because * already present on the target DB or was not found in the current DB. */ @Override public Long move(final byte[] key, final int dbIndex) { checkIsInMultiOrPipeline(); client.move(key, dbIndex); return client.getIntegerReply(); } /** * Delete all the keys of all the existing databases, not just the currently selected one. This * command never fails. * @return Status code reply */ @Override public String flushAll() { checkIsInMultiOrPipeline(); client.flushAll(); return client.getStatusCodeReply(); } /** * GETSET is an atomic set this value and return the old value command. Set key to the string * value and return the old value stored at key. The string can't be longer than 1073741824 bytes * (1 GB). * <p> * Time complexity: O(1) * @param key * @param value * @return Bulk reply */ @Override public byte[] getSet(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); client.getSet(key, value); return client.getBinaryBulkReply(); } /** * Get the values of all the specified keys. If one or more keys dont exist or is not of type * String, a 'nil' value is returned instead of the value of the specified key, but the operation * never fails. * <p> * Time complexity: O(1) for every key * @param keys * @return Multi bulk reply */ @Override public List<byte[]> mget(final byte[]... keys) { checkIsInMultiOrPipeline(); client.mget(keys); return client.getBinaryMultiBulkReply(); } /** * SETNX works exactly like {@link #set(byte[], byte[]) SET} with the only difference that if the * key already exists no operation is performed. SETNX actually means "SET if Not eXists". * <p> * Time complexity: O(1) * @param key * @param value * @return Integer reply, specifically: 1 if the key was set 0 if the key was not set */ @Override public Long setnx(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); client.setnx(key, value); return client.getIntegerReply(); } /** * The command is exactly equivalent to the following group of commands: * {@link #set(byte[], byte[]) SET} + {@link #expire(byte[], int) EXPIRE}. The operation is * atomic. * <p> * Time complexity: O(1) * @param key * @param seconds * @param value * @return Status code reply */ @Override public String setex(final byte[] key, final int seconds, final byte[] value) { checkIsInMultiOrPipeline(); client.setex(key, seconds, value); return client.getStatusCodeReply(); } /** * Set the the respective keys to the respective values. MSET will replace old values with new * values, while {@link #msetnx(byte[]...) MSETNX} will not perform any operation at all even if * just a single key already exists. * <p> * Because of this semantic MSETNX can be used in order to set different keys representing * different fields of an unique logic object in a way that ensures that either all the fields or * none at all are set. * <p> * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B * are modified, another client talking to Redis can either see the changes to both A and B at * once, or no modification at all. * @see #msetnx(byte[]...) * @param keysvalues * @return Status code reply Basically +OK as MSET can't fail */ @Override public String mset(final byte[]... keysvalues) { checkIsInMultiOrPipeline(); client.mset(keysvalues); return client.getStatusCodeReply(); } /** * Set the the respective keys to the respective values. {@link #mset(byte[]...) MSET} will * replace old values with new values, while MSETNX will not perform any operation at all even if * just a single key already exists. * <p> * Because of this semantic MSETNX can be used in order to set different keys representing * different fields of an unique logic object in a way that ensures that either all the fields or * none at all are set. * <p> * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B * are modified, another client talking to Redis can either see the changes to both A and B at * once, or no modification at all. * @see #mset(byte[]...) * @param keysvalues * @return Integer reply, specifically: 1 if the all the keys were set 0 if no key was set (at * least one key already existed) */ @Override public Long msetnx(final byte[]... keysvalues) { checkIsInMultiOrPipeline(); client.msetnx(keysvalues); return client.getIntegerReply(); } /** * DECRBY work just like {@link #decr(byte[]) INCR} but instead to decrement by 1 the decrement is * integer. * <p> * INCR commands are limited to 64 bit signed integers. * <p> * Note: this is actually a string operation, that is, in Redis there are not "integer" types. * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, * and then converted back as a string. * <p> * Time complexity: O(1) * @see #incr(byte[]) * @see #decr(byte[]) * @see #incrBy(byte[], long) * @param key * @param integer * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override public Long decrBy(final byte[] key, final long integer) { checkIsInMultiOrPipeline(); client.decrBy(key, integer); return client.getIntegerReply(); } /** * Decrement the number stored at key by one. If the key does not exist or contains a value of a * wrong type, set the key to the value of "0" before to perform the decrement operation. * <p> * INCR commands are limited to 64 bit signed integers. * <p> * Note: this is actually a string operation, that is, in Redis there are not "integer" types. * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, * and then converted back as a string. * <p> * Time complexity: O(1) * @see #incr(byte[]) * @see #incrBy(byte[], long) * @see #decrBy(byte[], long) * @param key * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override public Long decr(final byte[] key) { checkIsInMultiOrPipeline(); client.decr(key); return client.getIntegerReply(); } /** * INCRBY work just like {@link #incr(byte[]) INCR} but instead to increment by 1 the increment is * integer. * <p> * INCR commands are limited to 64 bit signed integers. * <p> * Note: this is actually a string operation, that is, in Redis there are not "integer" types. * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, * and then converted back as a string. * <p> * Time complexity: O(1) * @see #incr(byte[]) * @see #decr(byte[]) * @see #decrBy(byte[], long) * @param key * @param integer * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override public Long incrBy(final byte[] key, final long integer) { checkIsInMultiOrPipeline(); client.incrBy(key, integer); return client.getIntegerReply(); } /** * INCRBYFLOAT work just like {@link #incrBy(byte[], long)} INCRBY} but increments by floats * instead of integers. * <p> * INCRBYFLOAT commands are limited to double precision floating point values. * <p> * Note: this is actually a string operation, that is, in Redis there are not "double" types. * Simply the string stored at the key is parsed as a base double precision floating point value, * incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a * negative value will work as expected. * <p> * Time complexity: O(1) * @see #incr(byte[]) * @see #decr(byte[]) * @see #decrBy(byte[], long) * @param key the key to increment * @param integer the value to increment by * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override public Double incrByFloat(final byte[] key, final double integer) { checkIsInMultiOrPipeline(); client.incrByFloat(key, integer); String dval = client.getBulkReply(); return (dval != null ? new Double(dval) : null); } /** * Increment the number stored at key by one. If the key does not exist or contains a value of a * wrong type, set the key to the value of "0" before to perform the increment operation. * <p> * INCR commands are limited to 64 bit signed integers. * <p> * Note: this is actually a string operation, that is, in Redis there are not "integer" types. * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, * and then converted back as a string. * <p> * Time complexity: O(1) * @see #incrBy(byte[], long) * @see #decr(byte[]) * @see #decrBy(byte[], long) * @param key * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override public Long incr(final byte[] key) { checkIsInMultiOrPipeline(); client.incr(key); return client.getIntegerReply(); } /** * If the key already exists and is a string, this command appends the provided value at the end * of the string. If the key does not exist it is created and set as an empty string, so APPEND * will be very similar to SET in this special case. * <p> * Time complexity: O(1). The amortized time complexity is O(1) assuming the appended value is * small and the already present value is of any size, since the dynamic string library used by * Redis will double the free space available on every reallocation. * @param key * @param value * @return Integer reply, specifically the total length of the string after the append operation. */ @Override public Long append(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); client.append(key, value); return client.getIntegerReply(); } /** * Return a subset of the string from offset start to offset end (both offsets are inclusive). * Negative offsets can be used in order to provide an offset starting from the end of the string. * So -1 means the last char, -2 the penultimate and so forth. * <p> * The function handles out of range requests without raising an error, but just limiting the * resulting range to the actual length of the string. * <p> * Time complexity: O(start+n) (with start being the start index and n the total length of the * requested range). Note that the lookup part of this command is O(1) so for small strings this * is actually an O(1) command. * @param key * @param start * @param end * @return Bulk reply */ @Override public byte[] substr(final byte[] key, final int start, final int end) { checkIsInMultiOrPipeline(); client.substr(key, start, end); return client.getBinaryBulkReply(); } /** * Set the specified hash field to the specified value. * <p> * If key does not exist, a new key holding a hash is created. * <p> * <b>Time complexity:</b> O(1) * @param key * @param field * @param value * @return If the field already exists, and the HSET just produced an update of the value, 0 is * returned, otherwise if a new field is created 1 is returned. */ @Override public Long hset(final byte[] key, final byte[] field, final byte[] value) { checkIsInMultiOrPipeline(); client.hset(key, field, value); return client.getIntegerReply(); } /** * If key holds a hash, retrieve the value associated to the specified field. * <p> * If the field is not found or the key does not exist, a special 'nil' value is returned. * <p> * <b>Time complexity:</b> O(1) * @param key * @param field * @return Bulk reply */ @Override public byte[] hget(final byte[] key, final byte[] field) { checkIsInMultiOrPipeline(); client.hget(key, field); return client.getBinaryBulkReply(); } /** * Set the specified hash field to the specified value if the field not exists. <b>Time * complexity:</b> O(1) * @param key * @param field * @param value * @return If the field already exists, 0 is returned, otherwise if a new field is created 1 is * returned. */ @Override public Long hsetnx(final byte[] key, final byte[] field, final byte[] value) { checkIsInMultiOrPipeline(); client.hsetnx(key, field, value); return client.getIntegerReply(); } /** * Set the respective fields to the respective values. HMSET replaces old values with new values. * <p> * If key does not exist, a new key holding a hash is created. * <p> * <b>Time complexity:</b> O(N) (with N being the number of fields) * @param key * @param hash * @return Always OK because HMSET can't fail */ @Override public String hmset(final byte[] key, final Map<byte[], byte[]> hash) { checkIsInMultiOrPipeline(); client.hmset(key, hash); return client.getStatusCodeReply(); } /** * Retrieve the values associated to the specified fields. * <p> * If some of the specified fields do not exist, nil values are returned. Non existing keys are * considered like empty hashes. * <p> * <b>Time complexity:</b> O(N) (with N being the number of fields) * @param key * @param fields * @return Multi Bulk Reply specifically a list of all the values associated with the specified * fields, in the same order of the request. */ @Override public List<byte[]> hmget(final byte[] key, final byte[]... fields) { checkIsInMultiOrPipeline(); client.hmget(key, fields); return client.getBinaryMultiBulkReply(); } /** * Increment the number stored at field in the hash at key by value. If key does not exist, a new * key holding a hash is created. If field does not exist or holds a string, the value is set to 0 * before applying the operation. Since the value argument is signed you can use this command to * perform both increments and decrements. * <p> * The range of values supported by HINCRBY is limited to 64 bit signed integers. * <p> * <b>Time complexity:</b> O(1) * @param key * @param field * @param value * @return Integer reply The new value at field after the increment operation. */ @Override public Long hincrBy(final byte[] key, final byte[] field, final long value) { checkIsInMultiOrPipeline(); client.hincrBy(key, field, value); return client.getIntegerReply(); } /** * Increment the number stored at field in the hash at key by a double precision floating point * value. If key does not exist, a new key holding a hash is created. If field does not exist or * holds a string, the value is set to 0 before applying the operation. Since the value argument * is signed you can use this command to perform both increments and decrements. * <p> * The range of values supported by HINCRBYFLOAT is limited to double precision floating point * values. * <p> * <b>Time complexity:</b> O(1) * @param key * @param field * @param value * @return Double precision floating point reply The new value at field after the increment * operation. */ @Override public Double hincrByFloat(final byte[] key, final byte[] field, final double value) { checkIsInMultiOrPipeline(); client.hincrByFloat(key, field, value); final String dval = client.getBulkReply(); return (dval != null ? new Double(dval) : null); } /** * Test for existence of a specified field in a hash. <b>Time complexity:</b> O(1) * @param key * @param field * @return Return 1 if the hash stored at key contains the specified field. Return 0 if the key is * not found or the field is not present. */ @Override public Boolean hexists(final byte[] key, final byte[] field) { checkIsInMultiOrPipeline(); client.hexists(key, field); return client.getIntegerReply() == 1; } /** * Remove the specified field from an hash stored at key. * <p> * <b>Time complexity:</b> O(1) * @param key * @param fields * @return If the field was present in the hash it is deleted and 1 is returned, otherwise 0 is * returned and no operation is performed. */ @Override public Long hdel(final byte[] key, final byte[]... fields) { checkIsInMultiOrPipeline(); client.hdel(key, fields); return client.getIntegerReply(); } /** * Return the number of items in a hash. * <p> * <b>Time complexity:</b> O(1) * @param key * @return The number of entries (fields) contained in the hash stored at key. If the specified * key does not exist, 0 is returned assuming an empty hash. */ @Override public Long hlen(final byte[] key) { checkIsInMultiOrPipeline(); client.hlen(key); return client.getIntegerReply(); } /** * Return all the fields in a hash. * <p> * <b>Time complexity:</b> O(N), where N is the total number of entries * @param key * @return All the fields names contained into a hash. */ @Override public Set<byte[]> hkeys(final byte[] key) { checkIsInMultiOrPipeline(); client.hkeys(key); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Return all the values in a hash. * <p> * <b>Time complexity:</b> O(N), where N is the total number of entries * @param key * @return All the fields values contained into a hash. */ @Override public List<byte[]> hvals(final byte[] key) { checkIsInMultiOrPipeline(); client.hvals(key); return client.getBinaryMultiBulkReply(); } /** * Return all the fields and associated values in a hash. * <p> * <b>Time complexity:</b> O(N), where N is the total number of entries * @param key * @return All the fields and values contained into a hash. */ @Override public Map<byte[], byte[]> hgetAll(final byte[] key) { checkIsInMultiOrPipeline(); client.hgetAll(key); final List<byte[]> flatHash = client.getBinaryMultiBulkReply(); final Map<byte[], byte[]> hash = new JedisByteHashMap(); final Iterator<byte[]> iterator = flatHash.iterator(); while (iterator.hasNext()) { hash.put(iterator.next(), iterator.next()); } return hash; } /** * Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key * does not exist an empty list is created just before the append operation. If the key exists but * is not a List an error is returned. * <p> * Time complexity: O(1) * @see BinaryJedis#rpush(byte[], byte[]...) * @param key * @param strings * @return Integer reply, specifically, the number of elements inside the list after the push * operation. */ @Override public Long rpush(final byte[] key, final byte[]... strings) { checkIsInMultiOrPipeline(); client.rpush(key, strings); return client.getIntegerReply(); } /** * Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key * does not exist an empty list is created just before the append operation. If the key exists but * is not a List an error is returned. * <p> * Time complexity: O(1) * @see BinaryJedis#rpush(byte[], byte[]...) * @param key * @param strings * @return Integer reply, specifically, the number of elements inside the list after the push * operation. */ @Override public Long lpush(final byte[] key, final byte[]... strings) { checkIsInMultiOrPipeline(); client.lpush(key, strings); return client.getIntegerReply(); } /** * Return the length of the list stored at the specified key. If the key does not exist zero is * returned (the same behaviour as for empty lists). If the value stored at key is not a list an * error is returned. * <p> * Time complexity: O(1) * @param key * @return The length of the list. */ @Override public Long llen(final byte[] key) { checkIsInMultiOrPipeline(); client.llen(key); return client.getIntegerReply(); } /** * Return the specified elements of the list stored at the specified key. Start and end are * zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and * so on. * <p> * For example LRANGE foobar 0 2 will return the first three elements of the list. * <p> * start and end can also be negative numbers indicating offsets from the end of the list. For * example -1 is the last element of the list, -2 the penultimate element and so on. * <p> * <b>Consistency with range functions in various programming languages</b> * <p> * Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will return 11 elements, * that is, rightmost item is included. This may or may not be consistent with behavior of * range-related functions in your programming language of choice (think Ruby's Range.new, * Array#slice or Python's range() function). * <p> * LRANGE behavior is consistent with one of Tcl. * <p> * <b>Out-of-range indexes</b> * <p> * Indexes out of range will not produce an error: if start is over the end of the list, or start * &gt; end, an empty list is returned. If end is over the end of the list Redis will threat it * just like the last element of the list. * <p> * Time complexity: O(start+n) (with n being the length of the range and start being the start * offset) * @param key * @param start * @param end * @return Multi bulk reply, specifically a list of elements in the specified range. */ @Override public List<byte[]> lrange(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.lrange(key, start, end); return client.getBinaryMultiBulkReply(); } /** * Trim an existing list so that it will contain only the specified range of elements specified. * Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the * next element and so on. * <p> * For example LTRIM foobar 0 2 will modify the list stored at foobar key so that only the first * three elements of the list will remain. * <p> * start and end can also be negative numbers indicating offsets from the end of the list. For * example -1 is the last element of the list, -2 the penultimate element and so on. * <p> * Indexes out of range will not produce an error: if start is over the end of the list, or start * &gt; end, an empty list is left as value. If end over the end of the list Redis will threat it * just like the last element of the list. * <p> * Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example: * <p> * {@code lpush("mylist", "someelement"); ltrim("mylist", 0, 99); * } * <p> * The above two commands will push elements in the list taking care that the list will not grow * without limits. This is very useful when using Redis to store logs for example. It is important * to note that when used in this way LTRIM is an O(1) operation because in the average case just * one element is removed from the tail of the list. * <p> * Time complexity: O(n) (with n being len of list - len of range) * @param key * @param start * @param end * @return Status code reply */ @Override public String ltrim(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.ltrim(key, start, end); return client.getStatusCodeReply(); } /** * Return the specified element of the list stored at the specified key. 0 is the first element, 1 * the second and so on. Negative indexes are supported, for example -1 is the last element, -2 * the penultimate and so on. * <p> * If the value stored at key is not of list type an error is returned. If the index is out of * range a 'nil' reply is returned. * <p> * Note that even if the average time complexity is O(n) asking for the first or the last element * of the list is O(1). * <p> * Time complexity: O(n) (with n being the length of the list) * @param key * @param index * @return Bulk reply, specifically the requested element */ @Override public byte[] lindex(final byte[] key, final long index) { checkIsInMultiOrPipeline(); client.lindex(key, index); return client.getBinaryBulkReply(); } /** * Set a new value as the element at index position of the List at key. * <p> * Out of range indexes will generate an error. * <p> * Similarly to other list commands accepting indexes, the index can be negative to access * elements starting from the end of the list. So -1 is the last element, -2 is the penultimate, * and so forth. * <p> * <b>Time complexity:</b> * <p> * O(N) (with N being the length of the list), setting the first or last elements of the list is * O(1). * @see #lindex(byte[], long) * @param key * @param index * @param value * @return Status code reply */ @Override public String lset(final byte[] key, final long index, final byte[] value) { checkIsInMultiOrPipeline(); client.lset(key, index, value); return client.getStatusCodeReply(); } /** * Remove the first count occurrences of the value element from the list. If count is zero all the * elements are removed. If count is negative elements are removed from tail to head, instead to * go from head to tail that is the normal behaviour. So for example LREM with count -2 and hello * as value to remove against the list (a,b,c,hello,x,hello,hello) will have the list * (a,b,c,hello,x). The number of removed elements is returned as an integer, see below for more * information about the returned value. Note that non existing keys are considered like empty * lists by LREM, so LREM against non existing keys will always return 0. * <p> * Time complexity: O(N) (with N being the length of the list) * @param key * @param count * @param value * @return Integer Reply, specifically: The number of removed elements if the operation succeeded */ @Override public Long lrem(final byte[] key, final long count, final byte[] value) { checkIsInMultiOrPipeline(); client.lrem(key, count, value); return client.getIntegerReply(); } /** * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example * if the list contains the elements "a","b","c" LPOP will return "a" and the list will become * "b","c". * <p> * If the key does not exist or the list is already empty the special value 'nil' is returned. * @see #rpop(byte[]) * @param key * @return Bulk reply */ @Override public byte[] lpop(final byte[] key) { checkIsInMultiOrPipeline(); client.lpop(key); return client.getBinaryBulkReply(); } /** * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example * if the list contains the elements "a","b","c" LPOP will return "a" and the list will become * "b","c". * <p> * If the key does not exist or the list is already empty the special value 'nil' is returned. * @see #lpop(byte[]) * @param key * @return Bulk reply */ @Override public byte[] rpop(final byte[] key) { checkIsInMultiOrPipeline(); client.rpop(key); return client.getBinaryBulkReply(); } /** * Atomically return and remove the last (tail) element of the srckey list, and push the element * as the first (head) element of the dstkey list. For example if the source list contains the * elements "a","b","c" and the destination list contains the elements "foo","bar" after an * RPOPLPUSH command the content of the two lists will be "a","b" and "c","foo","bar". * <p> * If the key does not exist or the list is already empty the special value 'nil' is returned. If * the srckey and dstkey are the same the operation is equivalent to removing the last element * from the list and pusing it as first element of the list, so it's a "list rotation" command. * <p> * Time complexity: O(1) * @param srckey * @param dstkey * @return Bulk reply */ @Override public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) { checkIsInMultiOrPipeline(); client.rpoplpush(srckey, dstkey); return client.getBinaryBulkReply(); } /** * Add the specified member to the set value stored at key. If member is already a member of the * set no operation is performed. If key does not exist a new set with the specified member as * sole member is created. If the key exists but does not hold a set value an error is returned. * <p> * Time complexity O(1) * @param key * @param members * @return Integer reply, specifically: 1 if the new element was added 0 if the element was * already a member of the set */ @Override public Long sadd(final byte[] key, final byte[]... members) { checkIsInMultiOrPipeline(); client.sadd(key, members); return client.getIntegerReply(); } /** * Return all the members (elements) of the set value stored at key. This is just syntax glue for * {@link #sinter(byte[]...)} SINTER}. * <p> * Time complexity O(N) * @param key the key of the set * @return Multi bulk reply */ @Override public Set<byte[]> smembers(final byte[] key) { checkIsInMultiOrPipeline(); client.smembers(key); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Remove the specified member from the set value stored at key. If member was not a member of the * set no operation is performed. If key does not hold a set value an error is returned. * <p> * Time complexity O(1) * @param key the key of the set * @param member the set member to remove * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was * not a member of the set */ @Override public Long srem(final byte[] key, final byte[]... member) { checkIsInMultiOrPipeline(); client.srem(key, member); return client.getIntegerReply(); } /** * Remove a random element from a Set returning it as return value. If the Set is empty or the key * does not exist, a nil object is returned. * <p> * The {@link #srandmember(byte[])} command does a similar work but the returned element is not * removed from the Set. * <p> * Time complexity O(1) * @param key * @return Bulk reply */ @Override public byte[] spop(final byte[] key) { checkIsInMultiOrPipeline(); client.spop(key); return client.getBinaryBulkReply(); } @Override public Set<byte[]> spop(final byte[] key, final long count) { checkIsInMultiOrPipeline(); client.spop(key, count); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Move the specified member from the set at srckey to the set at dstkey. This operation is * atomic, in every given moment the element will appear to be in the source or destination set * for accessing clients. * <p> * If the source set does not exist or does not contain the specified element no operation is * performed and zero is returned, otherwise the element is removed from the source set and added * to the destination set. On success one is returned, even if the element was already present in * the destination set. * <p> * An error is raised if the source or destination keys contain a non Set value. * <p> * Time complexity O(1) * @param srckey * @param dstkey * @param member * @return Integer reply, specifically: 1 if the element was moved 0 if the element was not found * on the first set and no operation was performed */ @Override public Long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { checkIsInMultiOrPipeline(); client.smove(srckey, dstkey, member); return client.getIntegerReply(); } /** * Return the set cardinality (number of elements). If the key does not exist 0 is returned, like * for empty sets. * @param key * @return Integer reply, specifically: the cardinality (number of elements) of the set as an * integer. */ @Override public Long scard(final byte[] key) { checkIsInMultiOrPipeline(); client.scard(key); return client.getIntegerReply(); } /** * Return 1 if member is a member of the set stored at key, otherwise 0 is returned. * <p> * Time complexity O(1) * @param key * @param member * @return Integer reply, specifically: 1 if the element is a member of the set 0 if the element * is not a member of the set OR if the key does not exist */ @Override public Boolean sismember(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); client.sismember(key, member); return client.getIntegerReply() == 1; } /** * Return the members of a set resulting from the intersection of all the sets hold at the * specified keys. Like in {@link #lrange(byte[], long, long)} LRANGE} the result is sent to the * client as a multi-bulk reply (see the protocol specification for more information). If just a * single key is specified, then this command produces the same result as * {@link #smembers(byte[]) SMEMBERS}. Actually SMEMBERS is just syntax sugar for SINTER. * <p> * Non existing keys are considered like empty sets, so if one of the keys is missing an empty set * is returned (since the intersection with an empty set always is an empty set). * <p> * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the * number of sets * @param keys * @return Multi bulk reply, specifically the list of common elements. */ @Override public Set<byte[]> sinter(final byte[]... keys) { checkIsInMultiOrPipeline(); client.sinter(keys); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * This commnad works exactly like {@link #sinter(byte[]...) SINTER} but instead of being returned * the resulting set is sotred as dstkey. * <p> * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the * number of sets * @param dstkey * @param keys * @return Status code reply */ @Override public Long sinterstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); client.sinterstore(dstkey, keys); return client.getIntegerReply(); } /** * Return the members of a set resulting from the union of all the sets hold at the specified * keys. Like in {@link #lrange(byte[], long, long)} LRANGE} the result is sent to the client as a * multi-bulk reply (see the protocol specification for more information). If just a single key is * specified, then this command produces the same result as {@link #smembers(byte[]) SMEMBERS}. * <p> * Non existing keys are considered like empty sets. * <p> * Time complexity O(N) where N is the total number of elements in all the provided sets * @param keys * @return Multi bulk reply, specifically the list of common elements. */ @Override public Set<byte[]> sunion(final byte[]... keys) { checkIsInMultiOrPipeline(); client.sunion(keys); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * This command works exactly like {@link #sunion(byte[]...) SUNION} but instead of being returned * the resulting set is stored as dstkey. Any existing value in dstkey will be over-written. * <p> * Time complexity O(N) where N is the total number of elements in all the provided sets * @param dstkey * @param keys * @return Status code reply */ @Override public Long sunionstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); client.sunionstore(dstkey, keys); return client.getIntegerReply(); } /** * Return the difference between the Set stored at key1 and all the Sets key2, ..., keyN * <p> * <b>Example:</b> * * <pre> * key1 = [x, a, b, c] * key2 = [c] * key3 = [a, d] * SDIFF key1,key2,key3 =&gt; [x, b] * </pre> * * Non existing keys are considered like empty sets. * <p> * <b>Time complexity:</b> * <p> * O(N) with N being the total number of elements of all the sets * @param keys * @return Return the members of a set resulting from the difference between the first set * provided and all the successive sets. */ @Override public Set<byte[]> sdiff(final byte[]... keys) { checkIsInMultiOrPipeline(); client.sdiff(keys); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * This command works exactly like {@link #sdiff(byte[]...) SDIFF} but instead of being returned * the resulting set is stored in dstkey. * @param dstkey * @param keys * @return Status code reply */ @Override public Long sdiffstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); client.sdiffstore(dstkey, keys); return client.getIntegerReply(); } /** * Return a random element from a Set, without removing the element. If the Set is empty or the * key does not exist, a nil object is returned. * <p> * The SPOP command does a similar work but the returned element is popped (removed) from the Set. * <p> * Time complexity O(1) * @param key * @return Bulk reply */ @Override public byte[] srandmember(final byte[] key) { checkIsInMultiOrPipeline(); client.srandmember(key); return client.getBinaryBulkReply(); } @Override public List<byte[]> srandmember(final byte[] key, final int count) { checkIsInMultiOrPipeline(); client.srandmember(key, count); return client.getBinaryMultiBulkReply(); } /** * Add the specified member having the specifeid score to the sorted set stored at key. If member * is already a member of the sorted set the score is updated, and the element reinserted in the * right position to ensure sorting. If key does not exist a new sorted set with the specified * member as sole member is crated. If the key exists but does not hold a sorted set value an * error is returned. * <p> * The score value can be the string representation of a double precision floating point number. * <p> * Time complexity O(log(N)) with N being the number of elements in the sorted set * @param key * @param score * @param member * @return Integer reply, specifically: 1 if the new element was added 0 if the element was * already a member of the sorted set and the score was updated */ @Override public Long zadd(final byte[] key, final double score, final byte[] member) { checkIsInMultiOrPipeline(); client.zadd(key, score, member); return client.getIntegerReply(); } @Override public Long zadd(byte[] key, double score, byte[] member, ZAddParams params) { checkIsInMultiOrPipeline(); client.zadd(key, score, member, params); return client.getIntegerReply(); } @Override public Long zadd(final byte[] key, final Map<byte[], Double> scoreMembers) { checkIsInMultiOrPipeline(); client.zadd(key, scoreMembers); return client.getIntegerReply(); } @Override public Long zadd(byte[] key, Map<byte[], Double> scoreMembers, ZAddParams params) { checkIsInMultiOrPipeline(); client.zadd(key, scoreMembers, params); return client.getIntegerReply(); } @Override public Set<byte[]> zrange(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.zrange(key, start, end); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Remove the specified member from the sorted set value stored at key. If member was not a member * of the set no operation is performed. If key does not not hold a set value an error is * returned. * <p> * Time complexity O(log(N)) with N being the number of elements in the sorted set * @param key * @param members * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was * not a member of the set */ @Override public Long zrem(final byte[] key, final byte[]... members) { checkIsInMultiOrPipeline(); client.zrem(key, members); return client.getIntegerReply(); } /** * If member already exists in the sorted set adds the increment to its score and updates the * position of the element in the sorted set accordingly. If member does not already exist in the * sorted set it is added with increment as score (that is, like if the previous score was * virtually zero). If key does not exist a new sorted set with the specified member as sole * member is crated. If the key exists but does not hold a sorted set value an error is returned. * <p> * The score value can be the string representation of a double precision floating point number. * It's possible to provide a negative value to perform a decrement. * <p> * For an introduction to sorted sets check the Introduction to Redis data types page. * <p> * Time complexity O(log(N)) with N being the number of elements in the sorted set * @param key * @param score * @param member * @return The new score */ @Override public Double zincrby(final byte[] key, final double score, final byte[] member) { checkIsInMultiOrPipeline(); client.zincrby(key, score, member); String newscore = client.getBulkReply(); return Double.valueOf(newscore); } @Override public Double zincrby(byte[] key, double score, byte[] member, ZIncrByParams params) { checkIsInMultiOrPipeline(); client.zincrby(key, score, member, params); String newscore = client.getBulkReply(); // with nx / xx options it could return null now if (newscore == null) return null; return Double.valueOf(newscore); } /** * Return the rank (or index) or member in the sorted set at key, with scores being ordered from * low to high. * <p> * When the given member does not exist in the sorted set, the special value 'nil' is returned. * The returned rank (or index) of the member is 0-based for both commands. * <p> * <b>Time complexity:</b> * <p> * O(log(N)) * @see #zrevrank(byte[], byte[]) * @param key * @param member * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer * reply if the element exists. A nil bulk reply if there is no such element. */ @Override public Long zrank(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); client.zrank(key, member); return client.getIntegerReply(); } /** * Return the rank (or index) or member in the sorted set at key, with scores being ordered from * high to low. * <p> * When the given member does not exist in the sorted set, the special value 'nil' is returned. * The returned rank (or index) of the member is 0-based for both commands. * <p> * <b>Time complexity:</b> * <p> * O(log(N)) * @see #zrank(byte[], byte[]) * @param key * @param member * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer * reply if the element exists. A nil bulk reply if there is no such element. */ @Override public Long zrevrank(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); client.zrevrank(key, member); return client.getIntegerReply(); } @Override public Set<byte[]> zrevrange(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.zrevrange(key, start, end); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Set<Tuple> zrangeWithScores(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.zrangeWithScores(key, start, end); return getBinaryTupledSet(); } @Override public Set<Tuple> zrevrangeWithScores(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.zrevrangeWithScores(key, start, end); return getBinaryTupledSet(); } /** * Return the sorted set cardinality (number of elements). If the key does not exist 0 is * returned, like for empty sorted sets. * <p> * Time complexity O(1) * @param key * @return the cardinality (number of elements) of the set as an integer. */ @Override public Long zcard(final byte[] key) { checkIsInMultiOrPipeline(); client.zcard(key); return client.getIntegerReply(); } /** * Return the score of the specified element of the sorted set at key. If the specified element * does not exist in the sorted set, or the key does not exist at all, a special 'nil' value is * returned. * <p> * <b>Time complexity:</b> O(1) * @param key * @param member * @return the score */ @Override public Double zscore(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); client.zscore(key, member); final String score = client.getBulkReply(); return (score != null ? new Double(score) : null); } public Transaction multi() { client.multi(); client.getOne(); // expected OK transaction = new Transaction(client); return transaction; } protected void checkIsInMultiOrPipeline() { if (client.isInMulti()) { throw new JedisDataException( "Cannot use Jedis when in Multi. Please use Transation or reset jedis state."); } else if (pipeline != null && pipeline.hasPipelinedResponse()) { throw new JedisDataException( "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state ."); } } public void connect() { client.connect(); } public void disconnect() { client.disconnect(); } public void resetState() { if (client.isConnected()) { if (transaction != null) { transaction.clear(); } if (pipeline != null) { pipeline.clear(); } if (client.isInWatch()) { unwatch(); } client.resetState(); } transaction = null; pipeline = null; } @Override public String watch(final byte[]... keys) { client.watch(keys); return client.getStatusCodeReply(); } @Override public String unwatch() { client.unwatch(); return client.getStatusCodeReply(); } @Override public void close() { client.close(); } /** * Sort a Set or a List. * <p> * Sort the elements contained in the List, Set, or Sorted Set value at key. By default sorting is * numeric with elements being compared as double precision floating point numbers. This is the * simplest form of SORT. * @see #sort(byte[], byte[]) * @see #sort(byte[], SortingParams) * @see #sort(byte[], SortingParams, byte[]) * @param key * @return Assuming the Set/List at key contains a list of numbers, the return value will be the * list of numbers ordered from the smallest to the biggest number. */ @Override public List<byte[]> sort(final byte[] key) { checkIsInMultiOrPipeline(); client.sort(key); return client.getBinaryMultiBulkReply(); } /** * Sort a Set or a List accordingly to the specified parameters. * <p> * <b>examples:</b> * <p> * Given are the following sets and key/values: * * <pre> * x = [1, 2, 3] * y = [a, b, c] * * k1 = z * k2 = y * k3 = x * * w1 = 9 * w2 = 8 * w3 = 7 * </pre> * * Sort Order: * * <pre> * sort(x) or sort(x, sp.asc()) * -&gt; [1, 2, 3] * * sort(x, sp.desc()) * -&gt; [3, 2, 1] * * sort(y) * -&gt; [c, a, b] * * sort(y, sp.alpha()) * -&gt; [a, b, c] * * sort(y, sp.alpha().desc()) * -&gt; [c, a, b] * </pre> * * Limit (e.g. for Pagination): * * <pre> * sort(x, sp.limit(0, 2)) * -&gt; [1, 2] * * sort(y, sp.alpha().desc().limit(1, 2)) * -&gt; [b, a] * </pre> * * Sorting by external keys: * * <pre> * sort(x, sb.by(w*)) * -&gt; [3, 2, 1] * * sort(x, sb.by(w*).desc()) * -&gt; [1, 2, 3] * </pre> * * Getting external keys: * * <pre> * sort(x, sp.by(w*).get(k*)) * -&gt; [x, y, z] * * sort(x, sp.by(w*).get(#).get(k*)) * -&gt; [3, x, 2, y, 1, z] * </pre> * @see #sort(byte[]) * @see #sort(byte[], SortingParams, byte[]) * @param key * @param sortingParameters * @return a list of sorted elements. */ @Override public List<byte[]> sort(final byte[] key, final SortingParams sortingParameters) { checkIsInMultiOrPipeline(); client.sort(key, sortingParameters); return client.getBinaryMultiBulkReply(); } /** * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking * versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty * lists. * <p> * The following is a description of the exact semantic. We describe BLPOP but the two commands * are identical, the only difference is that BLPOP pops the element from the left (head) of the * list, and BRPOP pops from the right (tail). * <p> * <b>Non blocking behavior</b> * <p> * When BLPOP is called, if at least one of the specified keys contain a non empty list, an * element is popped from the head of the list and returned to the caller together with the name * of the key (BLPOP returns a two elements array, the first element is the key, the second the * popped value). * <p> * Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0 * against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP * guarantees to return an element from the list stored at list2 (since it is the first non empty * list starting from the left). * <p> * <b>Blocking behavior</b> * <p> * If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other * client performs a LPUSH or an RPUSH operation against one of the lists. * <p> * Once new data is present on one of the lists, the client finally returns with the name of the * key unblocking it and the popped value. * <p> * When blocking, if a non-zero timeout is specified, the client will unblock returning a nil * special value if the specified amount of seconds passed without a push operation against at * least one of the specified keys. * <p> * The timeout argument is interpreted as an integer value. A timeout of zero means instead to * block forever. * <p> * <b>Multiple clients blocking for the same keys</b> * <p> * Multiple clients can block for the same key. They are put into a queue, so the first to be * served will be the one that started to wait earlier, in a first-blpopping first-served fashion. * <p> * <b>blocking POP inside a MULTI/EXEC transaction</b> * <p> * BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies * in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis * transaction). * <p> * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil * reply, exactly what happens when the timeout is reached. If you like science fiction, think at * it like if inside MULTI/EXEC the time will flow at infinite speed :) * <p> * Time complexity: O(1) * @see #brpop(int, byte[]...) * @param timeout * @param keys * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the * unblocking key and the popped value. * <p> * When a non-zero timeout is specified, and the BLPOP operation timed out, the return * value is a nil multi bulk reply. Most client values will return false or nil * accordingly to the programming language used. */ @Override public List<byte[]> blpop(final int timeout, final byte[]... keys) { return blpop(getArgsAddTimeout(timeout, keys)); } private byte[][] getArgsAddTimeout(int timeout, byte[][] keys) { int size = keys.length; final byte[][] args = new byte[size + 1][]; for (int at = 0; at != size; ++at) { args[at] = keys[at]; } args[size] = Protocol.toByteArray(timeout); return args; } /** * Sort a Set or a List accordingly to the specified parameters and store the result at dstkey. * @see #sort(byte[], SortingParams) * @see #sort(byte[]) * @see #sort(byte[], byte[]) * @param key * @param sortingParameters * @param dstkey * @return The number of elements of the list at dstkey. */ @Override public Long sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { checkIsInMultiOrPipeline(); client.sort(key, sortingParameters, dstkey); return client.getIntegerReply(); } /** * Sort a Set or a List and Store the Result at dstkey. * <p> * Sort the elements contained in the List, Set, or Sorted Set value at key and store the result * at dstkey. By default sorting is numeric with elements being compared as double precision * floating point numbers. This is the simplest form of SORT. * @see #sort(byte[]) * @see #sort(byte[], SortingParams) * @see #sort(byte[], SortingParams, byte[]) * @param key * @param dstkey * @return The number of elements of the list at dstkey. */ @Override public Long sort(final byte[] key, final byte[] dstkey) { checkIsInMultiOrPipeline(); client.sort(key, dstkey); return client.getIntegerReply(); } /** * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking * versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty * lists. * <p> * The following is a description of the exact semantic. We describe BLPOP but the two commands * are identical, the only difference is that BLPOP pops the element from the left (head) of the * list, and BRPOP pops from the right (tail). * <p> * <b>Non blocking behavior</b> * <p> * When BLPOP is called, if at least one of the specified keys contain a non empty list, an * element is popped from the head of the list and returned to the caller together with the name * of the key (BLPOP returns a two elements array, the first element is the key, the second the * popped value). * <p> * Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0 * against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP * guarantees to return an element from the list stored at list2 (since it is the first non empty * list starting from the left). * <p> * <b>Blocking behavior</b> * <p> * If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other * client performs a LPUSH or an RPUSH operation against one of the lists. * <p> * Once new data is present on one of the lists, the client finally returns with the name of the * key unblocking it and the popped value. * <p> * When blocking, if a non-zero timeout is specified, the client will unblock returning a nil * special value if the specified amount of seconds passed without a push operation against at * least one of the specified keys. * <p> * The timeout argument is interpreted as an integer value. A timeout of zero means instead to * block forever. * <p> * <b>Multiple clients blocking for the same keys</b> * <p> * Multiple clients can block for the same key. They are put into a queue, so the first to be * served will be the one that started to wait earlier, in a first-blpopping first-served fashion. * <p> * <b>blocking POP inside a MULTI/EXEC transaction</b> * <p> * BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies * in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis * transaction). * <p> * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil * reply, exactly what happens when the timeout is reached. If you like science fiction, think at * it like if inside MULTI/EXEC the time will flow at infinite speed :) * <p> * Time complexity: O(1) * @see #blpop(int, byte[]...) * @param timeout * @param keys * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the * unblocking key and the popped value. * <p> * When a non-zero timeout is specified, and the BLPOP operation timed out, the return * value is a nil multi bulk reply. Most client values will return false or nil * accordingly to the programming language used. */ @Override public List<byte[]> brpop(final int timeout, final byte[]... keys) { return brpop(getArgsAddTimeout(timeout, keys)); } @Override public List<byte[]> blpop(byte[]... args) { checkIsInMultiOrPipeline(); client.blpop(args); client.setTimeoutInfinite(); try { return client.getBinaryMultiBulkReply(); } finally { client.rollbackTimeout(); } } @Override public List<byte[]> brpop(byte[]... args) { checkIsInMultiOrPipeline(); client.brpop(args); client.setTimeoutInfinite(); try { return client.getBinaryMultiBulkReply(); } finally { client.rollbackTimeout(); } } /** * Request for authentication in a password protected Redis server. A Redis server can be * instructed to require a password before to allow clients to issue commands. This is done using * the requirepass directive in the Redis configuration file. If the password given by the client * is correct the server replies with an OK status code reply and starts accepting commands from * the client. Otherwise an error is returned and the clients needs to try a new password. Note * that for the high performance nature of Redis it is possible to try a lot of passwords in * parallel in very short time, so make sure to generate a strong and very long password so that * this attack is infeasible. * @param password * @return Status code reply */ @Override public String auth(final String password) { checkIsInMultiOrPipeline(); client.auth(password); return client.getStatusCodeReply(); } public Pipeline pipelined() { pipeline = new Pipeline(); pipeline.setClient(client); return pipeline; } @Override public Long zcount(final byte[] key, final double min, final double max) { return zcount(key, toByteArray(min), toByteArray(max)); } @Override public Long zcount(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); client.zcount(key, min, max); return client.getIntegerReply(); } /** * Return the all the elements in the sorted set at key with a score between min and max * (including elements with score equal to min or max). * <p> * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). * <p> * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. * <p> * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. * <p> * <b>Exclusive intervals and infinity</b> * <p> * min and max can be -inf and +inf, so that you are not required to know what's the greatest or * smallest element in order to take, for instance, elements "up to a given value". * <p> * Also while the interval is for default closed (inclusive) it's possible to specify open * intervals prefixing the score with a "(" character, so for instance: * <p> * {@code ZRANGEBYSCORE zset (1.3 5} * <p> * Will return all the values with score &gt; 1.3 and &lt;= 5, while for instance: * <p> * {@code ZRANGEBYSCORE zset (5 (10} * <p> * Will return all the values with score &gt; 5 and &lt; 10 (5 and 10 excluded). * <p> * <b>Time complexity:</b> * <p> * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) * @see #zrangeByScore(byte[], double, double) * @see #zrangeByScore(byte[], double, double, int, int) * @see #zrangeByScoreWithScores(byte[], double, double) * @see #zrangeByScoreWithScores(byte[], double, double, int, int) * @see #zcount(byte[], double, double) * @param key * @param min * @param max * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max) { return zrangeByScore(key, toByteArray(min), toByteArray(max)); } @Override public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); client.zrangeByScore(key, min, max); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Return the all the elements in the sorted set at key with a score between min and max * (including elements with score equal to min or max). * <p> * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). * <p> * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. * <p> * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. * <p> * <b>Exclusive intervals and infinity</b> * <p> * min and max can be -inf and +inf, so that you are not required to know what's the greatest or * smallest element in order to take, for instance, elements "up to a given value". * <p> * Also while the interval is for default closed (inclusive) it's possible to specify open * intervals prefixing the score with a "(" character, so for instance: * <p> * {@code ZRANGEBYSCORE zset (1.3 5} * <p> * Will return all the values with score &gt; 1.3 and &lt;= 5, while for instance: * <p> * {@code ZRANGEBYSCORE zset (5 (10} * <p> * Will return all the values with score &gt; 5 and &lt; 10 (5 and 10 excluded). * <p> * <b>Time complexity:</b> * <p> * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) * @see #zrangeByScore(byte[], double, double) * @see #zrangeByScore(byte[], double, double, int, int) * @see #zrangeByScoreWithScores(byte[], double, double) * @see #zrangeByScoreWithScores(byte[], double, double, int, int) * @see #zcount(byte[], double, double) * @param key * @param min * @param max * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override public Set<byte[]> zrangeByScore(final byte[] key, final double min, final double max, final int offset, final int count) { return zrangeByScore(key, toByteArray(min), toByteArray(max), offset, count); } @Override public Set<byte[]> zrangeByScore(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { checkIsInMultiOrPipeline(); client.zrangeByScore(key, min, max, offset, count); return SetFromList.of(client.getBinaryMultiBulkReply()); } /** * Return the all the elements in the sorted set at key with a score between min and max * (including elements with score equal to min or max). * <p> * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). * <p> * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. * <p> * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. * <p> * <b>Exclusive intervals and infinity</b> * <p> * min and max can be -inf and +inf, so that you are not required to know what's the greatest or * smallest element in order to take, for instance, elements "up to a given value". * <p> * Also while the interval is for default closed (inclusive) it's possible to specify open * intervals prefixing the score with a "(" character, so for instance: * <p> * {@code ZRANGEBYSCORE zset (1.3 5} * <p> * Will return all the values with score &gt; 1.3 and &lt;= 5, while for instance: * <p> * {@code ZRANGEBYSCORE zset (5 (10} * <p> * Will return all the values with score &gt; 5 and &lt; 10 (5 and 10 excluded). * <p> * <b>Time complexity:</b> * <p> * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) * @see #zrangeByScore(byte[], double, double) * @see #zrangeByScore(byte[], double, double, int, int) * @see #zrangeByScoreWithScores(byte[], double, double) * @see #zrangeByScoreWithScores(byte[], double, double, int, int) * @see #zcount(byte[], double, double) * @param key * @param min * @param max * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max) { return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max)); } @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); client.zrangeByScoreWithScores(key, min, max); return getBinaryTupledSet(); } /** * Return the all the elements in the sorted set at key with a score between min and max * (including elements with score equal to min or max). * <p> * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). * <p> * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. * <p> * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. * <p> * <b>Exclusive intervals and infinity</b> * <p> * min and max can be -inf and +inf, so that you are not required to know what's the greatest or * smallest element in order to take, for instance, elements "up to a given value". * <p> * Also while the interval is for default closed (inclusive) it's possible to specify open * intervals prefixing the score with a "(" character, so for instance: * <p> * {@code ZRANGEBYSCORE zset (1.3 5} * <p> * Will return all the values with score &gt; 1.3 and &lt;= 5, while for instance: * <p> * {@code ZRANGEBYSCORE zset (5 (10} * <p> * Will return all the values with score &gt; 5 and &lt; 10 (5 and 10 excluded). * <p> * <b>Time complexity:</b> * <p> * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) * @see #zrangeByScore(byte[], double, double) * @see #zrangeByScore(byte[], double, double, int, int) * @see #zrangeByScoreWithScores(byte[], double, double) * @see #zrangeByScoreWithScores(byte[], double, double, int, int) * @see #zcount(byte[], double, double) * @param key * @param min * @param max * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final double min, final double max, final int offset, final int count) { return zrangeByScoreWithScores(key, toByteArray(min), toByteArray(max), offset, count); } @Override public Set<Tuple> zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { checkIsInMultiOrPipeline(); client.zrangeByScoreWithScores(key, min, max, offset, count); return getBinaryTupledSet(); } private Set<Tuple> getBinaryTupledSet() { checkIsInMultiOrPipeline(); List<byte[]> membersWithScores = client.getBinaryMultiBulkReply(); if (membersWithScores.size() == 0) { return Collections.emptySet(); } Set<Tuple> set = new LinkedHashSet<Tuple>(membersWithScores.size() / 2, 1.0f); Iterator<byte[]> iterator = membersWithScores.iterator(); while (iterator.hasNext()) { set.add(new Tuple(iterator.next(), Double.valueOf(SafeEncoder.encode(iterator.next())))); } return set; } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min) { return zrevrangeByScore(key, toByteArray(max), toByteArray(min)); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { checkIsInMultiOrPipeline(); client.zrevrangeByScore(key, max, min); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, final int count) { return zrevrangeByScore(key, toByteArray(max), toByteArray(min), offset, count); } @Override public Set<byte[]> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, final int offset, final int count) { checkIsInMultiOrPipeline(); client.zrevrangeByScore(key, max, min, offset, count); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { return zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min)); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, final int offset, final int count) { return zrevrangeByScoreWithScores(key, toByteArray(max), toByteArray(min), offset, count); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { checkIsInMultiOrPipeline(); client.zrevrangeByScoreWithScores(key, max, min); return getBinaryTupledSet(); } @Override public Set<Tuple> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min, final int offset, final int count) { checkIsInMultiOrPipeline(); client.zrevrangeByScoreWithScores(key, max, min, offset, count); return getBinaryTupledSet(); } /** * Remove all elements in the sorted set at key with rank between start and end. Start and end are * 0-based with rank 0 being the element with the lowest score. Both start and end can be negative * numbers, where they indicate offsets starting at the element with the highest rank. For * example: -1 is the element with the highest score, -2 the element with the second highest score * and so forth. * <p> * <b>Time complexity:</b> O(log(N))+O(M) with N being the number of elements in the sorted set * and M the number of elements removed by the operation */ @Override public Long zremrangeByRank(final byte[] key, final long start, final long end) { checkIsInMultiOrPipeline(); client.zremrangeByRank(key, start, end); return client.getIntegerReply(); } /** * Remove all the elements in the sorted set at key with a score between min and max (including * elements with score equal to min or max). * <p> * <b>Time complexity:</b> * <p> * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements removed by the operation * @param key * @param start * @param end * @return Integer reply, specifically the number of elements removed. */ @Override public Long zremrangeByScore(final byte[] key, final double start, final double end) { return zremrangeByScore(key, toByteArray(start), toByteArray(end)); } @Override public Long zremrangeByScore(final byte[] key, final byte[] start, final byte[] end) { checkIsInMultiOrPipeline(); client.zremrangeByScore(key, start, end); return client.getIntegerReply(); } /** * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys * and the other (optional) arguments. * <p> * As the terms imply, the {@link #zinterstore(byte[], byte[]...)} ZINTERSTORE} command requires * an element to be present in each of the given inputs to be inserted in the result. The {@link * #zunionstore(byte[], byte[]...)} command inserts all elements across all inputs. * <p> * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means * that the score of each element in the sorted set is first multiplied by this weight before * being passed to the aggregation. When this option is not given, all weights default to 1. * <p> * With the AGGREGATE option, it's possible to specify how the results of the union or * intersection are aggregated. This option defaults to SUM, where the score of an element is * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the * resulting set will contain the minimum or maximum score of an element across the inputs where * it exists. * <p> * <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input * sorted sets, and M being the number of elements in the resulting sorted set * @see #zunionstore(byte[], byte[]...) * @see #zunionstore(byte[], ZParams, byte[]...) * @see #zinterstore(byte[], byte[]...) * @see #zinterstore(byte[], ZParams, byte[]...) * @param dstkey * @param sets * @return Integer reply, specifically the number of elements in the sorted set at dstkey */ @Override public Long zunionstore(final byte[] dstkey, final byte[]... sets) { checkIsInMultiOrPipeline(); client.zunionstore(dstkey, sets); return client.getIntegerReply(); } /** * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys * and the other (optional) arguments. * <p> * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an * element to be present in each of the given inputs to be inserted in the result. The {@link * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. * <p> * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means * that the score of each element in the sorted set is first multiplied by this weight before * being passed to the aggregation. When this option is not given, all weights default to 1. * <p> * With the AGGREGATE option, it's possible to specify how the results of the union or * intersection are aggregated. This option defaults to SUM, where the score of an element is * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the * resulting set will contain the minimum or maximum score of an element across the inputs where * it exists. * <p> * <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input * sorted sets, and M being the number of elements in the resulting sorted set * @see #zunionstore(byte[], byte[]...) * @see #zunionstore(byte[], ZParams, byte[]...) * @see #zinterstore(byte[], byte[]...) * @see #zinterstore(byte[], ZParams, byte[]...) * @param dstkey * @param sets * @param params * @return Integer reply, specifically the number of elements in the sorted set at dstkey */ @Override public Long zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { checkIsInMultiOrPipeline(); client.zunionstore(dstkey, params, sets); return client.getIntegerReply(); } /** * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys * and the other (optional) arguments. * <p> * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an * element to be present in each of the given inputs to be inserted in the result. The {@link * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. * <p> * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means * that the score of each element in the sorted set is first multiplied by this weight before * being passed to the aggregation. When this option is not given, all weights default to 1. * <p> * With the AGGREGATE option, it's possible to specify how the results of the union or * intersection are aggregated. This option defaults to SUM, where the score of an element is * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the * resulting set will contain the minimum or maximum score of an element across the inputs where * it exists. * <p> * <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input * sorted sets, and M being the number of elements in the resulting sorted set * @see #zunionstore(byte[], byte[]...) * @see #zunionstore(byte[], ZParams, byte[]...) * @see #zinterstore(byte[], byte[]...) * @see #zinterstore(byte[], ZParams, byte[]...) * @param dstkey * @param sets * @return Integer reply, specifically the number of elements in the sorted set at dstkey */ @Override public Long zinterstore(final byte[] dstkey, final byte[]... sets) { checkIsInMultiOrPipeline(); client.zinterstore(dstkey, sets); return client.getIntegerReply(); } /** * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys * and the other (optional) arguments. * <p> * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an * element to be present in each of the given inputs to be inserted in the result. The {@link * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. * <p> * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means * that the score of each element in the sorted set is first multiplied by this weight before * being passed to the aggregation. When this option is not given, all weights default to 1. * <p> * With the AGGREGATE option, it's possible to specify how the results of the union or * intersection are aggregated. This option defaults to SUM, where the score of an element is * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the * resulting set will contain the minimum or maximum score of an element across the inputs where * it exists. * <p> * <b>Time complexity:</b> O(N) + O(M log(M)) with N being the sum of the sizes of the input * sorted sets, and M being the number of elements in the resulting sorted set * @see #zunionstore(byte[], byte[]...) * @see #zunionstore(byte[], ZParams, byte[]...) * @see #zinterstore(byte[], byte[]...) * @see #zinterstore(byte[], ZParams, byte[]...) * @param dstkey * @param sets * @param params * @return Integer reply, specifically the number of elements in the sorted set at dstkey */ @Override public Long zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { checkIsInMultiOrPipeline(); client.zinterstore(dstkey, params, sets); return client.getIntegerReply(); } @Override public Long zlexcount(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); client.zlexcount(key, min, max); return client.getIntegerReply(); } @Override public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); client.zrangeByLex(key, min, max); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Set<byte[]> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { checkIsInMultiOrPipeline(); client.zrangeByLex(key, min, max, offset, count); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { checkIsInMultiOrPipeline(); client.zrevrangeByLex(key, max, min); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Set<byte[]> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { checkIsInMultiOrPipeline(); client.zrevrangeByLex(key, max, min, offset, count); return SetFromList.of(client.getBinaryMultiBulkReply()); } @Override public Long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); client.zremrangeByLex(key, min, max); return client.getIntegerReply(); } /** * Synchronously save the DB on disk. * <p> * Save the whole dataset on disk (this means that all the databases are saved, as well as keys * with an EXPIRE set (the expire is preserved). The server hangs while the saving is not * completed, no connection is served in the meanwhile. An OK code is returned when the DB was * fully stored in disk. * <p> * The background variant of this command is {@link #bgsave() BGSAVE} that is able to perform the * saving in the background while the server continues serving other clients. * <p> * @return Status code reply */ @Override public String save() { client.save(); return client.getStatusCodeReply(); } /** * Asynchronously save the DB on disk. * <p> * Save the DB in background. The OK code is immediately returned. Redis forks, the parent * continues to server the clients, the child saves the DB on disk then exit. A client my be able * to check if the operation succeeded using the LASTSAVE command. * @return Status code reply */ @Override public String bgsave() { client.bgsave(); return client.getStatusCodeReply(); } /** * Rewrite the append only file in background when it gets too big. Please for detailed * information about the Redis Append Only File check the <a * href="http://redis.io/topics/persistence#append-only-file">Append Only File Howto</a>. * <p> * BGREWRITEAOF rewrites the Append Only File in background when it gets too big. The Redis Append * Only File is a Journal, so every operation modifying the dataset is logged in the Append Only * File (and replayed at startup). This means that the Append Only File always grows. In order to * rebuild its content the BGREWRITEAOF creates a new version of the append only file starting * directly form the dataset in memory in order to guarantee the generation of the minimal number * of commands needed to rebuild the database. * <p> * @return Status code reply */ @Override public String bgrewriteaof() { client.bgrewriteaof(); return client.getStatusCodeReply(); } /** * Return the UNIX time stamp of the last successfully saving of the dataset on disk. * <p> * Return the UNIX TIME of the last DB save executed with success. A client may check if a * {@link #bgsave() BGSAVE} command succeeded reading the LASTSAVE value, then issuing a BGSAVE * command and checking at regular intervals every N seconds if LASTSAVE changed. * @return Integer reply, specifically an UNIX time stamp. */ @Override public Long lastsave() { client.lastsave(); return client.getIntegerReply(); } /** * Synchronously save the DB on disk, then shutdown the server. * <p> * Stop all the clients, save the DB, then quit the server. This commands makes sure that the DB * is switched off without the lost of any data. This is not guaranteed if the client uses simply * {@link #save() SAVE} and then {@link #quit() QUIT} because other clients may alter the DB data * between the two commands. * @return Status code reply on error. On success nothing is returned since the server quits and * the connection is closed. */ @Override public String shutdown() { client.shutdown(); String status; try { status = client.getStatusCodeReply(); } catch (JedisException ex) { status = null; } return status; } /** * Provide information and statistics about the server. * <p> * The info command returns different information and statistics about the server in an format * that's simple to parse by computers and easy to read by humans. * <p> * <b>Format of the returned String:</b> * <p> * All the fields are in the form field:value * * <pre> * edis_version:0.07 * connected_clients:1 * connected_slaves:0 * used_memory:3187 * changes_since_last_save:0 * last_save_time:1237655729 * total_connections_received:1 * total_commands_processed:1 * uptime_in_seconds:25 * uptime_in_days:0 * </pre> * * <b>Notes</b> * <p> * used_memory is returned in bytes, and is the total number of bytes allocated by the program * using malloc. * <p> * uptime_in_days is redundant since the uptime in seconds contains already the full uptime * information, this field is only mainly present for humans. * <p> * changes_since_last_save does not refer to the number of key changes, but to the number of * operations that produced some kind of change in the dataset. * <p> * @return Bulk reply */ @Override public String info() { client.info(); return client.getBulkReply(); } @Override public String info(final String section) { client.info(section); return client.getBulkReply(); } /** * Dump all the received requests in real time. * <p> * MONITOR is a debugging command that outputs the whole sequence of commands received by the * Redis server. is very handy in order to understand what is happening into the database. This * command is used directly via telnet. * @param jedisMonitor */ public void monitor(final JedisMonitor jedisMonitor) { client.monitor(); client.getStatusCodeReply(); jedisMonitor.proceed(client); } /** * Change the replication settings. * <p> * The SLAVEOF command can change the replication settings of a slave on the fly. If a Redis * server is arleady acting as slave, the command SLAVEOF NO ONE will turn off the replicaiton * turning the Redis server into a MASTER. In the proper form SLAVEOF hostname port will make the * server a slave of the specific server listening at the specified hostname and port. * <p> * If a server is already a slave of some master, SLAVEOF hostname port will stop the replication * against the old server and start the synchrnonization against the new one discarding the old * dataset. * <p> * The form SLAVEOF no one will stop replication turning the server into a MASTER but will not * discard the replication. So if the old master stop working it is possible to turn the slave * into a master and set the application to use the new master in read/write. Later when the other * Redis server will be fixed it can be configured in order to work as slave. * <p> * @param host * @param port * @return Status code reply */ @Override public String slaveof(final String host, final int port) { client.slaveof(host, port); return client.getStatusCodeReply(); } @Override public String slaveofNoOne() { client.slaveofNoOne(); return client.getStatusCodeReply(); } /** * Retrieve the configuration of a running Redis server. Not all the configuration parameters are * supported. * <p> * CONFIG GET returns the current configuration parameters. This sub command only accepts a single * argument, that is glob style pattern. All the configuration parameters matching this parameter * are reported as a list of key-value pairs. * <p> * <b>Example:</b> * * <pre> * $ redis-cli config get '*' * 1. "dbfilename" * 2. "dump.rdb" * 3. "requirepass" * 4. (nil) * 5. "masterauth" * 6. (nil) * 7. "maxmemory" * 8. "0\n" * 9. "appendfsync" * 10. "everysec" * 11. "save" * 12. "3600 1 300 100 60 10000" * * $ redis-cli config get 'm*' * 1. "masterauth" * 2. (nil) * 3. "maxmemory" * 4. "0\n" * </pre> * @param pattern * @return Bulk reply. */ @Override public List<byte[]> configGet(final byte[] pattern) { client.configGet(pattern); return client.getBinaryMultiBulkReply(); } /** * Reset the stats returned by INFO * @return */ @Override public String configResetStat() { client.configResetStat(); return client.getStatusCodeReply(); } /** * Alter the configuration of a running Redis server. Not all the configuration parameters are * supported. * <p> * The list of configuration parameters supported by CONFIG SET can be obtained issuing a * {@link #configGet(byte[]) CONFIG GET *} command. * <p> * The configuration set using CONFIG SET is immediately loaded by the Redis server that will * start acting as specified starting from the next command. * <p> * <b>Parameters value format</b> * <p> * The value of the configuration parameter is the same as the one of the same parameter in the * Redis configuration file, with the following exceptions: * <p> * <ul> * <li>The save paramter is a list of space-separated integers. Every pair of integers specify the * time and number of changes limit to trigger a save. For instance the command CONFIG SET save * "3600 10 60 10000" will configure the server to issue a background saving of the RDB file every * 3600 seconds if there are at least 10 changes in the dataset, and every 60 seconds if there are * at least 10000 changes. To completely disable automatic snapshots just set the parameter as an * empty string. * <li>All the integer parameters representing memory are returned and accepted only using bytes * as unit. * </ul> * @param parameter * @param value * @return Status code reply */ @Override public byte[] configSet(final byte[] parameter, final byte[] value) { client.configSet(parameter, value); return client.getBinaryBulkReply(); } public boolean isConnected() { return client.isConnected(); } @Override public Long strlen(final byte[] key) { client.strlen(key); return client.getIntegerReply(); } public void sync() { client.sync(); } @Override public Long lpushx(final byte[] key, final byte[]... string) { client.lpushx(key, string); return client.getIntegerReply(); } /** * Undo a {@link #expire(byte[], int) expire} at turning the expire key into a normal key. * <p> * Time complexity: O(1) * @param key * @return Integer reply, specifically: 1: the key is now persist. 0: the key is not persist (only * happens when key not set). */ @Override public Long persist(final byte[] key) { client.persist(key); return client.getIntegerReply(); } @Override public Long rpushx(final byte[] key, final byte[]... string) { client.rpushx(key, string); return client.getIntegerReply(); } @Override public byte[] echo(final byte[] string) { client.echo(string); return client.getBinaryBulkReply(); } @Override public Long linsert(final byte[] key, final LIST_POSITION where, final byte[] pivot, final byte[] value) { client.linsert(key, where, pivot, value); return client.getIntegerReply(); } @Override public String debug(final DebugParams params) { client.debug(params); return client.getStatusCodeReply(); } public Client getClient() { return client; } /** * Pop a value from a list, push it to another list and return it; or block until one is available * @param source * @param destination * @param timeout * @return the element */ @Override public byte[] brpoplpush(byte[] source, byte[] destination, int timeout) { client.brpoplpush(source, destination, timeout); client.setTimeoutInfinite(); try { return client.getBinaryBulkReply(); } finally { client.rollbackTimeout(); } } /** * Sets or clears the bit at offset in the string value stored at key * @param key * @param offset * @param value * @return */ @Override public Boolean setbit(byte[] key, long offset, boolean value) { client.setbit(key, offset, value); return client.getIntegerReply() == 1; } @Override public Boolean setbit(byte[] key, long offset, byte[] value) { client.setbit(key, offset, value); return client.getIntegerReply() == 1; } /** * Returns the bit value at offset in the string value stored at key * @param key * @param offset * @return */ @Override public Boolean getbit(byte[] key, long offset) { client.getbit(key, offset); return client.getIntegerReply() == 1; } public Long bitpos(final byte[] key, final boolean value) { return bitpos(key, value, new BitPosParams()); } public Long bitpos(final byte[] key, final boolean value, final BitPosParams params) { client.bitpos(key, value, params); return client.getIntegerReply(); } @Override public Long setrange(byte[] key, long offset, byte[] value) { client.setrange(key, offset, value); return client.getIntegerReply(); } @Override public byte[] getrange(byte[] key, long startOffset, long endOffset) { client.getrange(key, startOffset, endOffset); return client.getBinaryBulkReply(); } @Override public Long publish(byte[] channel, byte[] message) { client.publish(channel, message); return client.getIntegerReply(); } @Override public void subscribe(BinaryJedisPubSub jedisPubSub, byte[]... channels) { client.setTimeoutInfinite(); try { jedisPubSub.proceed(client, channels); } finally { client.rollbackTimeout(); } } @Override public void psubscribe(BinaryJedisPubSub jedisPubSub, byte[]... patterns) { client.setTimeoutInfinite(); try { jedisPubSub.proceedWithPatterns(client, patterns); } finally { client.rollbackTimeout(); } } @Override public int getDB() { return client.getDB(); } /** * Evaluates scripts using the Lua interpreter built into Redis starting from version 2.6.0. * <p> * @return Script result */ @Override public Object eval(byte[] script, List<byte[]> keys, List<byte[]> args) { return eval(script, toByteArray(keys.size()), getParamsWithBinary(keys, args)); } protected static byte[][] getParamsWithBinary(List<byte[]> keys, List<byte[]> args) { final int keyCount = keys.size(); final int argCount = args.size(); byte[][] params = new byte[keyCount + argCount][]; for (int i = 0; i < keyCount; i++) params[i] = keys.get(i); for (int i = 0; i < argCount; i++) params[keyCount + i] = args.get(i); return params; } @Override public Object eval(byte[] script, byte[] keyCount, byte[]... params) { client.setTimeoutInfinite(); try { client.eval(script, keyCount, params); return client.getOne(); } finally { client.rollbackTimeout(); } } @Override public Object eval(byte[] script, int keyCount, byte[]... params) { return eval(script, toByteArray(keyCount), params); } @Override public Object eval(byte[] script) { return eval(script, 0); } @Override public Object evalsha(byte[] sha1) { return evalsha(sha1, 1); } @Override public Object evalsha(byte[] sha1, List<byte[]> keys, List<byte[]> args) { return evalsha(sha1, keys.size(), getParamsWithBinary(keys, args)); } @Override public Object evalsha(byte[] sha1, int keyCount, byte[]... params) { client.setTimeoutInfinite(); try { client.evalsha(sha1, keyCount, params); return client.getOne(); } finally { client.rollbackTimeout(); } } @Override public String scriptFlush() { client.scriptFlush(); return client.getStatusCodeReply(); } public Long scriptExists(byte[] sha1) { byte[][] a = new byte[1][]; a[0] = sha1; return scriptExists(a).get(0); } @Override public List<Long> scriptExists(byte[]... sha1) { client.scriptExists(sha1); return client.getIntegerMultiBulkReply(); } @Override public byte[] scriptLoad(byte[] script) { client.scriptLoad(script); return client.getBinaryBulkReply(); } @Override public String scriptKill() { client.scriptKill(); return client.getStatusCodeReply(); } @Override public String slowlogReset() { client.slowlogReset(); return client.getBulkReply(); } @Override public Long slowlogLen() { client.slowlogLen(); return client.getIntegerReply(); } @Override public List<byte[]> slowlogGetBinary() { client.slowlogGet(); return client.getBinaryMultiBulkReply(); } @Override public List<byte[]> slowlogGetBinary(long entries) { client.slowlogGet(entries); return client.getBinaryMultiBulkReply(); } @Override public Long objectRefcount(byte[] key) { client.objectRefcount(key); return client.getIntegerReply(); } @Override public byte[] objectEncoding(byte[] key) { client.objectEncoding(key); return client.getBinaryBulkReply(); } @Override public Long objectIdletime(byte[] key) { client.objectIdletime(key); return client.getIntegerReply(); } @Override public Long bitcount(final byte[] key) { client.bitcount(key); return client.getIntegerReply(); } @Override public Long bitcount(final byte[] key, long start, long end) { client.bitcount(key, start, end); return client.getIntegerReply(); } @Override public Long bitop(BitOP op, final byte[] destKey, byte[]... srcKeys) { client.bitop(op, destKey, srcKeys); return client.getIntegerReply(); } public byte[] dump(final byte[] key) { checkIsInMultiOrPipeline(); client.dump(key); return client.getBinaryBulkReply(); } public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { checkIsInMultiOrPipeline(); client.restore(key, ttl, serializedValue); return client.getStatusCodeReply(); } /** * Set a timeout on the specified key. After the timeout the key will be automatically deleted by * the server. A key with an associated timeout is said to be volatile in Redis terminology. * <p> * Voltile keys are stored on disk like the other keys, the timeout is persistent too like all the * other aspects of the dataset. Saving a dataset containing expires and stopping the server does * not stop the flow of time as Redis stores on disk the time when the key will no longer be * available as Unix time, and not the remaining milliseconds. * <p> * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire * set. It is also possible to undo the expire at all turning the key into a normal key using the * {@link #persist(byte[]) PERSIST} command. * <p> * Time complexity: O(1) * @see <ahref="http://redis.io/commands/pexpire">PEXPIRE Command</a> * @param key * @param milliseconds * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since * the key already has an associated timeout (this may happen only in Redis versions < * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. */ @Override public Long pexpire(final byte[] key, final long milliseconds) { checkIsInMultiOrPipeline(); client.pexpire(key, milliseconds); return client.getIntegerReply(); } @Override public Long pexpireAt(final byte[] key, final long millisecondsTimestamp) { checkIsInMultiOrPipeline(); client.pexpireAt(key, millisecondsTimestamp); return client.getIntegerReply(); } public Long pttl(final byte[] key) { checkIsInMultiOrPipeline(); client.pttl(key); return client.getIntegerReply(); } /** * PSETEX works exactly like {@link #setex(byte[], int, byte[])} with the sole difference that the * expire time is specified in milliseconds instead of seconds. Time complexity: O(1) * @param key * @param milliseconds * @param value * @return Status code reply */ public String psetex(final byte[] key, final long milliseconds, final byte[] value) { checkIsInMultiOrPipeline(); client.psetex(key, milliseconds, value); return client.getStatusCodeReply(); } public String clientKill(final byte[] client) { checkIsInMultiOrPipeline(); this.client.clientKill(client); return this.client.getStatusCodeReply(); } public String clientGetname() { checkIsInMultiOrPipeline(); client.clientGetname(); return client.getBulkReply(); } public String clientList() { checkIsInMultiOrPipeline(); client.clientList(); return client.getBulkReply(); } public String clientSetname(final byte[] name) { checkIsInMultiOrPipeline(); client.clientSetname(name); return client.getBulkReply(); } public List<String> time() { checkIsInMultiOrPipeline(); client.time(); return client.getMultiBulkReply(); } public String migrate(final byte[] host, final int port, final byte[] key, final int destinationDb, final int timeout) { checkIsInMultiOrPipeline(); client.migrate(host, port, key, destinationDb, timeout); return client.getStatusCodeReply(); } /** * Syncrhonous replication of Redis as described here: http://antirez.com/news/66 Since Java * Object class has implemented "wait" method, we cannot use it, so I had to change the name of * the method. Sorry :S */ @Override public Long waitReplicas(int replicas, long timeout) { checkIsInMultiOrPipeline(); client.waitReplicas(replicas, timeout); return client.getIntegerReply(); } @Override public Long pfadd(final byte[] key, final byte[]... elements) { checkIsInMultiOrPipeline(); client.pfadd(key, elements); return client.getIntegerReply(); } @Override public long pfcount(final byte[] key) { checkIsInMultiOrPipeline(); client.pfcount(key); return client.getIntegerReply(); } @Override public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) { checkIsInMultiOrPipeline(); client.pfmerge(destkey, sourcekeys); return client.getStatusCodeReply(); } @Override public Long pfcount(byte[]... keys) { checkIsInMultiOrPipeline(); client.pfcount(keys); return client.getIntegerReply(); } public ScanResult<byte[]> scan(final byte[] cursor) { return scan(cursor, new ScanParams()); } public ScanResult<byte[]> scan(final byte[] cursor, final ScanParams params) { checkIsInMultiOrPipeline(); client.scan(cursor, params); List<Object> result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); List<byte[]> rawResults = (List<byte[]>) result.get(1); return new ScanResult<byte[]>(newcursor, rawResults); } public ScanResult<Map.Entry<byte[], byte[]>> hscan(final byte[] key, final byte[] cursor) { return hscan(key, cursor, new ScanParams()); } public ScanResult<Map.Entry<byte[], byte[]>> hscan(final byte[] key, final byte[] cursor, final ScanParams params) { checkIsInMultiOrPipeline(); client.hscan(key, cursor, params); List<Object> result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); List<Map.Entry<byte[], byte[]>> results = new ArrayList<Map.Entry<byte[], byte[]>>(); List<byte[]> rawResults = (List<byte[]>) result.get(1); Iterator<byte[]> iterator = rawResults.iterator(); while (iterator.hasNext()) { results.add(new AbstractMap.SimpleEntry<byte[], byte[]>(iterator.next(), iterator.next())); } return new ScanResult<Map.Entry<byte[], byte[]>>(newcursor, results); } public ScanResult<byte[]> sscan(final byte[] key, final byte[] cursor) { return sscan(key, cursor, new ScanParams()); } public ScanResult<byte[]> sscan(final byte[] key, final byte[] cursor, final ScanParams params) { checkIsInMultiOrPipeline(); client.sscan(key, cursor, params); List<Object> result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); List<byte[]> rawResults = (List<byte[]>) result.get(1); return new ScanResult<byte[]>(newcursor, rawResults); } public ScanResult<Tuple> zscan(final byte[] key, final byte[] cursor) { return zscan(key, cursor, new ScanParams()); } public ScanResult<Tuple> zscan(final byte[] key, final byte[] cursor, final ScanParams params) { checkIsInMultiOrPipeline(); client.zscan(key, cursor, params); List<Object> result = client.getObjectMultiBulkReply(); byte[] newcursor = (byte[]) result.get(0); List<Tuple> results = new ArrayList<Tuple>(); List<byte[]> rawResults = (List<byte[]>) result.get(1); Iterator<byte[]> iterator = rawResults.iterator(); while (iterator.hasNext()) { results.add(new Tuple(iterator.next(), Double.valueOf(SafeEncoder.encode(iterator.next())))); } return new ScanResult<Tuple>(newcursor, results); } /** * A decorator to implement Set from List. Assume that given List do not contains duplicated * values. The resulting set displays the same ordering, concurrency, and performance * characteristics as the backing list. This class should be used only for Redis commands which * return Set result. * @param <E> */ protected static class SetFromList<E> extends AbstractSet<E> { private final List<E> list; private SetFromList(List<E> list) { if (list == null) { throw new NullPointerException("list"); } this.list = list; } @Override public void clear() { list.clear(); } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public boolean remove(Object o) { return list.remove(o); } @Override public boolean add(E e) { return !contains(e) && list.add(e); } @Override public Iterator<E> iterator() { return list.iterator(); } @Override public Object[] toArray() { return list.toArray(); } @Override public <T> T[] toArray(T[] a) { return list.toArray(a); } public String toString() { return list.toString(); } public int hashCode() { return list.hashCode(); } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Set)) { return false; } Collection<?> c = (Collection<?>) o; if (c.size() != size()) { return false; } return containsAll(c); } @Override public boolean containsAll(Collection<?> c) { return list.containsAll(c); } @Override public boolean removeAll(Collection<?> c) { return list.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return list.retainAll(c); } protected static <E> SetFromList<E> of(List<E> list) { return new SetFromList<E>(list); } } }
mit
anagav/TinkerRocks
src/main/java/com/tinkerrocks/process/traversal/Predicate.java
927
package com.tinkerrocks.process.traversal; import org.apache.tinkerpop.gremlin.process.traversal.P; import java.util.function.BiPredicate; /** <p> Class with predicate of string Ignore case contains</p> * Created by ashishn on 8/16/15. */ public class Predicate<V> extends P<V> { public Predicate(BiPredicate<V, V> biPredicate, V value) { super(biPredicate, value); } /** * <p> method to check if HasContainer string is part of the property. </p> * * @param value incoming value * @param <V> type of value * @return Predicate to match string contains */ @SuppressWarnings("unchecked") public static <V> P<V> stringContains(final V value) { if (!(value instanceof String)) { throw new IllegalArgumentException("cannot compare String and class: " + value.getClass()); } return new P(StringContains.subString, value); } }
mit
felipexpert/truco
src/miquilini/felipe/intermediario/carta/Carta.java
3592
package miquilini.felipe.intermediario.carta; import java.util.HashSet; import java.util.List; import java.util.Set; public enum Carta { PAUS_4(0, "Quatro de Paus", 1), COPAS_4(1, "Quatro de Copas", 1), ESPADAS_4(2, "Quatro de Espadas", 1), OUROS_4(3, "Quatro de Ouros", 1), PAUS_5(4, "Cinco de Paus", 2), COPAS_5(5, "Cinco de Copas", 2), ESPADAS_5(6, "Cinco de Espadas", 2), OUROS_5(7, "Cinco de Ouros", 2), PAUS_6(8, "Seis de Paus", 3), COPAS_6(9, "Seis de Copas", 3), ESPADAS_6(10, "Seis de Espadas", 3), OUROS_6(11, "Seis de Ouros", 3), PAUS_7(12, "Sete de Paus", 4), COPAS_7(13, "Sete de Copas", 4), ESPADAS_7(14, "Sete de Espadas", 4), OUROS_7(15, "Sete de Ouros", 4), PAUS_Q(16, "Dama de Paus", 5), COPAS_Q(17, "Dama de Copas", 5), ESPADAS_Q(18, "Dama de Espadas", 5), OUROS_Q(19, "Dama de Ouros", 5), PAUS_J(20, "Valete de Paus", 6), COPAS_J(21, "Valete de Copas", 6), ESPADAS_J(22, "Valete de Espadas", 6), OUROS_J(23, "Valete de Ouros", 6), PAUS_K(24, "Rei de Paus", 7), COPAS_K(25, "Rei de Copas", 7), ESPADAS_K(26, "Rei de Espadas", 7), OUROS_K(27, "Rei de Ouros", 7), PAUS_A(28, "Ás de Paus", 8), COPAS_A(29, "Ás de Copas", 8), ESPADAS_A(30, "Ás de Espadas", 8), OUROS_A(31, "Ás de Ouros", 8), PAUS_2(32, "Dois de Paus", 9), COPAS_2(33, "Dois de Copas", 9), ESPADAS_2(34, "Dois de Espadas", 9), OUROS_2(35, "Dois de Ouros", 9), PAUS_3(36, "Três de Paus", 10), COPAS_3(37, "Três de Copas", 10), ESPADAS_3(38, "Três de Espadas", 10), OUROS_3(39, "Três de Ouros", 10), INCOBERTO(40, "Incoberto", 0); private final int codigo; private int forcaBruta; private int adicionalManilha; private String nome; Carta(int codigo, String nome, int forcaBruta) { this.codigo = codigo; this.nome = nome; this.forcaBruta = forcaBruta; adicionalManilha = 0; } public static void gerarManilha(Carta vira) { //para zerar a manilha da rodada anterior Carta[] todasCartas = Carta.values(); for(Carta carta : todasCartas) { carta.adicionalManilha = 0; } int codPausDaManilha = 0; if(vira.codigo < 36) codPausDaManilha = vira.codigo + 4 - (vira.codigo % 4); for(int i = 0, j = 13; i < 4; i++, j--) { todasCartas[codPausDaManilha + i].adicionalManilha = j; } } public int getForca() { return forcaBruta + adicionalManilha; } /** * * @param cartas * @return * @throws IllegalArgumentException */ public static Set<Carta> pegarMaisFortes(List<Carta> cartas) throws IllegalArgumentException{ if(cartas == null || cartas.size() == 0) throw new IllegalArgumentException(); Set<Carta> maisFortes = new HashSet<>(); for(Carta ca : cartas) { if(maisFortes.size() == 0) { maisFortes.add(ca); continue; } int forcaDaCartaMaisForte = maisFortes.iterator().next().getForca(); int forcaDaCartaCA = ca.getForca(); if(forcaDaCartaMaisForte == forcaDaCartaCA) { maisFortes.add(ca); continue; } if(forcaDaCartaCA > forcaDaCartaMaisForte) { maisFortes.clear(); maisFortes.add(ca); continue; } } assert maisFortes.size() > 0; return maisFortes; } public static Carta getCarta(String nome) throws IllegalArgumentException{ Carta carta = null; for(Carta c : values()) { if(c.nome.equals(nome)) { carta = c; break; } } if(carta == null) throw new IllegalStateException("Este nome de carta não existe"); return carta; } @Override public String toString() { return nome; } }
mit
navalev/azure-sdk-for-java
sdk/servicebus/microsoft-azure-servicebus/src/test/java/com/microsoft/azure/servicebus/ManagementTests.java
27721
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.servicebus; import com.microsoft.azure.servicebus.management.AccessRights; import com.microsoft.azure.servicebus.management.AuthorizationRule; import com.microsoft.azure.servicebus.management.EntityNameHelper; import com.microsoft.azure.servicebus.management.ManagementClientAsync; import com.microsoft.azure.servicebus.management.NamespaceInfo; import com.microsoft.azure.servicebus.management.NamespaceType; import com.microsoft.azure.servicebus.management.QueueDescription; import com.microsoft.azure.servicebus.management.QueueRuntimeInfo; import com.microsoft.azure.servicebus.management.SharedAccessAuthorizationRule; import com.microsoft.azure.servicebus.management.SubscriptionDescription; import com.microsoft.azure.servicebus.management.SubscriptionRuntimeInfo; import com.microsoft.azure.servicebus.management.TopicDescription; import com.microsoft.azure.servicebus.management.TopicRuntimeInfo; import com.microsoft.azure.servicebus.primitives.MessagingEntityAlreadyExistsException; import com.microsoft.azure.servicebus.primitives.MessagingEntityNotFoundException; import com.microsoft.azure.servicebus.primitives.MessagingFactory; import com.microsoft.azure.servicebus.primitives.ServiceBusException; import com.microsoft.azure.servicebus.rules.CorrelationFilter; import com.microsoft.azure.servicebus.rules.FalseFilter; import com.microsoft.azure.servicebus.rules.RuleDescription; import com.microsoft.azure.servicebus.rules.SqlFilter; import com.microsoft.azure.servicebus.rules.SqlRuleAction; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.net.URI; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicBoolean; public class ManagementTests extends TestBase { private ManagementClientAsync managementClientAsync; @Before public void setup() { URI namespaceEndpointURI = TestUtils.getNamespaceEndpointURI(); ClientSettings managementClientSettings = TestUtils.getManagementClientSettings(); managementClientAsync = new ManagementClientAsync(namespaceEndpointURI, managementClientSettings); } @Test public void basicQueueCrudTest() throws InterruptedException, ExecutionException { String queueName = UUID.randomUUID().toString().substring(0, 8); QueueDescription q = new QueueDescription(queueName); q.setAutoDeleteOnIdle(Duration.ofHours(1)); q.setDefaultMessageTimeToLive(Duration.ofDays(2)); q.setDuplicationDetectionHistoryTimeWindow(Duration.ofMinutes(1)); q.setEnableBatchedOperations(false); q.setEnableDeadLetteringOnMessageExpiration(true); q.setEnablePartitioning(false); q.setForwardTo(null); q.setForwardDeadLetteredMessagesTo(null); q.setLockDuration(Duration.ofSeconds(45)); q.setMaxDeliveryCount(8); q.setMaxSizeInMB(2048); q.setRequiresDuplicateDetection(true); q.setRequiresSession(true); q.setUserMetadata("basicQueueCrudTest"); ArrayList<AuthorizationRule> rules = new ArrayList<>(); ArrayList<AccessRights> rights = new ArrayList<>(); rights.add(AccessRights.Send); rights.add(AccessRights.Listen); rights.add(AccessRights.Manage); rules.add(new SharedAccessAuthorizationRule("allClaims", rights)); q.setAuthorizationRules(rules); QueueDescription qCreated = this.managementClientAsync.createQueueAsync(q).get(); Assert.assertEquals(q, qCreated); QueueDescription queue = this.managementClientAsync.getQueueAsync(queueName).get(); Assert.assertEquals(qCreated, queue); queue.setEnableBatchedOperations(false); queue.setMaxDeliveryCount(9); queue.getAuthorizationRules().clear(); rights = new ArrayList<>(); rights.add(AccessRights.Send); rights.add(AccessRights.Listen); queue.getAuthorizationRules().add(new SharedAccessAuthorizationRule("noManage", rights)); QueueDescription updatedQ = this.managementClientAsync.updateQueueAsync(queue).get(); Assert.assertEquals(queue, updatedQ); Boolean exists = this.managementClientAsync.queueExistsAsync(queueName).get(); Assert.assertTrue(exists); List<QueueDescription> queues = this.managementClientAsync.getQueuesAsync().get(); Assert.assertTrue(queues.size() > 0); AtomicBoolean found = new AtomicBoolean(false); queues.forEach(queueDescription -> { if (queueDescription.getPath().equalsIgnoreCase(queueName)) { found.set(true); } }); Assert.assertTrue(found.get()); this.managementClientAsync.deleteQueueAsync(queueName).get(); exists = this.managementClientAsync.queueExistsAsync(queueName).get(); Assert.assertFalse(exists); } @Test public void basicTopicCrudTest() throws InterruptedException, ExecutionException { String topicName = UUID.randomUUID().toString().substring(0, 8); TopicDescription td = new TopicDescription(topicName); td.setAutoDeleteOnIdle(Duration.ofHours(1)); td.setDefaultMessageTimeToLive(Duration.ofDays(2)); td.setDuplicationDetectionHistoryTimeWindow(Duration.ofMinutes(1)); td.setEnableBatchedOperations(false); td.setEnablePartitioning(false); td.setMaxSizeInMB(2048); td.setRequiresDuplicateDetection(true); td.setUserMetadata("basicTopicCrudTest"); td.setSupportOrdering(true); ArrayList<AuthorizationRule> rules = new ArrayList<>(); ArrayList<AccessRights> rights = new ArrayList<>(); rights.add(AccessRights.Send); rights.add(AccessRights.Listen); rights.add(AccessRights.Manage); rules.add(new SharedAccessAuthorizationRule("allClaims", rights)); td.setAuthorizationRules(rules); TopicDescription tCreated = this.managementClientAsync.createTopicAsync(td).get(); Assert.assertEquals(td, tCreated); TopicDescription topic = this.managementClientAsync.getTopicAsync(topicName).get(); Assert.assertEquals(tCreated, topic); topic.setEnableBatchedOperations(false); topic.setDefaultMessageTimeToLive(Duration.ofDays(3)); topic.getAuthorizationRules().clear(); rights = new ArrayList<>(); rights.add(AccessRights.Send); rights.add(AccessRights.Listen); topic.getAuthorizationRules().add(new SharedAccessAuthorizationRule("noManage", rights)); TopicDescription updatedT = this.managementClientAsync.updateTopicAsync(topic).get(); Assert.assertEquals(topic, updatedT); Boolean exists = this.managementClientAsync.topicExistsAsync(topicName).get(); Assert.assertTrue(exists); List<TopicDescription> topics = this.managementClientAsync.getTopicsAsync().get(); Assert.assertTrue(topics.size() > 0); AtomicBoolean found = new AtomicBoolean(false); topics.forEach(topicDescription -> { if (topicDescription.getPath().equalsIgnoreCase(topicName)) { found.set(true); } }); Assert.assertTrue(found.get()); this.managementClientAsync.deleteTopicAsync(topicName).get(); exists = this.managementClientAsync.topicExistsAsync(topicName).get(); Assert.assertFalse(exists); } @Test public void basicSubscriptionCrudTest() throws InterruptedException, ExecutionException { String topicName = UUID.randomUUID().toString().substring(0, 8); this.managementClientAsync.createTopicAsync(topicName).get(); String subscriptionName = UUID.randomUUID().toString().substring(0, 8); SubscriptionDescription subscriptionDescription = new SubscriptionDescription(topicName, subscriptionName); subscriptionDescription.setAutoDeleteOnIdle(Duration.ofHours(1)); subscriptionDescription.setDefaultMessageTimeToLive(Duration.ofDays(2)); subscriptionDescription.setEnableBatchedOperations(false); subscriptionDescription.setEnableDeadLetteringOnMessageExpiration(true); subscriptionDescription.setEnableDeadLetteringOnFilterEvaluationException(false); subscriptionDescription.setForwardTo(null); subscriptionDescription.setForwardDeadLetteredMessagesTo(null); subscriptionDescription.setLockDuration(Duration.ofSeconds(45)); subscriptionDescription.setMaxDeliveryCount(8); subscriptionDescription.setRequiresSession(true); subscriptionDescription.setUserMetadata("basicSubscriptionCrudTest"); SubscriptionDescription createdS = this.managementClientAsync.createSubscriptionAsync(subscriptionDescription).get(); Assert.assertEquals(subscriptionDescription, createdS); SubscriptionDescription getS = this.managementClientAsync.getSubscriptionAsync(topicName, subscriptionName).get(); Assert.assertEquals(createdS, getS); getS.setEnableBatchedOperations(false); getS.setMaxDeliveryCount(9); SubscriptionDescription updatedQ = this.managementClientAsync.updateSubscriptionAsync(getS).get(); Assert.assertEquals(getS, updatedQ); Boolean exists = this.managementClientAsync.subscriptionExistsAsync(topicName, subscriptionName).get(); Assert.assertTrue(exists); List<SubscriptionDescription> subscriptions = this.managementClientAsync.getSubscriptionsAsync(topicName).get(); Assert.assertEquals(1, subscriptions.size()); Assert.assertEquals(subscriptionName, subscriptions.get(0).getSubscriptionName()); this.managementClientAsync.deleteSubscriptionAsync(topicName, subscriptionName).get(); exists = this.managementClientAsync.subscriptionExistsAsync(topicName, subscriptionName).get(); Assert.assertFalse(exists); this.managementClientAsync.deleteTopicAsync(topicName).get(); exists = this.managementClientAsync.subscriptionExistsAsync(topicName, subscriptionName).get(); Assert.assertFalse(exists); } @Test public void basicRulesCrudTest() throws InterruptedException, ExecutionException { String topicName = UUID.randomUUID().toString().substring(0, 8); String subscriptionName = UUID.randomUUID().toString().substring(0, 8); this.managementClientAsync.createTopicAsync(topicName).get(); this.managementClientAsync.createSubscriptionAsync( new SubscriptionDescription(topicName, subscriptionName), new RuleDescription("rule0", new FalseFilter())).get(); //SqlFilter sqlFilter = new SqlFilter("stringValue = @stringParam AND intValue = @intParam AND longValue = @longParam AND dateValue = @dateParam"); SqlFilter sqlFilter = new SqlFilter("1=1"); /* todo sqlFilter.Parameters.Add("@stringParam", "string"); sqlFilter.Parameters.Add("@intParam", (int)1); sqlFilter.Parameters.Add("@longParam", (long)12); sqlFilter.Parameters.Add("@dateParam", DateTime.UtcNow); */ RuleDescription rule1 = new RuleDescription("rule1"); rule1.setFilter(sqlFilter); rule1.setAction(new SqlRuleAction("SET a='b'")); this.managementClientAsync.createRuleAsync(topicName, subscriptionName, rule1).get(); CorrelationFilter correlationFilter = new CorrelationFilter(); correlationFilter.setContentType("contentType"); correlationFilter.setCorrelationId("correlationId"); correlationFilter.setLabel("label"); correlationFilter.setMessageId("messageId"); correlationFilter.setReplyTo("replyTo"); correlationFilter.setReplyToSessionId("replyToSessionId"); correlationFilter.setSessionId("sessionId"); correlationFilter.setTo("to"); // todo // correlationFilter.Properties.Add("customKey", "customValue"); RuleDescription rule2 = new RuleDescription("rule2"); rule2.setFilter(correlationFilter); this.managementClientAsync.createRuleAsync(topicName, subscriptionName, rule2).get(); List<RuleDescription> rules = this.managementClientAsync.getRulesAsync(topicName, subscriptionName).get(); Assert.assertEquals(3, rules.size()); Assert.assertEquals("rule0", rules.get(0).getName()); Assert.assertEquals(rule1, rules.get(1)); Assert.assertEquals(rule2, rules.get(2)); ((CorrelationFilter) (rule2.getFilter())).setCorrelationId("correlationIdModified"); RuleDescription updatedRule2 = this.managementClientAsync.updateRuleAsync(topicName, subscriptionName, rule2).get(); Assert.assertEquals(rule2, updatedRule2); RuleDescription defaultRule = this.managementClientAsync.getRuleAsync(topicName, subscriptionName, "rule0").get(); Assert.assertNotNull(defaultRule); this.managementClientAsync.deleteRuleAsync(topicName, subscriptionName, "rule0").get(); try { this.managementClientAsync.getRuleAsync(topicName, subscriptionName, "rule0").get(); Assert.fail("Get rule0 should have thrown."); } catch (Exception ex) { Assert.assertTrue(ex instanceof ExecutionException); Throwable cause = ex.getCause(); Assert.assertTrue(cause instanceof MessagingEntityNotFoundException); } Assert.assertFalse(this.managementClientAsync.ruleExistsAsync(topicName, subscriptionName, "rule0").get()); this.managementClientAsync.deleteTopicAsync(topicName).get(); } @Test public void getQueueRuntimeInfoTest() throws ExecutionException, InterruptedException, ServiceBusException { String queueName = UUID.randomUUID().toString().substring(0, 8); // Setting created time QueueDescription qd = this.managementClientAsync.createQueueAsync(queueName).get(); // Changing last updated time qd.setAutoDeleteOnIdle(Duration.ofHours(2)); QueueDescription updatedQd = this.managementClientAsync.updateQueueAsync(qd).get(); // Populating 1 active, 1 dead and 1 scheduled message. // Changing last accessed time. MessagingFactory factory = MessagingFactory.createFromNamespaceEndpointURI(TestUtils.getNamespaceEndpointURI(), TestUtils.getClientSettings()); IMessageSender sender = ClientFactory.createMessageSenderFromEntityPath(factory, queueName); IMessageReceiver receiver = ClientFactory.createMessageReceiverFromEntityPath(factory, queueName); sender.send(new Message("m1")); sender.send(new Message("m2")); sender.scheduleMessage(new Message("m3"), Instant.now().plusSeconds(1000)); IMessage msg = receiver.receive(); receiver.deadLetter(msg.getLockToken()); QueueRuntimeInfo runtimeInfo = this.managementClientAsync.getQueueRuntimeInfoAsync(queueName).get(); Assert.assertEquals(queueName, runtimeInfo.getPath()); Assert.assertTrue(runtimeInfo.getCreatedAt().isBefore(runtimeInfo.getUpdatedAt())); Assert.assertTrue(runtimeInfo.getUpdatedAt().isBefore(runtimeInfo.getAccessedAt())); Assert.assertEquals(1, runtimeInfo.getMessageCountDetails().getActiveMessageCount()); Assert.assertEquals(1, runtimeInfo.getMessageCountDetails().getDeadLetterMessageCount()); Assert.assertEquals(1, runtimeInfo.getMessageCountDetails().getScheduledMessageCount()); Assert.assertEquals(3, runtimeInfo.getMessageCount()); Assert.assertTrue(runtimeInfo.getSizeInBytes() > 0); this.managementClientAsync.deleteQueueAsync(queueName).get(); receiver.close(); sender.close(); factory.close(); } @Test public void getTopicAndSubscriptionRuntimeInfoTest() throws ExecutionException, InterruptedException, ServiceBusException { String topicName = UUID.randomUUID().toString().substring(0, 8); String subscriptionName = UUID.randomUUID().toString().substring(0, 8); // Setting created time TopicDescription td = this.managementClientAsync.createTopicAsync(topicName).get(); // Changing last updated time td.setAutoDeleteOnIdle(Duration.ofHours(2)); TopicDescription updatedTd = this.managementClientAsync.updateTopicAsync(td).get(); SubscriptionDescription sd = this.managementClientAsync.createSubscriptionAsync(topicName, subscriptionName).get(); // Changing Last updated time for subscription. sd.setAutoDeleteOnIdle(Duration.ofHours(2)); SubscriptionDescription updatedSd = this.managementClientAsync.updateSubscriptionAsync(sd).get(); // Populating 1 active, 1 dead and 1 scheduled message. // Changing last accessed time. MessagingFactory factory = MessagingFactory.createFromNamespaceEndpointURI(TestUtils.getNamespaceEndpointURI(), TestUtils.getClientSettings()); IMessageSender sender = ClientFactory.createMessageSenderFromEntityPath(factory, topicName); IMessageReceiver receiver = ClientFactory.createMessageReceiverFromEntityPath(factory, EntityNameHelper.formatSubscriptionPath(topicName, subscriptionName)); sender.send(new Message("m1")); sender.send(new Message("m2")); sender.scheduleMessage(new Message("m3"), Instant.now().plusSeconds(1000)); IMessage msg = receiver.receive(); receiver.deadLetter(msg.getLockToken()); TopicRuntimeInfo topicRuntimeInfo = this.managementClientAsync.getTopicRuntimeInfoAsync(topicName).get(); SubscriptionRuntimeInfo subscriptionRuntimeInfo = this.managementClientAsync.getSubscriptionRuntimeInfoAsync(topicName, subscriptionName).get(); Assert.assertEquals(topicName, topicRuntimeInfo.getPath()); Assert.assertEquals(topicName, subscriptionRuntimeInfo.getTopicPath()); Assert.assertEquals(subscriptionName, subscriptionRuntimeInfo.getSubscriptionName()); Assert.assertEquals(0, topicRuntimeInfo.getMessageCountDetails().getActiveMessageCount()); Assert.assertEquals(0, topicRuntimeInfo.getMessageCountDetails().getDeadLetterMessageCount()); Assert.assertEquals(1, topicRuntimeInfo.getMessageCountDetails().getScheduledMessageCount()); Assert.assertEquals(1, subscriptionRuntimeInfo.getMessageCountDetails().getActiveMessageCount()); Assert.assertEquals(1, subscriptionRuntimeInfo.getMessageCountDetails().getDeadLetterMessageCount()); Assert.assertEquals(0, subscriptionRuntimeInfo.getMessageCountDetails().getScheduledMessageCount()); Assert.assertEquals(2, subscriptionRuntimeInfo.getMessageCount()); Assert.assertEquals(1, topicRuntimeInfo.getSubscriptionCount()); Assert.assertTrue(topicRuntimeInfo.getSizeInBytes() > 0); Assert.assertTrue(topicRuntimeInfo.getCreatedAt().isBefore(topicRuntimeInfo.getUpdatedAt())); Assert.assertTrue(topicRuntimeInfo.getUpdatedAt().isBefore(topicRuntimeInfo.getAccessedAt())); Assert.assertTrue(subscriptionRuntimeInfo.getCreatedAt().isBefore(subscriptionRuntimeInfo.getUpdatedAt())); Assert.assertTrue(subscriptionRuntimeInfo.getUpdatedAt().isBefore(subscriptionRuntimeInfo.getAccessedAt())); Assert.assertTrue(topicRuntimeInfo.getUpdatedAt().isBefore(subscriptionRuntimeInfo.getUpdatedAt())); this.managementClientAsync.deleteSubscriptionAsync(topicName, subscriptionName).get(); this.managementClientAsync.deleteTopicAsync(topicName).get(); receiver.close(); sender.close(); factory.close(); } @Test public void messagingEntityNotFoundExceptionTest() throws ServiceBusException, InterruptedException, ExecutionException { try { Utils.completeFuture(this.managementClientAsync.getQueueAsync("NonExistingPath")); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.getTopicAsync("NonExistingPath")); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.getSubscriptionAsync("NonExistingTopic", "NonExistingPath")); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.updateQueueAsync(new QueueDescription("NonExistingPath"))); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.updateTopicAsync(new TopicDescription("NonExistingPath"))); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.updateSubscriptionAsync(new SubscriptionDescription("NonExistingTopic", "NonExistingPath"))); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.deleteQueueAsync("NonExistingPath")); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.deleteTopicAsync("NonExistingPath")); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.deleteSubscriptionAsync("nonExistingTopic", "NonExistingPath")); } catch (MessagingEntityNotFoundException e) { } String queueName = UUID.randomUUID().toString().substring(0, 8); String topicName = UUID.randomUUID().toString().substring(0, 8); this.managementClientAsync.createQueueAsync(queueName).get(); this.managementClientAsync.createTopicAsync(topicName).get(); try { Utils.completeFuture(this.managementClientAsync.getQueueAsync(topicName)); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.getTopicAsync(queueName)); } catch (MessagingEntityNotFoundException e) { } try { Utils.completeFuture(this.managementClientAsync.getSubscriptionAsync(topicName, "NonExistingSubscription")); } catch (MessagingEntityNotFoundException e) { } this.managementClientAsync.deleteQueueAsync(queueName).get(); this.managementClientAsync.deleteTopicAsync(topicName).get(); } @Test public void messagingEntityAlreadyExistsExceptionTest() throws ServiceBusException, InterruptedException, ExecutionException { String queueName = UUID.randomUUID().toString().substring(0, 8); String topicName = UUID.randomUUID().toString().substring(0, 8); String subscriptionName = UUID.randomUUID().toString().substring(0, 8); this.managementClientAsync.createQueueAsync(queueName).get(); this.managementClientAsync.createTopicAsync(topicName).get(); this.managementClientAsync.createSubscriptionAsync(topicName, subscriptionName).get(); try { Utils.completeFuture(this.managementClientAsync.createQueueAsync(queueName)); } catch (MessagingEntityAlreadyExistsException e) { } try { Utils.completeFuture(this.managementClientAsync.createTopicAsync(topicName)); } catch (MessagingEntityAlreadyExistsException e) { } try { Utils.completeFuture(this.managementClientAsync.createSubscriptionAsync(topicName, subscriptionName)); } catch (MessagingEntityAlreadyExistsException e) { } this.managementClientAsync.deleteQueueAsync(queueName).get(); this.managementClientAsync.deleteSubscriptionAsync(topicName, subscriptionName).get(); this.managementClientAsync.deleteTopicAsync(topicName).get(); } @Test public void forwardingEntitySetupTest() throws ServiceBusException, InterruptedException { // queueName -- fwdTo --> destinationName -- fwd dlqTo --> dlqDestinationName String queueName = UUID.randomUUID().toString().substring(0, 8); String destinationName = UUID.randomUUID().toString().substring(0, 8); String dlqDestinationName = UUID.randomUUID().toString().substring(0, 8); QueueDescription dqlDestinationQ = Utils.completeFuture(this.managementClientAsync.createQueueAsync(dlqDestinationName)); QueueDescription destinationQToCreate = new QueueDescription(destinationName); destinationQToCreate.setForwardDeadLetteredMessagesTo(dlqDestinationName); QueueDescription destinationQ = Utils.completeFuture(this.managementClientAsync.createQueueAsync(destinationQToCreate)); QueueDescription qd = new QueueDescription(queueName); qd.setForwardTo(destinationName); QueueDescription baseQ = Utils.completeFuture(this.managementClientAsync.createQueueAsync(qd)); MessagingFactory factory = MessagingFactory.createFromNamespaceEndpointURI(TestUtils.getNamespaceEndpointURI(), TestUtils.getClientSettings()); IMessageSender sender = ClientFactory.createMessageSenderFromEntityPath(factory, queueName); IMessage message = new Message(); message.setMessageId("mid"); sender.send(message); sender.close(); IMessageReceiver receiver = ClientFactory.createMessageReceiverFromEntityPath(factory, destinationName); IMessage msg = receiver.receive(); Assert.assertNotNull(msg); Assert.assertEquals("mid", msg.getMessageId()); receiver.deadLetter(msg.getLockToken()); receiver.close(); receiver = ClientFactory.createMessageReceiverFromEntityPath(factory, dlqDestinationName); msg = receiver.receive(); Assert.assertNotNull(msg); Assert.assertEquals("mid", msg.getMessageId()); receiver.complete(msg.getLockToken()); receiver.close(); this.managementClientAsync.deleteQueueAsync(queueName); this.managementClientAsync.deleteQueueAsync(destinationName); this.managementClientAsync.deleteQueueAsync(dlqDestinationName); } @Test public void authRulesEqualityCheckTest() { QueueDescription qd = new QueueDescription("a"); SharedAccessAuthorizationRule rule1 = new SharedAccessAuthorizationRule("sendListen", new ArrayList<>(Arrays.asList(AccessRights.Listen, AccessRights.Send))); SharedAccessAuthorizationRule rule2 = new SharedAccessAuthorizationRule("manage", new ArrayList<>(Arrays.asList(AccessRights.Listen, AccessRights.Send, AccessRights.Manage))); qd.setAuthorizationRules(new ArrayList<>(Arrays.asList(rule1, rule2))); QueueDescription qd2 = new QueueDescription("a"); AuthorizationRule rule11 = new SharedAccessAuthorizationRule(rule2.getKeyName(), rule2.getPrimaryKey(), rule2.getSecondaryKey(), rule2.getRights()); AuthorizationRule rule22 = new SharedAccessAuthorizationRule(rule1.getKeyName(), rule1.getPrimaryKey(), rule1.getSecondaryKey(), rule1.getRights()); qd2.setAuthorizationRules(new ArrayList<>(Arrays.asList(rule11, rule22))); Assert.assertTrue(qd.equals(qd2)); } @Test public void getNamespaceInfoTest() throws ExecutionException, InterruptedException { NamespaceInfo nsInfo = this.managementClientAsync.getNamespaceInfoAsync().get(); Assert.assertNotNull(nsInfo); Assert.assertEquals(NamespaceType.ServiceBus, nsInfo.getNamespaceType()); } }
mit
softjourn-internship/sales-if-ua
src/main/java/sales/bucket/domain/Bucket.java
968
package sales.bucket.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import sales.users.domain.User; import javax.persistence.*; import java.util.List; /** * Created by taras on 13.08.15. */ @Entity @Table(name="buckets") public class Bucket { @Id @GeneratedValue(strategy = GenerationType.AUTO) @JsonProperty private Long id; @ManyToOne(targetEntity = User.class) @JoinColumn(name = "client", referencedColumnName = "id") @JsonProperty private User client; @OneToMany(cascade = CascadeType.ALL, mappedBy="bucket", fetch = FetchType.EAGER) @JsonProperty private List<GoodInBucket> goodsInBucket; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getClient() { return client; } public void setClient(User client) { this.client = client; } }
mit
f2prateek/segment-android
segment-model/src/main/java/com/f2prateek/segment/model/ScreenMessage.java
5218
package com.f2prateek.segment.model; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.util.Collections; import java.util.Date; import java.util.Map; import static com.f2prateek.segment.model.Utils.assertNotNull; import static com.f2prateek.segment.model.Utils.assertNotNullOrEmpty; import static com.f2prateek.segment.model.Utils.immutableCopyOf; import static com.f2prateek.segment.model.Utils.isNullOrEmpty; /** * The screen call lets you record whenever a user sees a screen, along with any properties about * the screen. * * @see <a href="https://segment.com/docs/spec/screen/">Screen</a> */ public final class ScreenMessage extends Message { private @NonNull final String name; private @Nullable final Map<String, Object> properties; @Private ScreenMessage(Type type, String messageId, Date timestamp, Map<String, Object> context, Map<String, Object> integrations, String userId, String anonymousId, @NonNull String name, @Nullable Map<String, Object> properties) { super(type, messageId, timestamp, context, integrations, userId, anonymousId); this.name = name; this.properties = properties; } public @NonNull String name() { return name; } public @Nullable Map<String, Object> properties() { return properties; } @Override public @NonNull Builder toBuilder() { return new Builder(this); } @Override public String toString() { return "ScreenMessage{" + "type=" + type + ", " + "messageId=" + messageId + ", " + "timestamp=" + timestamp + ", " + "context=" + context + ", " + "integrations=" + integrations + ", " + "userId=" + userId + ", " + "anonymousId=" + anonymousId + ", " + "name=" + name + ", " + "properties=" + properties + "}"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof ScreenMessage) { ScreenMessage that = (ScreenMessage) o; return (this.type.equals(that.type())) && ((this.messageId == null) ? (that.messageId() == null) : this.messageId.equals(that.messageId())) && ((this.timestamp == null) ? (that.timestamp() == null) : this.timestamp.equals(that.timestamp())) && ((this.context == null) ? (that.context() == null) : this.context.equals(that.context())) && ((this.integrations == null) ? (that.integrations() == null) : this.integrations.equals(that.integrations())) && ((this.userId == null) ? (that.userId() == null) : this.userId.equals(that.userId())) && ((this.anonymousId == null) ? (that.anonymousId() == null) : this.anonymousId.equals(that.anonymousId())) && (this.name.equals(that.name())) && ((this.properties == null) ? (that.properties() == null) : this.properties.equals(that.properties())); } return false; } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= this.type.hashCode(); h *= 1000003; h ^= (messageId == null) ? 0 : this.messageId.hashCode(); h *= 1000003; h ^= (timestamp == null) ? 0 : this.timestamp.hashCode(); h *= 1000003; h ^= (context == null) ? 0 : this.context.hashCode(); h *= 1000003; h ^= (integrations == null) ? 0 : this.integrations.hashCode(); h *= 1000003; h ^= (userId == null) ? 0 : this.userId.hashCode(); h *= 1000003; h ^= (anonymousId == null) ? 0 : this.anonymousId.hashCode(); h *= 1000003; h ^= this.name.hashCode(); h *= 1000003; h ^= (properties == null) ? 0 : this.properties.hashCode(); return h; } /** Fluent API for creating {@link ScreenMessage} instances. */ public static class Builder extends Message.Builder<ScreenMessage, Builder> { private String name; private Map<String, Object> properties; public Builder() { super(Type.screen); } @Private Builder(ScreenMessage screen) { super(screen); name = screen.name(); properties = screen.properties(); } public @NonNull Builder name(@NonNull String name) { this.name = assertNotNullOrEmpty(name, "name"); return this; } public @NonNull Builder properties(@NonNull Map<String, Object> properties) { assertNotNull(properties, "properties"); this.properties = immutableCopyOf(properties); return this; } @Override protected ScreenMessage realBuild(Type type, String messageId, Date timestamp, Map<String, Object> context, Map<String, Object> integrations, String userId, String anonymousId) { assertNotNullOrEmpty(name, "name"); Map<String, Object> properties = this.properties; if (isNullOrEmpty(properties)) { properties = Collections.emptyMap(); } return new ScreenMessage(type, messageId, timestamp, context, integrations, userId, anonymousId, name, properties); } @Override Builder self() { return this; } } }
mit
backuporg/Witchworks
src/main/java/com/witchworks/api/brew/IBrewDeath.java
447
package com.witchworks.api.brew; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.DamageSource; import net.minecraftforge.event.entity.living.LivingDeathEvent; /** * This class was created by Arekkuusu on 06/06/2017. * It's distributed as part of Witchworks under * the MIT license. */ public interface IBrewDeath { void onDeath(LivingDeathEvent event, DamageSource source, EntityLivingBase dying, int amplifier); }
mit
InnovateUKGitHub/innovation-funding-service
ifs-web-service/ifs-competition-mgt-service/src/main/java/org/innovateuk/ifs/management/publiccontent/formpopulator/section/ScopeFormPopulator.java
842
package org.innovateuk.ifs.management.publiccontent.formpopulator.section; import org.innovateuk.ifs.competition.publiccontent.resource.PublicContentSectionType; import org.innovateuk.ifs.management.publiccontent.form.section.ScopeForm; import org.innovateuk.ifs.management.publiccontent.formpopulator.PublicContentFormPopulator; import org.innovateuk.ifs.management.publiccontent.formpopulator.AbstractContentGroupFormPopulator; import org.springframework.stereotype.Service; @Service public class ScopeFormPopulator extends AbstractContentGroupFormPopulator<ScopeForm> implements PublicContentFormPopulator<ScopeForm> { @Override protected ScopeForm createInitial() { return new ScopeForm(); } @Override protected PublicContentSectionType getType() { return PublicContentSectionType.SCOPE; } }
mit
kasperisager/bookie
src/main/java/dk/itu/donkey/Schema.java
5660
/** * Copyright (C) 2014 Kasper Kronborg Isager. */ package dk.itu.donkey; // SQL utilities import java.sql.SQLException; /** * The Schema class is used for executing Data Definition Language (DDL) * statements against a database thus handling schema definition. * * @see <a href="https://en.wikipedia.org/wiki/Data_definition_language"> * Wikipedia - Data definition language</a> * * @since 1.0.0 Initial release. */ public final class Schema { /** * The database to run the schema against. */ private Database db; /** * The SQL grammar to use for the schema. */ private Grammar grammar; /** * Initialize a new schema. * * @param db The database to run the schema against. */ public Schema(final Database db) { this.db = db; this.grammar = db.grammar(); } /** * Begin a table creation statement. * * @param table The name of the table to create. * @return The current {@link Schema} object, for chaining. */ public Schema create(final String table) { this.grammar.addTable(table); return this; } /** * Run the create statement. * * @throws SQLException In case of a SQL error. */ public void run() throws SQLException { this.db.execute(this.grammar.compileCreate()); } /** * Drop a database table. * * @param table The table to drop from the database. * * @throws SQLException In case of a SQL error. */ public void drop(final String table) throws SQLException { this.grammar.addTable(table); this.db.execute(this.grammar.compileDrop()); } /** * Add a text column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema text(final String column) { this.grammar.addDataType(column, "text", true); return this; } /** * Add an integer column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema integer(final String column) { this.grammar.addDataType(column, "integer", true); return this; } /** * Add a double column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema doublePrecision(final String column) { this.grammar.addDataType(column, "double precision", true); return this; } /** * Add a float column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema floatingPoint(final String column) { this.grammar.addDataType(column, "float", 24, true); return this; } /** * Add a long column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema longInteger(final String column) { this.grammar.addDataType(column, "bigint", true); return this; } /** * Add a real column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema real(final String column) { this.grammar.addDataType(column, "real", true); return this; } /** * Add a numeric column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema numeric(final String column) { this.grammar.addDataType(column, "numeric", true); return this; } /** * Add a boolean column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema bool(final String column) { this.grammar.addDataType(column, "boolean", true); return this; } /** * Add a date column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema date(final String column) { this.grammar.addDataType(column, "date", true); return this; } /** * Add a time column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema time(final String column) { this.grammar.addDataType(column, "time", true); return this; } /** * Add a timestamp column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema timestamp(final String column) { this.grammar.addDataType(column, "timestamp", true); return this; } /** * Add an auto incrementing integer column to the schema. * * @param column The name of the column. * @return The current {@link Schema} object, for chaining. */ public Schema increments(final String column) { this.grammar.addAutoIncrement(column); return this; } /** * Add a foreign key to the schema. * * @param column The name of the column. * @param foreignTable The name of the foreign table. * @param foreignColumn The name of the foreign column. * @return The current {@link Schema} object, for chaining. */ public Schema foreignKey( final String column, final String foreignTable, final String foreignColumn ) { this.grammar.addForeignKey(column, foreignTable, foreignColumn); return this; } }
mit
mustah/jexpect
test/com/jexpect/exception_messages/ToBeBooleanTest.java
1619
package com.jexpect.exception_messages; import org.junit.Test; import com.jexpect.util.Command; import static com.jexpect.Expect.expect; import static com.jexpect.util.ExceptionHandler.getExceptionMessage; import static org.junit.Assert.assertEquals; public class ToBeBooleanTest { @Test public void When_Expected_False_Fails_Then_Exception_Should_Have_Message() throws Exception { assertEquals("Expected to be <false>, but found: <true>", getExceptionMessage(new Command() { @Override public void execute() { expect(true).toBeFalse(); } })); } @Test public void When_Expected_To_Be_True_Fails_Then_Exception_Should_Have_Message() throws Exception { assertEquals("Expected to be <true>, but found: <false>", getExceptionMessage(new Command() { @Override public void execute() { expect(false).toBeTrue(); } })); } @Test public void When_Expected_Actual_To_Be_Same_As_Expected_Fails_Then_Exception_Should_Have_Message() throws Exception { assertEquals("Expected to be <true>, but found: <false>", getExceptionMessage(new Command() { @Override public void execute() { expect(false).toBe(true); } })); assertEquals("Expected to be <false>, but found: <true>", getExceptionMessage(new Command() { @Override public void execute() { expect(true).toBe(false); } })); assertEquals("Expected to be <null>, but found: <true>", getExceptionMessage(new Command() { @Override public void execute() { expect(true).toBe(null); } })); } }
mit
Dwarfartisan/jparsec
advance/src/java/com/dwarfartisan/parsec/Digit.java
653
package com.dwarfartisan.parsec; import java.io.EOFException; /** * Created by Mars Liu on 2016-01-07. * Digit 判断下一个项是否是一个表示数字的字符.它仅接受 Character/char . */ public class Digit<Status, Tran> implements Parsec<Character, Character, Status, Tran> { @Override public Character parse(State<Character, Status, Tran> s) throws EOFException, ParsecException { Character re = s.next(); if (Character.isDigit(re)) { return re; } else { String message = String.format("Expect %c is digit.", re); throw s.trap(message); } } }
mit
shwarzes89/ExpressionPredictor
src/SockServer.java
203
public class SockServer { /** * @param args */ public static void main(String[] args) { SockServerController server = new SockServerController(9679); server.runServer(); } }
mit
BoiseState/CS121-resources
examples/chap06/TwoDColorChooser.java
2653
import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * Demonstrate 2D array of GUI components. (This could all be done using a * 1D array. See MiniColorChooserV1.java and MiniColorChooserV2.java). * * Get color from the clicked button, itself. * * @author CS121 Instructors */ @SuppressWarnings("serial") public class TwoDColorChooser extends JPanel { private final Color[][] COLORS = { { Color.RED, Color.GREEN, Color.BLUE }, { Color.YELLOW, Color.CYAN, Color.MAGENTA }, { Color.WHITE, Color.BLACK, Color.GRAY }, { Color.PINK, Color.ORANGE, Color.LIGHT_GRAY} }; private JButton[][] colorButtons; private JPanel displayPanel; /** * main panel constructor */ private TwoDColorChooser() { //sub-panel for grid of color choices JPanel gridPanel = new JPanel(); gridPanel.setLayout(new GridLayout(COLORS.length, COLORS[0].length)); gridPanel.setPreferredSize(new Dimension(300, 300)); //sub-panel to display chosen color displayPanel = new JPanel(); displayPanel.setPreferredSize(new Dimension(300,300)); //instantiate a ColorButtonListener. all buttons should share the same instance. ColorButtonListener listener = new ColorButtonListener(); //buttons colorButtons = new JButton[COLORS.length][COLORS[0].length]; for (int i = 0; i < colorButtons.length; i++) { for(int j = 0; j < colorButtons[0].length; j++) { colorButtons[i][j] = new JButton(); colorButtons[i][j].setBackground(COLORS[i][j]); colorButtons[i][j].addActionListener(listener); gridPanel.add(colorButtons[i][j]); } } //add sub-panels to this panel this.add(gridPanel); this.add(displayPanel); } private class ColorButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // have to cast generic Object reference from e.getSource() // to a JButton reference in order to use button method // getBackground() JButton source = (JButton)(e.getSource()); //set display panel to the color of the button that was clicked displayPanel.setBackground(source.getBackground()); } } /** * Initialize the GUI and make it visible * @param args unused */ public static void main(String[] args) { JFrame frame = new JFrame("Mini-ColorChooser"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new TwoDColorChooser()); frame.pack(); frame.setVisible(true); } }
mit
javasuki/RJava
NXDO.Java.V2015/jxdo.rjava/src/jxdo/rjava/JCSharp.java
6826
package jxdo.rjava; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Modifier; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; class JCSharp { static String crlf; static ClassLoader clazzLoader; List<String> lstClassNames; public JCSharp(String jarNames) throws Throwable{ if(crlf == null)crlf= System.getProperty("line.separator"); lstClassNames = new ArrayList<String>(); if(clazzLoader == null) clazzLoader = this.getJarClassLoader(jarNames, this.getClass().getClassLoader()); } @SuppressWarnings("unused") private void addClassLaoder(String jarNames) throws Throwable { lstClassNames.clear(); ClassLoader newClazzLoader = this.getJarClassLoader(jarNames, clazzLoader); if(newClazzLoader != clazzLoader)clazzLoader = newClazzLoader; } private ClassLoader getJarClassLoader(String jarNames, ClassLoader parentClassLoader) throws Throwable{ List<URL> lstUrls = new ArrayList<URL>(); for(String jarName : jarNames.split(";")){ //System.out.println(jarName); File file = new File(jarName); if(file.getName().compareToIgnoreCase("jxdo.rjava.jar") == 0)continue; if(!file.exists()) { java.io.FileNotFoundException exp = new java.io.FileNotFoundException(jarName); if(exp.getMessage() == null){ Throwable ta = exp.getCause(); if(ta!=null)throw ta; } throw exp; } this.fillClassNames(jarName); URL jarUrl = new URL("jar", "","file:" + file.getAbsolutePath()+"!/"); lstUrls.add(jarUrl); } if(lstUrls.size()==0) return parentClassLoader; URL[] urls = lstUrls.toArray(new URL[0]); return URLClassLoader.newInstance(urls, parentClassLoader); } private void fillClassNames(String jarFileName) throws Throwable{ JarFile jar = new JarFile(jarFileName); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String entry = entries.nextElement().getName(); if(!entry.endsWith(".class"))continue; //System.out.println(entry); String clsName = entry.replaceAll(".class", "").replaceAll("/", "."); lstClassNames.add(clsName); } } List<Class<?>> lstClasses; public void fillClasses(String directoryName) throws Throwable{ if(lstClasses == null) lstClasses = new ArrayList<Class<?>>(); else lstClasses.clear(); //System.out.println(directoryName); List<ClassFile> lst = new ArrayList<ClassFile>(); for(int i=0;i<lstClassNames.size();i++){ String name = lstClassNames.get(i); if(name.indexOf("$") > 0){ continue; } ClassFile cd = new ClassFile(); cd.className = name; lst.add(cd); lstClassNames.remove(i); i-=1; } java.io.File f = new File(directoryName); if(!f.exists())f.mkdirs(); lstFileWriters = new ArrayList<FileWriter>(); this.ForEachCoder(lst,directoryName); for(FileWriter fw : lstFileWriters) fw.close(); } List<FileWriter> lstFileWriters; private void ForEachCoder(List<ClassFile> lst, String directoryName){ for(ClassFile cf : lst){ Class<?> clazz = cf.loadClass(); if(clazz == null)continue; //C#¶ËµÄ½Ó¿Ú²»Ö§³ÖǶÌ× boolean isInterface = clazz.isInterface(); FileWriter fwCurrent = isInterface ? cf.getFileWriter(directoryName) : cf.getParent(cf).getFileWriter(directoryName); String tabs = isInterface ? "\t" : cf.getTabs(); if(!lstFileWriters.contains(fwCurrent)) lstFileWriters.add(fwCurrent); JCSharpOuter jcOuter = new JCSharpOuter(clazz, fwCurrent, isInterface ? false : cf.Postion > 0); jcOuter.writerNamespaceStart(tabs); jcOuter.writerDefineStart(); System.out.println(tabs + cf.className); this.ForEachCoder(cf.getNetseds(), directoryName); jcOuter.writerDefineEnd(); jcOuter.writerNamespaceEnd(); } } public class ClassFile{ String className; int Postion = 0; ClassFile Parent; public List<ClassFile> getNetseds(){ List<ClassFile> netseds = new ArrayList<ClassFile>(); for(int i=0;i<lstClassNames.size();i++){ String ns = lstClassNames.get(i); if(!ns.startsWith(className))continue; int level = ns.split("\\$").length - 1; if(level == Postion +1) { ClassFile cd = new ClassFile(); cd.className = ns; cd.Postion = level; cd.Parent = this; netseds.add(cd); lstClassNames.remove(i); i-=1; } } return netseds; } ClassFile cfSearchParent; private ClassFile getParent(ClassFile cf){ if(cfSearchParent == null) searchParent(cf); return cfSearchParent; } private void searchParent(ClassFile cf){ if(cf.Parent == null){ cfSearchParent = cf; return; } searchParent(cf.Parent); //cf.Level += 1; } Class<?> cls; public Class<?> loadClass(){ if(cls == null){ try { cls = clazzLoader.loadClass(this.className); } catch (ClassNotFoundException e) { return null; } int im = cls.getModifiers(); if(!Modifier.isPublic(im)) return null; } return cls; } String _tabs; public String getTabs(){ if(_tabs == null){ String s = "\t"; for(int i=0;i<this.Postion;i++) s += "\t"; _tabs = s; } return _tabs; } FileWriter fw; public FileWriter getFileWriter(String directoryName){ if(fw == null){ String csFileName = className.replace('$', '.'); // if(csFileName.indexOf(".") > -1) // csFileName = csFileName.substring(csFileName.indexOf(".") + 1, csFileName.length() + 2 - csFileName.indexOf(".")); // if(csFileName.indexOf("$") > -1) // csFileName = csFileName.substring(csFileName.indexOf("$") + 1, csFileName.length() + 2 - csFileName.indexOf("$")); File f = new File(directoryName + File.separator + csFileName + ".cs"); if(f.exists())f.delete(); boolean isCreated; try { isCreated = f.createNewFile(); } catch (IOException e) { isCreated = false; } if(!isCreated)return null; try { fw = new FileWriter(f); } catch (IOException e) { return null; } } return fw; } } public static void main(String[] args) throws Throwable { //home // String fname = "E:\\DotNet2010\\NXDO.Mixed\\NXDO.Mixed.V2015\\Tester\\RJavaX64\\bin\\Debug\\jforloaded.jar"; // JCSharp jf = new JCSharp(fname); // jf.fillClasses("E:\\DotNet2010\\NXDO.Mixed\\nxdo.jacoste"); //ltd String fname = "E:\\DotNet2012\\CSharp2Java\\NXDO.Mixed.V2015\\Tester\\RJavaX64\\bin\\Debug\\jforloaded.jar"; JCSharp jf = new JCSharp(fname); jf.fillClasses("E:\\DotNet2012\\CSharp2Java\\nxdo.jacoste"); } }
mit
AdoHe/ODataSync
src/main/java/com/ado/java/odata/pool/Pool.java
698
package com.ado.java.odata.pool; import java.sql.Connection; import java.sql.SQLException; public interface Pool { /** * Make a new connection * * @throws SQLException */ Connection makeConnection() throws SQLException; /** * Gets a valid connection from the connection pool * * @return a valid connection from the pool * @throws SQLException */ Connection getConnection() throws SQLException; /** * Return a connection into the connection pool * * @param connection the connection to return to the pool * @throws SQLException */ void returnConnection(Connection connection) throws SQLException; }
mit
goldenapple3/CopperTools
src/api/vazkii/botania/api/corporea/CorporeaHelper.java
11357
/** * This class was created by <Vazkii>. It's distributed as * part of the Botania Mod. Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php * * File Created @ [Feb 14, 2015, 3:28:54 PM (GMT)] */ package vazkii.botania.api.corporea; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; public final class CorporeaHelper { private static final List<IInventory> empty = Collections.unmodifiableList(new ArrayList()); private static final WeakHashMap<List<ICorporeaSpark>, List<IInventory>> cachedNetworks = new WeakHashMap(); public static final String[] WILDCARD_STRINGS = new String[] { "...", "~", "+", "?" , "*" }; /** * How many items were matched in the last request. If java had "out" params like C# this wouldn't be needed :V */ public static int lastRequestMatches = 0; /** * How many items were extracted in the last request. */ public static int lastRequestExtractions = 0; /** * Gets a list of all the inventories on this spark network. This list is cached for use once every tick, * and if something changes during that tick it'll still have the first result. */ public static List<IInventory> getInventoriesOnNetwork(ICorporeaSpark spark) { ICorporeaSpark master = spark.getMaster(); if(master == null) return empty; List<ICorporeaSpark> network = master.getConnections(); if(cachedNetworks.containsKey(network)) { List<IInventory> cache = cachedNetworks.get(network); if(cache != null) return cache; } List<IInventory> inventories = new ArrayList(); if(network != null) for(ICorporeaSpark otherSpark : network) if(otherSpark != null) { IInventory inv = otherSpark.getInventory(); if(inv != null) inventories.add(inv); } cachedNetworks.put(network, inventories); return inventories; } /** * Gets the amount of available items in the network of the type passed in, checking NBT or not. * The higher level functions that use a List< IInventory > or a Map< IInventory, Integer > should be * called instead if the context for those exists to avoid having to get the values again. */ public static int getCountInNetwork(ItemStack stack, ICorporeaSpark spark, boolean checkNBT) { List<IInventory> inventories = getInventoriesOnNetwork(spark); return getCountInNetwork(stack, inventories, checkNBT); } /** * Gets the amount of available items in the network of the type passed in, checking NBT or not. * The higher level function that use a Map< IInventory, Integer > should be * called instead if the context for this exists to avoid having to get the value again. */ public static int getCountInNetwork(ItemStack stack, List<IInventory> inventories, boolean checkNBT) { Map<IInventory, Integer> map = getInventoriesWithItemInNetwork(stack, inventories, checkNBT); return getCountInNetwork(stack, map, checkNBT); } /** * Gets the amount of available items in the network of the type passed in, checking NBT or not. */ public static int getCountInNetwork(ItemStack stack, Map<IInventory, Integer> inventories, boolean checkNBT) { int count = 0; for(IInventory inv : inventories.keySet()) count += inventories.get(inv); return count; } /** * Gets a Map mapping IInventories to the amount of items of the type passed in that exist * The higher level function that use a List< IInventory > should be * called instead if the context for this exists to avoid having to get the value again. */ public static Map<IInventory, Integer> getInventoriesWithItemInNetwork(ItemStack stack, ICorporeaSpark spark, boolean checkNBT) { List<IInventory> inventories = getInventoriesOnNetwork(spark); return getInventoriesWithItemInNetwork(stack, inventories, checkNBT); } /** * Gets a Map mapping IInventories to the amount of items of the type passed in that exist * The deeper level function that use a List< IInventory > should be * called instead if the context for this exists to avoid having to get the value again. */ public static Map<IInventory, Integer> getInventoriesWithItemInNetwork(ItemStack stack, List<IInventory> inventories, boolean checkNBT) { Map<IInventory, Integer> countMap = new HashMap(); for(IInventory inv : inventories) { int count = 0; for(int i = 0; i < inv.getSizeInventory(); i++) { if(!isValidSlot(inv, i)) continue; ItemStack stackAt = inv.getStackInSlot(i); if(stacksMatch(stack, stackAt, checkNBT)) count += stackAt.stackSize; } if(count > 0) countMap.put(inv, count); } return countMap; } /** * Bridge for requestItem() using an ItemStack. */ public static List<ItemStack> requestItem(ItemStack stack, ICorporeaSpark spark, boolean checkNBT, boolean doit) { return requestItem(stack, stack.stackSize, spark, checkNBT, doit); } /** * Bridge for requestItem() using a String and an item count. */ public static List<ItemStack> requestItem(String name, int count, ICorporeaSpark spark, boolean doit) { return requestItem(name, count, spark, false, doit); } /** * Requests list of ItemStacks of the type passed in from the network, or tries to, checking NBT or not. * This will remove the items from the adequate inventories unless the "doit" parameter is false. * Returns a new list of ItemStacks of the items acquired or an empty list if none was found. * Case itemCount is -1 it'll find EVERY item it can. * <br><br> * The "matcher" parameter has to be an ItemStack or a String, if the first it'll check if the * two stacks are similar using the "checkNBT" parameter, else it'll check if the name of the item * equals or matches (case a regex is passed in) the matcher string. */ public static List<ItemStack> requestItem(Object matcher, int itemCount, ICorporeaSpark spark, boolean checkNBT, boolean doit) { List<ItemStack> stacks = new ArrayList(); CorporeaRequestEvent event = new CorporeaRequestEvent(matcher, itemCount, spark, checkNBT, doit); if(MinecraftForge.EVENT_BUS.post(event)) return stacks; List<IInventory> inventories = getInventoriesOnNetwork(spark); Map<ICorporeaInterceptor, ICorporeaSpark> interceptors = new HashMap(); lastRequestMatches = 0; lastRequestExtractions = 0; int count = itemCount; for(IInventory inv : inventories) { ICorporeaSpark invSpark = getSparkForInventory(inv); if(inv instanceof ICorporeaInterceptor) { ICorporeaInterceptor interceptor = (ICorporeaInterceptor) inv; interceptor.interceptRequest(matcher, itemCount, invSpark, spark, stacks, inventories, doit); interceptors.put(interceptor, invSpark); } for(int i = inv.getSizeInventory() - 1; i >= 0; i--) { if(!isValidSlot(inv, i)) continue; ItemStack stackAt = inv.getStackInSlot(i); if(matcher instanceof ItemStack ? stacksMatch((ItemStack) matcher, stackAt, checkNBT) : matcher instanceof String ? stacksMatch(stackAt, (String) matcher) : false) { int rem = Math.min(stackAt.stackSize, count == -1 ? stackAt.stackSize : count); if(rem > 0) { ItemStack copy = stackAt.copy(); if(rem < copy.stackSize) copy.stackSize = rem; stacks.add(copy); } lastRequestMatches += stackAt.stackSize; lastRequestExtractions += rem; if(doit && rem > 0) { inv.decrStackSize(i, rem); if(invSpark != null) invSpark.onItemExtracted(stackAt); } if(count != -1) count -= rem; } } } for(ICorporeaInterceptor interceptor : interceptors.keySet()) interceptor.interceptRequestLast(matcher, itemCount, interceptors.get(interceptor), spark, stacks, inventories, doit); return stacks; } /** * Gets the spark attached to the inventory passed case it's a TileEntity. */ public static ICorporeaSpark getSparkForInventory(IInventory inv) { if(!(inv instanceof TileEntity)) return null; TileEntity tile = (TileEntity) inv; return getSparkForBlock(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord); } /** * Gets the spark attached to the block in the coords passed in. Note that the coords passed * in are for the block that the spark will be on, not the coords of the spark itself. */ public static ICorporeaSpark getSparkForBlock(World world, int x, int y, int z) { List<ICorporeaSpark> sparks = world.getEntitiesWithinAABB(ICorporeaSpark.class, AxisAlignedBB.getBoundingBox(x, y + 1, z, x + 1, y + 2, z + 1)); return sparks.isEmpty() ? null : sparks.get(0); } /** * Gets if the block in the coords passed in has a spark attached. Note that the coords passed * in are for the block that the spark will be on, not the coords of the spark itself. */ public static boolean doesBlockHaveSpark(World world, int x, int y, int z) { return getSparkForBlock(world, x, y, z) != null; } /** * Gets if the slot passed in can be extracted from by a spark. */ public static boolean isValidSlot(IInventory inv, int slot) { return !(inv instanceof ISidedInventory) || arrayHas(((ISidedInventory) inv).getAccessibleSlotsFromSide(ForgeDirection.UP.ordinal()), slot) && ((ISidedInventory) inv).canExtractItem(slot, inv.getStackInSlot(slot), ForgeDirection.UP.ordinal()); } /** * Gets if two stacks match. */ public static boolean stacksMatch(ItemStack stack1, ItemStack stack2, boolean checkNBT) { return stack1 != null && stack2 != null && stack1.isItemEqual(stack2) && (!checkNBT || ItemStack.areItemStackTagsEqual(stack1, stack2)); } /** * Gets if the name of a stack matches the string passed in. */ public static boolean stacksMatch(ItemStack stack, String s) { if(stack == null) return false; boolean contains = false; for(String wc : WILDCARD_STRINGS) { if(s.endsWith(wc)) { contains = true; s = s.substring(0, s.length() - wc.length()); } else if(s.startsWith(wc)) { contains = true; s = s.substring(wc.length()); } if(contains) break; } String name = stack.getDisplayName().toLowerCase().trim(); return equalOrContain(name, s, contains) || equalOrContain(name + "s", s, contains) || equalOrContain(name + "es", s, contains) || name.endsWith("y") && equalOrContain(name.substring(0, name.length() - 1) + "ies", s, contains); } /** * Clears the cached networks, called once per tick, should not be called outside * of the botania code. */ public static void clearCache() { cachedNetworks.clear(); } /** * Helper method to check if an int array contains an int. */ public static boolean arrayHas(int[] arr, int val) { for (int element : arr) if(element == val) return true; return false; } /** * Helper method to make stacksMatch() less messy. */ public static boolean equalOrContain(String s1, String s2, boolean contain) { return contain ? s1.contains(s2) : s1.equals(s2); } }
mit
LLionel/sefa
src/cn/sefa/test/combinator/Result.java
1109
/** * */ package cn.sefa.test.combinator; /** * @author Lionel * */ public class Result { private String recognized ; private String remaining; private boolean succeeded ; private Result(String recognized , String remaining , boolean succeeded){ this.recognized = recognized; this.remaining = remaining; this.succeeded = succeeded; } /** * @return the recognized */ public String getRecognized() { return recognized; } /** * @param recognized the recognized to set */ public void setRecognized(String recognized) { this.recognized = recognized; } /** * @return the remaining */ public String getRemaining() { return remaining; } public void setRemaining(String remaining) { this.remaining = remaining; } public boolean isSucceeded() { return succeeded; } public void setSucceeded(boolean succeeded) { this.succeeded = succeeded; } public static Result succeed(String recognized , String remaining){ return new Result(recognized,remaining,true); } public static Result fail(){ return new Result("","",false); } }
mit
hustcalm/elasticsearch-hotsearch
wap-gen-data/src/com/cgroups/gendata/RandomEntry.java
2458
package com.cgroups.gendata; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class RandomEntry { private ArrayList<String> words; private ArrayList<Double> weights; Random random = null; private double total_weight; public RandomEntry(){ this.init_menbers(); } /** * @param word_path Path of the file listing the words * @param weights_path Path of the file listing weights of each word */ public RandomEntry(String word_path, String weights_path){ this.init_menbers(); BufferedReader br1 = null; BufferedReader br2 = null; try{ br1 = new BufferedReader(new FileReader(word_path)); br2 = new BufferedReader(new FileReader(weights_path)); while (true){ String line1=null, line2=null; line1 = br1.readLine(); line2 = br2.readLine(); if (line1==null || line2==null) break; double weight; try{ weight = Double.parseDouble(line2); }catch (NumberFormatException e){ continue; } words.add(line1); weights.add(weight); total_weight += weight; } }catch(IOException e){ e.printStackTrace(); }finally{ try{br1.close(); br2.close();} catch (Exception e){} } } /** * @return A random word */ public String getNextWord(){ double rnumber = random.nextDouble(); double offset = rnumber*total_weight; //get the index int i; for (i=0; i<weights.size(); i++){ double weight = weights.get(i); if (weight + 0.000001>=offset) break; offset = offset - weight; } if (i>=0 && i < weights.size()) return words.get(i); return null; } private void init_menbers(){ random = new Random(); words = new ArrayList<String>(); weights = new ArrayList<Double>(); total_weight = 0.0; } public void addWordsWithEqualWeight(String path){ this.addWordsWithEqualWeight(path, 1.0); } public void addWordsWithEqualWeight(String path, double weight){ BufferedReader br = null; try{ br = new BufferedReader(new FileReader(path)); while (true){ String line = br.readLine(); if (line == null) break; if (line.equals("")) continue; this.words.add(line); this.weights.add(weight); this.total_weight += weight; } }catch(IOException e){ e.printStackTrace(); }finally{ try{br.close();} catch(Exception e){} } } public ArrayList<String> getAllWords(){ return this.words; } }
mit
jsong00505/Coding-Practice
backjoon/src/bj174x/bj1740/Main.java
1203
package bj174x.bj1740; import java.io.PrintWriter; import java.util.Scanner; /** * Created by jsong on 30/03/2017. * * @hackerrank https://www.hackerrank.com/jsong00505 * @backjoon https://www.acmicpc.net/user/jsong00505 * @github https://github.com/jsong00505 * @linkedin https://www.linkedin.com/in/junesongskorea/ * @email jsong00505@gmail.com * @challenge Power of N */ public class Main { /** * Method Name: findNthNumbers * * @param n a 'n'th position * @return a number at 'n'th position */ static long findNthNumbers(long n) { long result = 0; // the flag checking if the element is the last order boolean isLast = false; long t = 1; while (n > 0) { if ((n & 1) == 1) { result += t; } n = n >> 1; t *= 3; } return result; } public static void main(String[] args) { try (Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); ) { // get n long n = in.nextLong(); // validation assert (n >= 1 && n <= (5 * Math.pow(10, 11))); out.println(findNthNumbers(n)); } catch (Exception e) { e.printStackTrace(); } } }
mit
AlphaBAT69/Java-Programs
IOPackage/UsingFileInputStream.java
302
import java.io.IOException; import java.io.FileInputStream; public class UsingFileInputStream{ public static void main(String[] main) throws IOException{ FileInputStream fis=new FileInputStream("file.txt"); int i; while((i=fis.read())!=-1){ System.out.print((char)i); } fis.close(); } }
mit
GitHubRGI/swagd
RGISuite/src/main/java/com/rgi/suite/tilestoreadapter/TileStoreWriterAdapter.java
3466
/* The MIT License (MIT) * * Copyright (c) 2015 Reinventing Geospatial, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.rgi.suite.tilestoreadapter; import java.io.File; import java.util.Collection; import javax.swing.JComponent; import com.rgi.store.tiles.TileStoreException; import com.rgi.store.tiles.TileStoreReader; import com.rgi.store.tiles.TileStoreWriter; import com.rgi.suite.Settings; /** * Abstract base class for UI adapters for tile store writers * * @author Luke Lambert * */ public abstract class TileStoreWriterAdapter { /** * Constructor * * @param settings * Handle to the application's settings object */ public TileStoreWriterAdapter(final Settings settings) { this.settings = settings; } /** * Use an input file to hint at possible values for the UI elements * * @param inputFile * Input file * @throws TileStoreException * if there's a problem with the tile store */ public abstract void hint(final File inputFile) throws TileStoreException; /** * Provides UI elements to use as input to construct a tile store writer * * @return Returns a matrix of UI elements to build an input form that will * provide the inputs to build a corresponding tile store * writer */ public abstract Collection<Collection<JComponent>> getWriterParameterControls(); /** * Constructs a tile store writer based on the values of the UI elements * * @param tileStoreReader * Tile store reader that may be required to know how to build * a tile scheme for our new tile store writer * @return A {@link TileStoreWriter} * @throws TileStoreException * if construction of the tile store reader fails */ public abstract TileStoreWriter getTileStoreWriter(final TileStoreReader tileStoreReader) throws TileStoreException; /** * In the case of a failed tile store operation (e.g. packaging, or tiling) * call this method to clean up the process started by calling {@link * #getTileStoreWriter(TileStoreReader)} * * @throws TileStoreException * if tile store removal fails */ public abstract void removeStore() throws TileStoreException; protected final Settings settings; }
mit
rbrick/Mojo
Core/src/main/java/me/rbrickis/mojo/utils/PrimitiveUtils.java
784
package me.rbrickis.mojo.utils; public final class PrimitiveUtils { public static Object toPrimitiveNumber(Number number) { if (number instanceof Byte) { return number.byteValue(); } else if (number instanceof Long) { return number.longValue(); } else if (number instanceof Short) { return number.shortValue(); } else if (number instanceof Integer) { return number.intValue(); } else if (number instanceof Float) { return number.floatValue(); } else if (number instanceof Double) { return number.doubleValue(); } return 0; } public static Object toPrimitiveBoolean(Boolean booleans) { return booleans.booleanValue(); } }
mit
illusionww/gpsHub
client/app/src/main/java/com/gpshub/api/AccountManager.java
2355
package com.gpshub.api; import android.util.Log; import com.gpshub.utils.Preferences; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class AccountManager { private static final String TAG = AccountManager.class.getSimpleName(); public static final int RESULT_SUCCESS = 1; public static final int RESULT_WRONG_NUMBER = 2; public static final int RESULT_ERROR = 3; public static int login(String url, String driver_id) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("company_hash", "qwerty")); nameValuePairs.add(new BasicNameValuePair("id", driver_id)); String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url + "/actions/drivers.php?" + paramString); try { HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); String responseText = EntityUtils.toString(entity); Log.i(TAG, "login result: " + responseText); if ("OK".equals(responseText)) { Preferences.setServerUrl(url); Preferences.setDriverID(driver_id); return RESULT_SUCCESS; } } catch (IOException e) { return RESULT_ERROR; } return RESULT_WRONG_NUMBER; } public static void logout() { Preferences.wipeAccountSettings(); Log.i(TAG, "logout"); } public static boolean isLoggedIn() { String server_url = Preferences.getServerUrl(); String driver_id = Preferences.getDriverID(); Log.i(TAG, "logged in: server_url: " + server_url + ", driver_id: " + driver_id); return server_url != null && driver_id != null || Preferences.tryMigration(); } }
mit
Daeliin/java-components
components-persistence/src/main/java/com/daeliin/components/persistence/resource/repository/BaseRepository.java
3785
package com.daeliin.components.persistence.resource.repository; import com.daeliin.components.core.pagination.Page; import com.daeliin.components.core.pagination.PageRequest; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.Predicate; import com.querydsl.sql.RelationalPathBase; import com.querydsl.sql.SQLQuery; import com.querydsl.sql.SQLQueryFactory; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.Collection; import java.util.Objects; import java.util.Optional; /** * @param <R> row type */ public class BaseRepository<R> implements PagingRepository<R> { @Inject protected SQLQueryFactory queryFactory; protected final RowOrder rowOrder; protected final RelationalPathBase<R> rowPath; public BaseRepository(RelationalPathBase<R> rowPath) { this.rowPath = Objects.requireNonNull(rowPath); this.rowOrder = new RowOrder(rowPath); } @Override public RelationalPathBase<R> rowPath() { return rowPath; } @Transactional(readOnly = true) @Override public Optional<R> findOne(Predicate predicate) { if (predicate == null) { return Optional.empty(); } return Optional.ofNullable(queryFactory.select(rowPath) .from(rowPath) .where(predicate) .fetchOne()); } @Transactional(readOnly = true) @Override public Collection<R> findAll(Predicate predicate) { SQLQuery<R> query = queryFactory.select(rowPath) .from(rowPath); if (predicate != null) { query = query.where(predicate); } return query.fetch(); } @Transactional(readOnly = true) @Override public Page<R> findAll(PageRequest pageRequest) { return findAll(null, pageRequest); } @Transactional(readOnly = true) @Override public Page<R> findAll(Predicate predicate, PageRequest pageRequest) { long totalItems = count(predicate); long totalPages = rowOrder.computeTotalPages(totalItems, pageRequest.size); OrderSpecifier[] orders = rowOrder.computeOrders(pageRequest); SQLQuery<R> query = queryFactory.select(rowPath) .from(rowPath) .limit(pageRequest.size) .offset(pageRequest.offset) .orderBy(orders); if (predicate != null) { query = query.where(predicate); } return new Page<>(query.fetch(), totalItems, totalPages); } @Transactional(readOnly = true) @Override public Collection<R> findAll() { return queryFactory.select(rowPath) .from(rowPath) .fetch(); } @Transactional(readOnly = true) @Override public long count() { return queryFactory.select(rowPath) .from(rowPath) .fetchCount(); } @Transactional(readOnly = true) @Override public long count(Predicate predicate) { SQLQuery<R> query = queryFactory.select(rowPath) .from(rowPath); if (predicate != null) { query = query.where(predicate); } return query.fetchCount(); } @Transactional @Override public boolean delete(Predicate predicate) { if (predicate == null) { throw new IllegalArgumentException("Predicate should not be null on a delete, otherwise whole table will be deleted, " + "call deleteAll() instead if it's the desired operation"); } return queryFactory.delete(rowPath).where(predicate).execute() > 0; } @Transactional @Override public boolean deleteAll() { return queryFactory.delete(rowPath).execute() > 0; } }
mit
TempestasLudi/CSS-Preprocessor
src/test/java/com/tempestasludi/java/p14_cssp/pcss/selectors/IdTest.java
347
package com.tempestasludi.java.p14_cssp.pcss.selectors; import static org.junit.Assert.*; import org.junit.Test; public class IdTest { @Test public void testId() { Id id = new Id("main"); assertEquals("main", id.getName()); } @Test public void testToString() { Id id = new Id("main"); assertEquals("#main", id.toString()); } }
mit
theotherside/TrackerBill
gen/com/example/billtracker/R.java
2608
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.example.billtracker; public final class R { public static final class attr { } public static final class dimen { /** Default screen margins, per the Android Design guidelines. Customize dimensions originally defined in res/values/dimens.xml (such as screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here. */ public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f080002; public static final int calendar_main=0x7f080001; public static final int text_view_calendar=0x7f080000; } public static final class layout { public static final int activity_calendar=0x7f030000; } public static final class menu { public static final int calendar=0x7f070000; public static final int main=0x7f070001; } public static final class string { public static final int action_settings=0x7f050001; public static final int app_name=0x7f050000; public static final int hello_world=0x7f050002; } public static final class style { /** Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. Base application theme for API 11+. This theme completely replaces AppBaseTheme from res/values/styles.xml on API 11+ devices. API 11 theme customizations can go here. Base application theme for API 14+. This theme completely replaces AppBaseTheme from BOTH res/values/styles.xml and res/values-v11/styles.xml on API 14+ devices. API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f060000; /** Application theme. All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f060001; } }
mit
kocsenc/java-swing-htmleditor
src/command/ShutDownCommand.java
1323
package TeamTwoHTMLEditor.command; import TeamTwoHTMLEditor.CommandDistributor; import TeamTwoHTMLEditor.CommandMediator; import TeamTwoHTMLEditor.GUI.EditorFrame; import javax.swing.*; /** * Created with IntelliJ IDEA. User: Kocsen Date: 3/22/13 Time: 2:16 PM */ public class ShutDownCommand implements Command{ private final ActiveContext context; public ShutDownCommand(ActiveContext context){ this.context = context; } /** * Checks if the editor can quit based on the save state of the files. If * all files are saved, the editor quit, else an interruption option pane is * shown to prevent the shutdown operation. * * @param c - Command distributor who has a reference access to the * FileManager */ @Override public void execute(CommandDistributor c, CommandMediator cmd){ if(c.getFileManager().canQuit()){ context.getParent().dispose(); System.out.println("Shutting Down System"); } else{ int n = JOptionPane.showConfirmDialog( context.getParent(), "There are some unsaved files, would you like to quit anyway?", "Unsaved Files", JOptionPane.YES_NO_OPTION); if(n == JOptionPane.YES_OPTION){ context.getParent().dispose(); System.out.println("Shutting Down System"); } else{ } } c.getFileManager().printStatus(); } }
mit
plafue/writeily-nightly
app/src/main/java/me/writeily/pro/settings/SettingsFragment.java
6459
package me.writeily.pro.settings; import android.app.Activity; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import me.writeily.pro.AlphanumericPinActivity; import me.writeily.pro.PinActivity; import me.writeily.pro.R; import me.writeily.pro.dialog.FilesystemDialog; import me.writeily.pro.model.Constants; /** * Created by jeff on 2014-04-11. */ public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { WriteilySettingsListener mCallback; ListPreference pinPreference; Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); context = getActivity().getApplicationContext(); pinPreference = (ListPreference) findPreference(getString(R.string.pref_lock_type_key)); updateLockSummary(); // Listen for Pin Preference change pinPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object o) { String lockType = (String) o; if (lockType == null || lockType.equals("") || getString(R.string.pref_no_lock_value).equals(lockType)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putString(Constants.USER_PIN_KEY, "").apply(); editor.putString(getString(R.string.pref_lock_type_key), getString(R.string.pref_no_lock_value)).apply(); pinPreference.setSummary(PreferenceManager.getDefaultSharedPreferences(context) .getString(getString(R.string.pref_no_lock_value), getString(R.string.pref_no_lock))); return true; } else if (getString(R.string.pref_pin_lock_value).equals(lockType)) { Intent pinIntent = new Intent(context, PinActivity.class); pinIntent.setAction(Constants.SET_PIN_ACTION); startActivityForResult(pinIntent, Constants.SET_PIN_REQUEST_CODE); } else if (getString(R.string.pref_alpha_pin_lock_value).equals(lockType)) { Intent pinIntent = new Intent(context, AlphanumericPinActivity.class); pinIntent.setAction(Constants.SET_PIN_ACTION); startActivityForResult(pinIntent, Constants.SET_PIN_REQUEST_CODE); } return false; } }); // Register PreferenceChangeListener getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // Workaround for About-Screen Preference aboutScreen = (Preference) findPreference(getString(R.string.pref_about_key)); aboutScreen.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (mCallback == null) { return false; } mCallback.onAboutClicked(); return true; } }); setUpStorageDirPreference(); } private void setUpStorageDirPreference() { final Preference rootDir = (Preference) findPreference(getString(R.string.pref_root_directory)); rootDir.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { FragmentManager fragManager = getFragmentManager(); Bundle args = new Bundle(); args.putString(Constants.FILESYSTEM_ACTIVITY_ACCESS_TYPE_KEY, Constants.FILESYSTEM_SELECT_FOLDER_ACCESS_TYPE); FilesystemDialog filesystemDialog = new FilesystemDialog(); filesystemDialog.setArguments(args); filesystemDialog.show(fragManager, Constants.FILESYSTEM_SELECT_FOLDER_TAG); return true; } }); updateRootDirSummary(); } public void updateRootDirSummary() { Preference rootDir = findPreference(getString(R.string.pref_root_directory));; rootDir.setSummary(PreferenceManager.getDefaultSharedPreferences(context).getString(getString(R.string.pref_root_directory), Constants.DEFAULT_WRITEILY_STORAGE_FOLDER)); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.SET_PIN_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { updateLockSummary(); } } } private void updateLockSummary() { Integer currentLockType = Integer.valueOf(PreferenceManager.getDefaultSharedPreferences(context).getString(getString(R.string.pref_lock_type_key), "0")); pinPreference.setSummary(getResources().getStringArray(R.array.possibleLocksStrings)[currentLockType]); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { ActionBarActivity activity = (ActionBarActivity) mCallback; if (activity.getString(R.string.pref_theme_key).equals(key)) { mCallback.onThemeChanged(); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); // Make sure the container has implemented the callback interface try { mCallback = (WriteilySettingsListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + "must implement OnThemeChangedListener"); } } // Needed for callback to container activity public interface WriteilySettingsListener { public void onThemeChanged(); public void onAboutClicked(); } }
mit
lreimer/secure-programming-101
secpro-mlr01-j/src/main/java/de/qaware/campus/secpro/mlr01/TheUnsafe.java
4023
/* * The MIT License (MIT) * * Copyright (c) 2015 QAware GmbH, Munich, Germany * * 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 de.qaware.campus.secpro.mlr01; import sun.misc.Unsafe; import java.lang.reflect.Field; /** * Special factory to obtain unsafe instance. Ideas and code are taken from * http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/ * * @author mario-leander.reimer */ public final class TheUnsafe { /** * Utility factory class. No instances. */ private TheUnsafe() { } /** * Factory method for Unsafe instances. * * @return an Unsafe instance */ public static Unsafe getInstance() { try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (Unsafe) f.get(null); } catch (NoSuchFieldException | SecurityException | IllegalAccessException e) { throw new IllegalStateException(e); } } /** * Convert object to its address in memory. * * @param obj the object * @return the address in memory */ public static long toAddress(Object obj) { Object[] array = new Object[]{obj}; long baseOffset = getInstance().arrayBaseOffset(Object[].class); return normalize(getInstance().getInt(array, baseOffset)); } /** * Convert address to associated object in memory. * * @param address the address * @return the object */ public static Object fromAddress(long address) { Object[] array = new Object[]{null}; long baseOffset = getInstance().arrayBaseOffset(Object[].class); getInstance().putLong(array, baseOffset, address); return array[0]; } /** * Obtain a copy of the given object. No Cloneable required. * * @param obj the object to copy * @return the copy */ public static Object shallowCopy(Object obj) { long size = sizeOf(obj); long start = toAddress(obj); Unsafe instance = getInstance(); long address = instance.allocateMemory(size); instance.copyMemory(start, address, size); return fromAddress(address); } /** * Much simpler sizeOf can be achieved if we just read size value from the class * struct for this object, which located with offset 12 in JVM 1.7 32 bit. * * @param object the object instance * @return the size of the object */ public static long sizeOf(Object object) { Unsafe instance = getInstance(); return instance.getAddress(normalize(instance.getInt(object, 4L)) + 12L); } /** * Normalize is a method for casting signed int to unsigned long, for correct address usage. * * @param value the signed int * @return an unsigned long */ private static long normalize(int value) { if (value >= 0) return value; return (~0L >>> 32) & value; } }
mit
bbuenz/provisions
src/main/java/edu/stanford/crypto/proof/assets/AddressProof.java
5567
/* * Decompiled with CFR 0_110. */ package edu.stanford.crypto.proof.assets; import edu.stanford.crypto.ECConstants; import edu.stanford.crypto.proof.MemoryProof; import org.bouncycastle.math.ec.ECPoint; import java.math.BigInteger; import java.util.Arrays; import java.util.List; public class AddressProof implements MemoryProof { private final ECPoint commitmentBalance; private final ECPoint commitmentXHat; private final BigInteger challengeZero; private final BigInteger challengeOne; private final BigInteger responseS; private final BigInteger responseV; private final BigInteger responseT; private final BigInteger responseXHat; private final BigInteger responseZero; private final BigInteger responseOne; public AddressProof(ECPoint commitmentBalance, ECPoint commitmentXHat, BigInteger challengeZero, BigInteger challengeOne, BigInteger responseS, BigInteger responseV, BigInteger responseT, BigInteger responseXHat, BigInteger responseZero, BigInteger responseOne) { this.commitmentBalance = commitmentBalance; this.commitmentXHat = commitmentXHat; this.challengeZero = challengeZero; this.challengeOne = challengeOne; this.responseS = responseS; this.responseV = responseV; this.responseT = responseT; this.responseXHat = responseXHat; this.responseZero = responseZero; this.responseOne = responseOne; } public AddressProof(byte[] array) { int index = 0; byte statementLength = array[index++]; this.commitmentBalance = ECConstants.BITCOIN_CURVE.decodePoint(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.commitmentXHat = ECConstants.BITCOIN_CURVE.decodePoint(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.challengeZero = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.challengeOne = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseS = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseT = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseV = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseXHat = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseZero = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); index += statementLength; statementLength = array[index++]; this.responseOne = new BigInteger(Arrays.copyOfRange(array, index, statementLength + index)); } @Override public byte[] serialize() { byte[] commitmentBalanceEncoded = this.commitmentBalance.getEncoded(true); byte[] commitmentXHatEncoded = this.commitmentXHat.getEncoded(true); byte[] challengeZeroEncoded = this.challengeZero.toByteArray(); byte[] challengeOneEncoded = this.challengeOne.toByteArray(); byte[] responseSEncoded = this.responseS.toByteArray(); byte[] responseTEncoded = this.responseT.toByteArray(); byte[] responseVEncoded = this.responseV.toByteArray(); byte[] responseXHatEncoded = this.responseXHat.toByteArray(); byte[] responseZeroEncoded = this.responseZero.toByteArray(); byte[] responseOneEncoded = this.responseOne.toByteArray(); List<byte[]> arrList = Arrays.asList(commitmentBalanceEncoded, commitmentXHatEncoded, challengeZeroEncoded, challengeOneEncoded,responseSEncoded, responseTEncoded, responseVEncoded, responseXHatEncoded, responseZeroEncoded, responseOneEncoded); int totalLength = arrList.stream().mapToInt(arr -> arr.length).map(i -> i + 1).sum(); byte[] fullArray = new byte[totalLength]; int currIndex = 0; for (byte[] arr2 : arrList) { fullArray[currIndex++] = (byte) arr2.length; System.arraycopy(arr2, 0, fullArray, currIndex, arr2.length); currIndex += arr2.length; } return fullArray; } public BigInteger getChallengeZero() { return this.challengeZero; } public BigInteger getChallengeOne() { return challengeOne; } public BigInteger getResponseS() { return this.responseS; } public ECPoint getCommitmentBalance() { return this.commitmentBalance; } public ECPoint getCommitmentXHat() { return this.commitmentXHat; } public BigInteger getResponseV() { return this.responseV; } public BigInteger getResponseT() { return this.responseT; } public BigInteger getResponseXHat() { return this.responseXHat; } public BigInteger getResponseZero() { return responseZero; } public BigInteger getResponseOne() { return responseOne; } }
mit
Nirespire/Rogo
Android/src/com/rogoapp/LoginActivity.java
2167
package com.rogoapp; import com.rogoapp.auth.RegisterActivity; import android.app.Activity; import android.accounts.AccountAuthenticatorActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class LoginActivity extends Activity { EditText email; EditText password; Button loginButton; Button cancelButton; TextView registerButton; public static final String PARAM_AUTHTOKEN_TYPE = "auth.token"; public static final String PARAM_CREATE = "create"; public static final int REQ_CODE_CREATE = 1; public static final int REQ_CODE_UPDATE = 2; public static final String EXTRA_REQUEST_CODE = "req.code"; public static final int RESP_CODE_SUCCESS = 0; public static final int RESP_CODE_ERROR = 1; public static final int RESP_CODE_CANCEL = 2; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.login); } public void onClick(View v) { // Switch to main activity Intent i = new Intent(getApplicationContext(),MainScreenActivity.class); startActivity(i); } public void addListenerOnButton1() { registerButton = (Button) findViewById(R.id.link_to_register); registerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { openRegistrationScreen(arg0); } }); } public void openRegistrationScreen(View v){ final Context context = this; Intent intent = new Intent(context, RegisterActivity.class); startActivity(intent); } public void onCancelClick(View V){ System.exit(0); } public void addListenerOnButtonCancel(){ cancelButton = (Button) findViewById(R.id.on_Cancel_Click); cancelButton.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0){ openRegistrationScreen(arg0); } }); } }
mit
adben002/test-data-builder
core/src/main/java/com/adben/testdatabuilder/core/analyzers/generators/generator/BooleanGenerator.java
1657
package com.adben.testdatabuilder.core.analyzers.generators.generator; import static com.adben.testdatabuilder.core.helper.ReflectionHelper.getClz; import static java.lang.invoke.MethodHandles.lookup; import static org.slf4j.LoggerFactory.getLogger; import com.google.common.base.MoreObjects; import java.lang.reflect.Type; import java.util.Objects; import org.slf4j.Logger; /** * {@link com.adben.testdatabuilder.core.analyzers.generators.Generator Generator} for {@link * Boolean}. * * <p> * * {@link BooleanGenerator#currValue} starts at false, then flip flops from there. */ public class BooleanGenerator extends AbstractGenerator<Boolean> { private static final Logger LOGGER = getLogger(lookup().lookupClass()); private boolean currValue = false; /** * Default constructor. */ public BooleanGenerator() { super(); LOGGER.trace("Default constructor"); } /** * Applicable type is {@link Boolean} or boolean. * * <p> * * {@inheritDoc} */ @Override protected boolean isApplicable(final Type type) { return Boolean.class.isAssignableFrom(getClz(type)) || Objects.equals(getClz(type), boolean.class); } /** * Get the next value for this generator, and flip the boolean value. * * <p> * * {@inheritDoc} */ @Override protected Boolean getNextValue(final Type type) { try { return this.currValue; } finally { this.currValue = !this.currValue; } } @Override public String toString() { LOGGER.trace("toString"); return MoreObjects.toStringHelper(this) .add("currValue", this.currValue) .toString(); } }
mit
rzhilkibaev/demo-simple-web
demo-store/src/main/java/org/simplemart/product/health/PingHealthCheck.java
245
package org.simplemart.product.health; import com.codahale.metrics.health.HealthCheck; public class PingHealthCheck extends HealthCheck { @Override protected Result check() throws Exception { return Result.healthy(); } }
mit
tdebatty/spark-kmedoids
spark-kmedoids-eval/src/main/java/spark/kmedoids/eval/tv/SimulatedAnnealingTest.java
1585
/* * The MIT License * * Copyright 2017 Thibault Debatty. * * 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 spark.kmedoids.eval.tv; import info.debatty.java.datasets.tv.Sequence; import info.debatty.spark.kmedoids.neighborgenerator.SANeighborGenerator; /** * * @author Thibault Debatty */ public class SimulatedAnnealingTest extends AbstractTest { /** * Return a test instance with a clarans neighbor generator. */ public SimulatedAnnealingTest() { super(new SANeighborGenerator<Sequence>(64000, 0.980)); } }
mit
hckrtst/TIJ
sortingExamples/src/sortingexamples/SortingExamples.java
6022
/* * The MIT License * * Copyright 2015 Sanket K. * * 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 sortingexamples; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Sanket K */ public class SortingExamples { /** * @param args the command line arguments */ public static void main(String[] args) { SortingExamples obj = new SortingExamples(); List<Integer> data = new LinkedList<>(); // TODO add random numbers in a loop data.add(100); data.add(34); data.add(39); data.add(3); data.add(3); data.add(3); //System.out.println("Unsorted list = " + data); //if (obj.insertionSort(data)) { //System.out.println("Sorted list = " + data); //} int [] data2 = {3,5,6,7,8,9,2,2,1000,4111, 377, 178, 3726, 1, 9, 67754, 56425}; System.out.println("Unsorted = " + Arrays.toString(data2)); obj.quickSort(0, data2.length - 1, data2); System.out.println("Sorted = " + Arrays.toString(data2)); } public SortingExamples() { } private void dumpState(int j, List<Integer> list) { for(int i =0; i < list.size(); i++ ) { if (i == j) { System.out.print("(" + list.get(i) + ")"); }else { System.out.print(list.get(i)); } System.out.print(", "); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ex) { Logger.getLogger(SortingExamples.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(""); } public boolean insertionSort(List<Integer> mylist) { if (null == mylist) { System.out.println("Cannot sort a null list"); return false; } if (mylist.isEmpty()) { System.out.println("Cannot sort an empty list"); return false; } for (int i = 1; i < mylist.size(); i++) { int j = i; int testvar = mylist.get(i); System.out.print("Testing " + testvar + ": "); dumpState(j, mylist); while (j > 0 && mylist.get(j-1) > testvar ) { System.out.println(mylist.get(j-1) + " > " + testvar); mylist.set(j, mylist.get(j-1)); //unsorted.set(j-1,0); j = j-1; //dumpState(testvar, data); } mylist.set(j, testvar); } return true; } public boolean shellSort(List<Integer> unsorted) { return false; } private void dump(int i, int j, int pivot, int[] d) { System.out.println(""); for (int k = 0; k < 40; k++) System.out.print("-"); System.out.println(""); int close = 0; for(int k=0; k < d.length; k++) { if (k == i) { System.out.print("i("); close++; } if (k == j) { System.out.print("j("); close++; } if (d[k] == pivot) { System.out.print("p("); close++; } System.out.print(d[k]); while(close > 0) { System.out.print(")"); close--; } System.out.print(", "); } System.out.println(""); } public boolean quickSort(int low, int high, int[] d) { int i = low, j = high; System.out.println("\n\nQuicksort called: low value = " + d[low] + " high value = " + d[high]); // Pivots can be selected many ways int p = low + (high - low)/2; int pivot = d[p]; System.out.println("pivot = " + pivot); while (i <= j) { dump(i, j, pivot, d); System.out.println("\ninc i until d[i]>pivot & dec j until d[j]<pivot"); while (d[i] < pivot) i++; while (d[j] > pivot) j--; dump(i, j, pivot, d); if (i <= j) { swap(i,j, d); System.out.println("\nSwap i & j"); dump(i, j, pivot, d); i++; j--; } } if (low < j) { System.out.println("low < j"); quickSort(low, j, d); } if (i < high) { System.out.println("i < high"); quickSort(i, high, d); } return false; } private void swap(int i, int j, int[] d) { int temp = d[i]; d[i] = d[j]; d[j] = temp; } }
mit
GlowstoneMC/GlowstonePlusPlus
src/main/java/net/glowstone/io/entity/LivingEntityStore.java
13397
package net.glowstone.io.entity; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import net.glowstone.entity.AttributeManager; import net.glowstone.entity.AttributeManager.Property; import net.glowstone.entity.GlowLivingEntity; import net.glowstone.entity.objects.GlowLeashHitch; import net.glowstone.io.nbt.NbtSerialization; import net.glowstone.util.InventoryUtil; import net.glowstone.util.nbt.CompoundTag; import org.bukkit.Location; import org.bukkit.attribute.AttributeModifier; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LeashHitch; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public abstract class LivingEntityStore<T extends GlowLivingEntity> extends EntityStore<T> { public LivingEntityStore(Class<T> clazz, String type) { super(clazz, type); } public LivingEntityStore(Class<T> clazz, EntityType type) { super(clazz, type); } // these tags that apply to living entities only are documented as global: // - short "Air" // - string "CustomName" // - bool "CustomNameVisible" // todo: the following tags // - float "AbsorptionAmount" // - short "HurtTime" // - int "HurtByTimestamp" // - short "DeathTime" // - bool "PersistenceRequired" // on ActiveEffects, bool "ShowParticles" @Override public void load(T entity, CompoundTag compound) { super.load(entity, compound); compound.readShort("Air", entity::setRemainingAir); compound.readString("CustomName", entity::setCustomName); compound.readBoolean("CustomNameVisible", entity::setCustomNameVisible); if (!compound.readFloat("HealF", entity::setHealth)) { compound.readShort("Health", entity::setHealth); } compound.readShort("AttackTime", entity::setNoDamageTicks); compound.readBoolean("FallFlying", entity::setFallFlying); compound.iterateCompoundList("ActiveEffects", effect -> { // should really always have every field, but be forgiving if possible if (!effect.isByte("Id") || !effect.isInt("Duration")) { return; } PotionEffectType type = PotionEffectType.getById(effect.getByte("Id")); int duration = effect.getInt("Duration"); if (type == null || duration < 0) { return; } final int amplifier = compound.tryGetInt("Amplifier").orElse(0); boolean ambient = compound.getBoolean("Ambient", false); // bool "ShowParticles" entity.addPotionEffect(new PotionEffect(type, duration, amplifier, ambient), true); }); EntityEquipment equip = entity.getEquipment(); if (equip != null) { loadEquipment(entity, equip, compound); } compound.readBoolean("CanPickUpLoot", entity::setCanPickupItems); AttributeManager am = entity.getAttributeManager(); compound.iterateCompoundList("Attributes", tag -> { if (!tag.isString("Name") || !tag.isDouble("Base")) { return; } List<AttributeModifier> modifiers = new ArrayList<>(); tag.iterateCompoundList("Modifiers", modifierTag -> { if (modifierTag.isDouble("Amount") && modifierTag.isString("Name") && modifierTag.isInt("Operation") && modifierTag.isLong("UUIDLeast") && modifierTag.isLong("UUIDMost")) { modifiers.add(new AttributeModifier( new UUID(modifierTag.getLong("UUIDLeast"), modifierTag.getLong("UUIDMost")), modifierTag.getString("Name"), modifierTag.getDouble("Amount"), AttributeModifier.Operation.values()[modifierTag.getInt("Operation")])); } }); AttributeManager.Key key = AttributeManager.Key.fromName(tag.getString("Name")); am.setProperty(key, tag.getDouble("Base"), modifiers); }); Optional<CompoundTag> maybeLeash = compound.tryGetCompound("Leash"); if (maybeLeash.isPresent()) { CompoundTag leash = maybeLeash.get(); if (!leash.readUuid("UUIDMost", "UUIDLeast", entity::setLeashHolderUniqueId) && leash.isInt("X") && leash.isInt("Y") && leash.isInt("Z")) { int x = leash.getInt("X"); int y = leash.getInt("Y"); int z = leash.getInt("Z"); LeashHitch leashHitch = GlowLeashHitch .getLeashHitchAt(new Location(entity.getWorld(), x, y, z).getBlock()); entity.setLeashHolder(leashHitch); } } else { compound.readBoolean("Leashed", leashSet -> { if (leashSet) { // We know that there was something leashed, but not what entity it was // This can happen, when for example Minecart got leashed // We still have to make sure that we drop a Leash Item entity.setLeashHolderUniqueId(UUID.randomUUID()); } }); } } private void loadEquipment(T entity, EntityEquipment equip, CompoundTag compound) { // Deprecated since 15w31a, left here for compatibilty for now compound.readCompoundList("Equipment", list -> { equip.setItemInMainHand(getItem(list, 0)); equip.setBoots(getItem(list, 1)); equip.setLeggings(getItem(list, 2)); equip.setChestplate(getItem(list, 3)); equip.setHelmet(getItem(list, 4)); }); // Deprecated since 15w31a, left here for compatibilty for now compound.readFloatList("DropChances", list -> { equip.setItemInMainHandDropChance(getOrDefault(list, 0, 1f)); equip.setBootsDropChance(getOrDefault(list, 1, 1f)); equip.setLeggingsDropChance(getOrDefault(list, 2, 1f)); equip.setChestplateDropChance(getOrDefault(list, 3, 1f)); equip.setHelmetDropChance(getOrDefault(list, 4, 1f)); }); compound.readCompoundList("HandItems", list -> { equip.setItemInMainHand(getItem(list, 0)); equip.setItemInOffHand(getItem(list, 1)); }); compound.readCompoundList("ArmorItems", list -> { equip.setBoots(getItem(list, 0)); equip.setLeggings(getItem(list, 1)); equip.setChestplate(getItem(list, 2)); equip.setHelmet(getItem(list, 3)); }); // set of dropchances on a player throws an UnsupportedOperationException if (!(entity instanceof Player)) { compound.readFloatList("HandDropChances", list -> { equip.setItemInMainHandDropChance(getOrDefault(list, 0, 1f)); equip.setItemInOffHandDropChance(getOrDefault(list, 1, 1f)); }); compound.readFloatList("ArmorDropChances", list -> { equip.setBootsDropChance(getOrDefault(list, 0, 1f)); equip.setLeggingsDropChance(getOrDefault(list, 1, 1f)); equip.setChestplateDropChance(getOrDefault(list, 2, 1f)); equip.setHelmetDropChance(getOrDefault(list, 3, 1f)); }); } } private ItemStack getItem(List<CompoundTag> list, int index) { if (list == null) { return InventoryUtil.createEmptyStack(); } if (index >= list.size()) { return InventoryUtil.createEmptyStack(); } return NbtSerialization.readItem(list.get(index)); } private float getOrDefault(List<Float> list, int index, float defaultValue) { if (list == null) { return defaultValue; } if (index >= list.size()) { return defaultValue; } return list.get(index); } @Override public void save(T entity, CompoundTag tag) { super.save(entity, tag); tag.putShort("Air", entity.getRemainingAir()); if (entity.getCustomName() != null && !entity.getCustomName().isEmpty()) { tag.putString("CustomName", entity.getCustomName()); tag.putBool("CustomNameVisible", entity.isCustomNameVisible()); } tag.putFloat("HealF", entity.getHealth()); tag.putShort("Health", (int) entity.getHealth()); tag.putShort("AttackTime", entity.getNoDamageTicks()); tag.putBool("FallFlying", entity.isFallFlying()); Map<String, Property> properties = entity.getAttributeManager().getAllProperties(); if (!properties.isEmpty()) { List<CompoundTag> attributes = new ArrayList<>(properties.size()); properties.forEach((key, property) -> { CompoundTag attribute = new CompoundTag(); attribute.putString("Name", key); attribute.putDouble("Base", property.getValue()); Collection<AttributeModifier> modifiers = property.getModifiers(); if (modifiers != null && !modifiers.isEmpty()) { List<CompoundTag> modifierTags = modifiers.stream().map(modifier -> { CompoundTag modifierTag = new CompoundTag(); modifierTag.putDouble("Amount", modifier.getAmount()); modifierTag.putString("Name", modifier.getName()); modifierTag.putInt("Operation", modifier.getOperation().ordinal()); UUID uuid = modifier.getUniqueId(); modifierTag.putLong("UUIDLeast", uuid.getLeastSignificantBits()); modifierTag.putLong("UUIDMost", uuid.getMostSignificantBits()); return modifierTag; }).collect(Collectors.toList()); attribute.putCompoundList("Modifiers", modifierTags); } attributes.add(attribute); }); tag.putCompoundList("Attributes", attributes); } List<CompoundTag> effects = new LinkedList<>(); for (PotionEffect effect : entity.getActivePotionEffects()) { CompoundTag effectTag = new CompoundTag(); effectTag.putByte("Id", effect.getType().getId()); effectTag.putByte("Amplifier", effect.getAmplifier()); effectTag.putInt("Duration", effect.getDuration()); effectTag.putBool("Ambient", effect.isAmbient()); effectTag.putBool("ShowParticles", true); effects.add(effectTag); } tag.putCompoundList("ActiveEffects", effects); EntityEquipment equip = entity.getEquipment(); if (equip != null) { tag.putCompoundList("HandItems", Arrays.asList( NbtSerialization.writeItem(equip.getItemInMainHand(), -1), NbtSerialization.writeItem(equip.getItemInOffHand(), -1) )); tag.putCompoundList("ArmorItems", Arrays.asList( NbtSerialization.writeItem(equip.getBoots(), -1), NbtSerialization.writeItem(equip.getLeggings(), -1), NbtSerialization.writeItem(equip.getChestplate(), -1), NbtSerialization.writeItem(equip.getHelmet(), -1) )); tag.putFloatList("HandDropChances", Arrays.asList( equip.getItemInMainHandDropChance(), equip.getItemInOffHandDropChance() )); tag.putFloatList("ArmorDropChances", Arrays.asList( equip.getBootsDropChance(), equip.getLeggingsDropChance(), equip.getChestplateDropChance(), equip.getHelmetDropChance() )); } tag.putBool("CanPickUpLoot", entity.getCanPickupItems()); tag.putBool("Leashed", entity.isLeashed()); if (entity.isLeashed()) { Entity leashHolder = entity.getLeashHolder(); CompoundTag leash = new CompoundTag(); // "Non-living entities excluding leashes will not persist as leash holders." // The empty Leash tag is still persisted tough if (leashHolder instanceof LeashHitch) { Location location = leashHolder.getLocation(); leash.putInt("X", location.getBlockX()); leash.putInt("Y", location.getBlockY()); leash.putInt("Z", location.getBlockZ()); } else if (leashHolder instanceof LivingEntity) { leash.putLong("UUIDMost", entity.getUniqueId().getMostSignificantBits()); leash.putLong("UUIDLeast", entity.getUniqueId().getLeastSignificantBits()); } tag.putCompound("Leash", leash); } } }
mit
iogav/Partner-Center-Java-SDK
PartnerSdk/src/main/java/com/microsoft/store/partnercenter/BasePartnerComponent.java
1795
// ----------------------------------------------------------------------- // <copyright file="BasePartnerComponent{TContext}.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter; /** * Holds common partner component properties and behavior. All components should inherit from this class. The context * object type. */ public abstract class BasePartnerComponent<TContext> implements IPartnerComponent<TContext> { /** * Initializes a new instance of the {@link #BasePartnerComponent{TContext}} class. * * @param rootPartnerOperations The root partner operations that created this component. * @param componentContext A component context object to work with. */ protected BasePartnerComponent( IPartner rootPartnerOperations, TContext componentContext ) { if ( rootPartnerOperations == null ) { throw new NullPointerException( "rootPartnerOperations null" ); } this.setPartner( rootPartnerOperations ); this.setContext( componentContext ); } /** * Gets a reference to the partner operations instance that generated this component. */ private IPartner __Partner; @Override public IPartner getPartner() { return __Partner; } private void setPartner( IPartner value ) { __Partner = value; } /** * Gets the component context object. */ private TContext __Context; @Override public TContext getContext() { return __Context; } private void setContext( TContext value ) { __Context = value; } }
mit
emilianocarvalho/Estacio
src/ExercicioPOO/TestaAgenda.java
513
package ExercicioPOO; public class TestaAgenda { public static void main(String[] args) { Agenda agenda = new Agenda(2); Pessoa p1 = new Pessoa(); p1.setNome("Emiliano"); p1.setIdade(43); p1.setAltura(1.82); Pessoa p2 = new Pessoa(); p2.setNome("Carvalho"); p2.setIdade(34); p2.setAltura(1.82); agenda.armazenaPessoa(p1.getNome(), p1.getIdade(), p1.getAltura()); agenda.armazenaPessoa(p2.getNome(), p2.getIdade(), p2.getAltura()); agenda.imprimePessoa(0); agenda.imprimeAgenda(); } }
mit
wolfgangimig/joa
java/joa-im/src-gen/com/wilutions/mslib/uccollaborationlib/IRoomJoinStateChangedEventData.java
491
/* ** GENEREATED FILE - DO NOT MODIFY ** */ package com.wilutions.mslib.uccollaborationlib; import com.wilutions.com.*; /** * IRoomJoinStateChangedEventData. * IRoomJoinStateChangedEventData Interface */ @CoInterface(guid="{4D120020-CE64-43C5-9F84-7A7B2360388F}") public interface IRoomJoinStateChangedEventData extends IDispatch { static boolean __typelib__loaded = __TypeLib.load(); @DeclDISPID(1610743808) public RoomJoinState getJoinState() throws ComException; }
mit
fredyw/leetcode
src/main/java/leetcode/Problem2022.java
519
package leetcode; /** * https://leetcode.com/problems/convert-1d-array-into-2d-array/ */ public class Problem2022 { public int[][] construct2DArray(int[] original, int m, int n) { if (m * n != original.length) { return new int[][]{}; } int[][] answer = new int[m][n]; int index = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { answer[i][j] = original[index++]; } } return answer; } }
mit
yholkamp/jadmin
src/main/java/net/nextpulse/jadmin/dao/GenericSQLDAO.java
12211
package net.nextpulse.jadmin.dao; import com.google.common.base.Joiner; import net.nextpulse.jadmin.ColumnDefinition; import net.nextpulse.jadmin.FormPostEntry; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * DAO implementation for resources backed by a SQL database. * * @author yholkamp */ public class GenericSQLDAO extends AbstractDAO { private static final Logger logger = LogManager.getLogger(); private final String tableName; private DataSource dataSource; public GenericSQLDAO(DataSource dataSource, String tableName) { this.dataSource = dataSource; this.tableName = tableName; } /** * @param keys primary key(s) * @return either an empty optional or one holding a DatabaseEntry matching the keys * @throws DataAccessException if an error occurs while accessing the database. */ @Override public Optional<DatabaseEntry> selectOne(Object[] keys) throws DataAccessException { logger.trace("Selecting one {}", tableName); Map<String, Object> editedObject = null; try(Connection conn = dataSource.getConnection()) { String conditions = resourceSchemaProvider.getKeyColumns().stream() .map(x -> String.format("%s = ?", x.getName())) .reduce((s, s2) -> s + " AND " + s2) .orElseThrow(() -> new DataAccessException("Could not generate SQL condition")); PreparedStatement statement = conn.prepareStatement(String.format("SELECT * FROM %s WHERE %s LIMIT 1", tableName, conditions)); for(int i = 1; i <= resourceSchemaProvider.getKeyColumns().size(); i++) { ColumnDefinition columnDefinition = resourceSchemaProvider.getKeyColumns().get(i - 1); setValue(statement, i, (String) keys[i - 1], columnDefinition, columnDefinition.getName()); } logger.debug("Executing statement {}", statement.toString()); ResultSet results = statement.executeQuery(); if(results.next()) { editedObject = new BasicRowProcessor().toMap(results); } } catch(SQLException e) { logger.error("Exception occurred while executing"); throw new DataAccessException(e); } return editedObject == null ? Optional.empty() : Optional.of(DatabaseEntry.buildFrom(editedObject)); } /** * @param offset number of objects to skip * @param count number of objects to retrieve * @param sortColumn column to sort the values by * @param sortDirection direction to sort, true for ascending, false for descending * @return list of entries of up to count long * @throws DataAccessException if an error occurs while accessing the database. */ @Override public List<DatabaseEntry> selectMultiple(long offset, long count, String sortColumn, boolean sortDirection) throws DataAccessException { logger.trace("Selecting multiple {}, {} offset, {} count", tableName, offset, count); List<DatabaseEntry> rows = new ArrayList<>(); try(Connection conn = dataSource.getConnection()) { // TODO: only select columns that are displayed or part of the primary key String sorting = sortDirection ? "asc" : "desc"; String query = String.format("SELECT * FROM %s ORDER BY %s %s LIMIT %d OFFSET %d", tableName, sortColumn, sorting, count, offset); logger.trace("Formatted selectMultiple query: {}", query); PreparedStatement statement = conn.prepareStatement(query); ResultSet results = statement.executeQuery(); while(results.next()) { Map<String, Object> row = new BasicRowProcessor().toMap(results); rows.add(DatabaseEntry.buildFrom(row)); } } catch(SQLException e) { throw new DataAccessException(e); } return rows; } /** * @param postEntry unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurs while accessing the database. */ @Override public void insert(FormPostEntry postEntry) throws DataAccessException { logger.trace("Inserting a new {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String query = createInsertStatement(postEntry); PreparedStatement statement = conn.prepareStatement(query); int index = 1; for(String columnName : postEntry.getKeyValues().keySet()) { setValue(statement, index++, postEntry.getKeyValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } for(String columnName : postEntry.getValues().keySet()) { setValue(statement, index++, postEntry.getValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } logger.debug("Prepared statement SQL: {}", query); int updatedRows = statement.executeUpdate(); if(updatedRows != 1) { throw new SQLException("Updated " + updatedRows + ", expected 1"); } } catch(SQLException e) { throw new DataAccessException(e); } } /** * @param postEntry unfiltered user submitted data, must be used with caution * @throws DataAccessException if an error occurs while accessing the database. */ @Override public void update(FormPostEntry postEntry) throws DataAccessException { logger.trace("Updating an existing {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String query = createUpdateQuery(postEntry); logger.debug("Prepared statement SQL: {}", query); PreparedStatement statement = conn.prepareStatement(query); int index = 1; // first bind the SET field = ? portion for(String columnName : postEntry.getValues().keySet()) { setValue(statement, index++, postEntry.getValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } // and next the WHERE field = ? part for(String columnName : postEntry.getKeyValues().keySet()) { setValue(statement, index++, postEntry.getKeyValues().get(columnName), getColumnDefinitions().get(columnName), columnName); } logger.debug("Query: {}", statement.toString()); int updatedRows = statement.executeUpdate(); if(updatedRows != 1) { throw new SQLException("Updated " + updatedRows + ", expected 1"); } } catch(SQLException e) { throw new DataAccessException(e); } } /** * Returns the number of entries in the database of the resource. * * @return number of entries * @throws DataAccessException if an SQL exception occurred */ @Override public int count() throws DataAccessException { try(Connection conn = dataSource.getConnection()) { PreparedStatement statement = conn.prepareStatement(String.format("SELECT COUNT(*) FROM %s", tableName)); ResultSet results = statement.executeQuery(); results.next(); return results.getInt(1); } catch(SQLException e) { throw new DataAccessException(e); } } @Override public void delete(Object... keys) throws DataAccessException { logger.trace("Updating an existing {}", tableName); try(Connection conn = dataSource.getConnection()) { // construct the SQL query String conditions = resourceSchemaProvider.getKeyColumns().stream() .map(x -> String.format("%s = ?", x.getName())) .reduce((s, s2) -> s + " AND " + s2) .orElseThrow(() -> new DataAccessException("Could not generate SQL condition")); PreparedStatement statement = conn.prepareStatement(String.format("DELETE FROM %s WHERE %s", tableName, conditions)); for(int i = 1; i <= resourceSchemaProvider.getKeyColumns().size(); i++) { ColumnDefinition columnDefinition = resourceSchemaProvider.getKeyColumns().get(i - 1); setValue(statement, i, (String) keys[i - 1], columnDefinition, columnDefinition.getName()); } logger.debug("Executing statement {}", statement.toString()); boolean results = statement.execute(); } catch(SQLException e) { throw new DataAccessException(e); } } /** * Creates an SQL update query for the provided postEntry. * * @param postEntry object to construct the update query for * @return update query with unbound parameters */ protected String createUpdateQuery(FormPostEntry postEntry) { String wherePortion = postEntry.getKeyValues().keySet().stream() .map(x -> x + " = ?") .reduce((s, s2) -> s + " AND " + s2).orElse(""); String setPortion = postEntry.getValues().keySet().stream() .map(x -> x + " = ?") .reduce((s, s2) -> s + "," + s2).orElse(""); return String.format("UPDATE %s SET %s WHERE %s", tableName, setPortion, wherePortion); } /** * Creates an SQL insert query for the provided postEntry. * * @param postEntry object to construct the insert query for * @return insert query with unbound parameters */ protected String createInsertStatement(FormPostEntry postEntry) { // obtain a list of all resource columns present in the post data List<String> columnSet = new ArrayList<>(postEntry.getKeyValues().keySet()); columnSet.addAll(postEntry.getValues().keySet()); String parameters = Joiner.on(",").join(Collections.nCopies(columnSet.size(), "?")); String parameterString = Joiner.on(",").join(columnSet); return String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, parameterString, parameters); } /** * Query updater that attempts to use the most specific setX method based on the provided input. * * @param statement statement to fill * @param index index of the parameter to configure * @param value user-provided value * @param columnDefinition column definition, used to obtain type information * @param columnName name of the column being set * @throws DataAccessException exception that may be thrown by {@link PreparedStatement#setObject(int, Object)} and others */ protected void setValue(PreparedStatement statement, int index, String value, ColumnDefinition columnDefinition, String columnName) throws DataAccessException { if(columnDefinition == null) { throw new DataAccessException("Found no column definition for column " + columnName + ", value " + value); } try { if(StringUtils.isEmpty(value)) { // TODO: use setNull here logger.trace("Setting null for column {}", columnDefinition.getName()); statement.setObject(index, null); } else { switch(columnDefinition.getType()) { case integer: statement.setInt(index, Integer.valueOf(value)); break; case bool: statement.setBoolean(index, Boolean.valueOf(value)); break; case datetime: // TODO: handle input-to-date conversion SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = format.parse(value); statement.setDate(index, new java.sql.Date(date.getTime())); } catch(ParseException e) { logger.error("Could not parse the provided datetime string: {}", value, e); } break; case string: case text: statement.setString(index, value); break; default: logger.error("Unsupported column definition type {} found, setting without type checking", columnDefinition.getType()); statement.setObject(index, value); break; } } } catch(SQLException e) { logger.error("Could not set {}.{} (type {}) to {}", tableName, columnDefinition.getName(), columnDefinition.getType(), value); throw new DataAccessException(e); } } }
mit
moltin/android-example
app/src/main/java/moltin/example_moltin/activities/CollectionActivity.java
14543
package moltin.example_moltin.activities; import android.content.Context; import android.content.Intent; import android.graphics.Point; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.view.Display; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity; import org.json.JSONObject; import java.util.ArrayList; import moltin.android_sdk.Moltin; import moltin.android_sdk.utilities.Constants; import moltin.example_moltin.R; import moltin.example_moltin.data.CartItem; import moltin.example_moltin.data.CollectionItem; import moltin.example_moltin.data.TotalCartItem; import moltin.example_moltin.fragments.CartFragment; import moltin.example_moltin.fragments.CollectionFragment; public class CollectionActivity extends SlidingFragmentActivity implements CollectionFragment.OnCollectionFragmentPictureDownloadListener, CartFragment.OnFragmentUpdatedListener, CartFragment.OnFragmentChangeListener, CollectionFragment.OnCollectionFragmentInteractionListener { private Moltin moltin; private ArrayList<CollectionItem> items; private ArrayList<CartItem> itemsForCart; private TotalCartItem cart; public static CollectionActivity instance = null; private SlidingMenu menu; private android.app.Fragment mContent; private CartFragment menuFragment; private Point screenSize; private int position=0; private LinearLayout layIndex; private int currentOffset=0; private int limit=20; private boolean endOfList=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); instance = this; moltin = new Moltin(this); menu = getSlidingMenu(); menu.setShadowWidth(20); menu.setBehindWidth(getListviewWidth()-50); menu.setTouchModeBehind(SlidingMenu.TOUCHMODE_FULLSCREEN); menu.setMode(SlidingMenu.RIGHT); menu.setFadeEnabled(false); menu.setBehindScrollScale(0.5f); setSlidingActionBarEnabled(true); currentOffset=0; endOfList=false; items=new ArrayList<CollectionItem>(); if (savedInstanceState != null) mContent = getFragmentManager().getFragment(savedInstanceState, "mContentCollection"); if (mContent == null) { mContent = CollectionFragment.newInstance(items,getListviewWidth(),currentOffset); } setContentView(R.layout.activity_collection); getFragmentManager() .beginTransaction() .replace(R.id.container, mContent) .commit(); itemsForCart=new ArrayList<CartItem>(); cart=new TotalCartItem(new JSONObject()); cart.setItems(itemsForCart); setBehindContentView(R.layout.cart_content_frame); menuFragment = CartFragment.newInstance(cart, getApplicationContext()); getFragmentManager() .beginTransaction() .replace(R.id.cart_content_frame, menuFragment) .commit(); ((TextView)findViewById(R.id.txtActivityTitle)).setTypeface(Typeface.createFromAsset(getResources().getAssets(), getString(R.string.font_regular))); ((TextView)findViewById(R.id.txtActivityTitleCart)).setTypeface(Typeface.createFromAsset(getResources().getAssets(), getString(R.string.font_regular))); try { moltin.authenticate(getString(R.string.moltin_api_key), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == Constants.RESULT_OK) { try { getCollections(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } }); } catch (Exception e) { e.printStackTrace(); } } public void setInitialPosition() { layIndex = (LinearLayout)findViewById(R.id.layIndex); if(((LinearLayout) layIndex).getChildCount() > 0) ((LinearLayout) layIndex).removeAllViews(); for(int i=0;i<items.size();i++) { ImageView img=new ImageView(this); if(position==i) img.setImageDrawable(getResources().getDrawable(R.drawable.circle_active)); else img.setImageDrawable(getResources().getDrawable(R.drawable.circle_inactive)); final float scale = getApplicationContext().getResources().getDisplayMetrics().density; ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams( (int)(12*scale + 0.5f), (int)(12*scale + 0.5f)); params.leftMargin = (int)(5*scale + 0.5f); params.rightMargin = (int)(5*scale + 0.5f); params.topMargin = (int)(5*scale + 0.5f); params.bottomMargin = (int)(40*scale + 0.5f); img.setLayoutParams(params); layIndex.addView(img); } } public void setPosition(int newPosition) { if(newPosition!=position) { if(((LinearLayout) layIndex).getChildCount() > 0) { ((ImageView)layIndex.getChildAt(position)).setImageDrawable(getResources().getDrawable(R.drawable.circle_inactive)); ((ImageView)layIndex.getChildAt(newPosition)).setImageDrawable(getResources().getDrawable(R.drawable.circle_active)); position=newPosition; } } } public void getNewPage(int currentNumber) { currentOffset=currentNumber; try { getCollections(); } catch (Exception e) { e.printStackTrace(); } } private int getListviewWidth() { Display display = getWindowManager().getDefaultDisplay(); screenSize = new Point(); display.getSize(screenSize); return screenSize.x; } public void onItemClickHandler(View view) { try { Intent intent = new Intent(this, ProductActivity.class); intent.putExtra("ID",view.getTag(R.id.txtDescription).toString()); intent.putExtra("COLLECTION",view.getTag(R.id.txtCollectionName).toString()); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } public void onClickHandler(View view) { try { switch (view.getId()) { case R.id.btnPlus: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.update(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(),new String[][]{{"quantity",""+(menuFragment.cart.getItems().get((int)view.getTag()).getItemQuantity()+1)}}, new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnMinus: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.update(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(),new String[][]{{"quantity",""+(menuFragment.cart.getItems().get((int)view.getTag()).getItemQuantity()-1)}}, new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnDelete: ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.VISIBLE); moltin.cart.remove(menuFragment.cart.getItems().get((int)view.getTag()).getItemIdentifier(), new Handler.Callback() {//"wf60kt82vtzkjIMslZ1FmDyV8WUWNQlLxUiRVLS4", new Handler.Callback() { @Override public boolean handleMessage(Message msg) { menuFragment.refresh(); if (msg.what == Constants.RESULT_OK) { try { } catch (Exception e) { e.printStackTrace(); } return true; } else { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); return false; } } }); break; case R.id.btnCheckout: if(menuFragment.cart!=null && menuFragment.cart.getItemTotalNumber()!=null && menuFragment.cart.getItemTotalNumber()>0) { Intent intent = new Intent(this, BillingActivity.class); intent.putExtra("JSON",menuFragment.cart.getItemJson().toString()); startActivity(intent); } else { Toast.makeText(getApplicationContext(), getString(R.string.alert_cart_is_empty), Toast.LENGTH_LONG).show(); } break; case R.id.btnMenu: onHomeClicked(); break; case R.id.btnCart: onHomeClicked(); break; } } catch (Exception e) { e.printStackTrace(); } } public void onHomeClicked() { toggle(); } private void getCollections() throws Exception { if(endOfList) return; ((LinearLayout)findViewById(R.id.layMainLoading)).setVisibility(View.VISIBLE); moltin.collection.listing(new String[][]{{"limit",Integer.toString(limit)},{"offset",Integer.toString(currentOffset)}},new Handler.Callback() { @Override public boolean handleMessage(Message msg) { if (msg.what == Constants.RESULT_OK) { try { JSONObject json=(JSONObject)msg.obj; if(json.has("status") && json.getBoolean("status") && json.has("result") && json.getJSONArray("result").length()>0) { for(int i=0;i<json.getJSONArray("result").length();i++) { items.add(new CollectionItem(json.getJSONArray("result").getJSONObject(i))); } } if(items.size()==json.getJSONObject("pagination").getInt("total")) endOfList=true; else endOfList=false; if(currentOffset>0) { onCollectionFragmentPictureDownloadListener(); } ((CollectionFragment)mContent).customRecyclerView.getAdapter().notifyDataSetChanged(); setInitialPosition(); } catch (Exception e) { e.printStackTrace(); } return true; } else { return false; } } }); } @Override public void onFragmentInteractionForCollectionItem(String itemId) { } @Override protected void onDestroy() { try { instance=null; } catch (Exception e) { e.printStackTrace(); } super.onDestroy(); } @Override protected void onResume() { try { menuFragment.refresh(); } catch (Exception e) { e.printStackTrace(); } super.onResume(); } @Override public void onFragmentChangeForCartItem(TotalCartItem cart) { ((TextView)findViewById(R.id.txtTotalPrice)).setText(cart.getItemTotalPrice()); } @Override public void onFragmentUpdatedForCartItem() { ((LinearLayout)findViewById(R.id.layLoading)).setVisibility(View.GONE); } @Override public void onCollectionFragmentPictureDownloadListener() { try { ((LinearLayout) findViewById(R.id.layMainLoading)).setVisibility(View.GONE); } catch (Exception e) { e.printStackTrace(); } } }
mit
maxalthoff/intro-to-java-exercises
03/E3_15/E3_15.java
2006
/* Revise Listing 3.8, Lottery.java, to generate a lottery of a three-digit number. The program prompts the user to enter a three-digit number and determines whether the user wins according to the following rules: 1. If the user input matches the lottery number in the exact order, the award is $10,000. 2. If all digits in the user input match all digits in the lottery number, the award is $3,000. 3. If one digit in the user input matches a digit in the lottery number, the award is $1,000. */ import java.util.Scanner; public class E3_15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a three-digit number: "); String numString = input.nextLine(); displayLotteryOutcome(numString); } private static void displayLotteryOutcome(String numString) { int a = Integer.parseInt(numString.charAt(0) + ""); int b = Integer.parseInt(numString.charAt(1) + ""); int c = Integer.parseInt(numString.charAt(2) + ""); int x = generateLottery(); int y = generateLottery(); int z = generateLottery(); StringBuilder output = new StringBuilder(); if (a == x && b == y && c == z) { output.append("Matched exact order: you win $10,000"); } else if ((a == x && c == y && b == z) || (b == x && c == y && a == z) || (b == x && a == y && c == z) || (c == x && a == y && b == z) || (c == x && b == y && a == z)) { output.append("All digits match: you win $3,000"); } else if ((a == x || a == y || a == z) || (b == x || b == y || b == z) || (c == x || c == y || c == z)) { output.append("At least one digit matches: you win $1,000"); } else { output.append("Too bad! You win nothing!"); } System.out.println("Lottery: " + x + y + z); System.out.println(output); } private static int generateLottery() { return (int)(Math.random() * 10); } }
mit
firm1/zmarkdown-editor
src/zmarkdown/javaeditor/EMarkdown.java
1070
/* * 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 zmarkdown.javaeditor; import org.python.util.PythonInterpreter; import org.python.core.*; /** * * @author firm1 */ public class EMarkdown{ PythonInterpreter interp; public EMarkdown() { interp = new PythonInterpreter(); interp.exec("from markdown import Markdown"); interp.exec("from markdown.extensions.zds import ZdsExtension"); interp.exec("from smileys_definition import smileys"); } public String html(String chaine) { interp.set("text", chaine); interp.exec("render = Markdown(extensions=(ZdsExtension({'inline': False, 'emoticons': smileys}),),safe_mode = 'escape', enable_attributes = False, tab_length = 4, output_format = 'html5', smart_emphasis = True, lazy_ol = True).convert(text)"); PyString render = interp.get("render", PyString.class); return render.toString(); } }
mit
Alex-BusNet/InfiniteStratos
src/main/java/com/sparta/is/entity/driveables/types/TypeFile.java
1134
package com.sparta.is.entity.driveables.types; import java.util.ArrayList; import java.util.HashMap; public class TypeFile { public EnumType type; public String name, contentPack; public ArrayList<String> lines; public static HashMap<EnumType, ArrayList<TypeFile>> files; private int readerPosition = 0; static { files = new HashMap<EnumType, ArrayList<TypeFile>>(); for(EnumType type: EnumType.values()) { files.put(type, new ArrayList<TypeFile>()); } } public TypeFile(String contentPack, EnumType t, String s) { this(contentPack, t, s, true); } public TypeFile(String contentPack, EnumType t, String s, boolean addToTypeFileList) { type = t; name = s; this.contentPack = contentPack; lines = new ArrayList<String>(); if(addToTypeFileList) { files.get(type).add(this); } } public String readLine() { if(readerPosition == lines.size()) { return null; } return lines.get(readerPosition++); } }
mit
github/codeql
java/ql/test/library-tests/frameworks/guava/handwritten/TestCollect.java
5835
package com.google.common.collect; import java.util.Collection; import java.util.Map; import java.util.SortedSet; import java.util.SortedMap; import java.util.Comparator; class TestCollect { String taint() { return "tainted"; } void sink(Object o) {} <T> T element(Collection<T> c) { return c.iterator().next(); } <K,V> K mapKey(Map<K,V> m) { return element(m.keySet()); } <K,V> V mapValue(Map<K,V> m) { return element(m.values()); } <K,V> K multimapKey(Multimap<K,V> m) { return element(m.keySet()); } <K,V> V multimapValue(Multimap<K,V> m) { return element(m.values()); } <R,C,V> R tableRow(Table<R,C,V> t) { return element(t.rowKeySet()); } <R,C,V> C tableColumn(Table<R,C,V> t) { return element(t.columnKeySet()); } <R,C,V> V tableValue(Table<R,C,V> t) { return element(t.values()); } void test1() { String x = taint(); ImmutableSet<String> xs = ImmutableSet.of(x, "y", "z"); sink(element(xs.asList())); // $numValueFlow=1 ImmutableSet<String> ys = ImmutableSet.of("a", "b", "c"); sink(element(Sets.filter(Sets.union(xs, ys), y -> true))); // $numValueFlow=1 sink(element(Sets.newHashSet("a", "b", "c", "d", x))); // $numValueFlow=1 } void test2() { sink(element(ImmutableList.of(taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint()))); // $numValueFlow=16 sink(element(ImmutableSet.of(taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint(),taint(), taint(), taint(), taint()))); // $numValueFlow=16 sink(mapKey(ImmutableMap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(mapValue(ImmutableMap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(multimapKey(ImmutableMultimap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(multimapValue(ImmutableMultimap.of(taint(), taint(), taint(), taint()))); // $numValueFlow=2 sink(tableRow(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 sink(tableColumn(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 sink(tableValue(ImmutableTable.of(taint(), taint(), taint()))); // $numValueFlow=1 } void test3() { String x = taint(); ImmutableList.Builder<String> b = ImmutableList.builder(); b.add("a"); sink(b); b.add(x); sink(element(b.build())); // $numValueFlow=1 b = ImmutableList.builder(); b.add("a").add(x); sink(element(b.build())); // $numValueFlow=1 sink(ImmutableList.builder().add("a").add(x).build().toArray()[0]); // $numValueFlow=1 ImmutableMap.Builder<String, String> b2 = ImmutableMap.builder(); b2.put(x,"v"); sink(mapKey(b2.build())); // $numValueFlow=1 b2.put("k",x); sink(mapValue(b2.build())); // $numValueFlow=1 } void test4(Table<String, String, String> t1, Table<String, String, String> t2, Table<String, String, String> t3) { String x = taint(); t1.put(x, "c", "v"); sink(tableRow(t1)); // $numValueFlow=1 t1.put("r", x, "v"); sink(tableColumn(t1)); // $numValueFlow=1 t1.put("r", "c", x); sink(tableValue(t1)); // $numValueFlow=1 sink(mapKey(t1.row("r"))); // $numValueFlow=1 sink(mapValue(t1.row("r"))); // $numValueFlow=1 t2.putAll(t1); for (Table.Cell<String,String,String> c : t2.cellSet()) { sink(c.getValue()); // $numValueFlow=1 } sink(t1.remove("r", "c")); // $numValueFlow=1 t3.row("r").put("c", x); sink(tableValue(t3)); // $ MISSING:numValueFlow=1 // depends on aliasing } void test5(Multimap<String, String> m1, Multimap<String, String> m2, Multimap<String, String> m3, Multimap<String, String> m4, Multimap<String, String> m5){ String x = taint(); m1.put("k", x); sink(multimapValue(m1)); // $numValueFlow=1 sink(element(m1.get("k"))); // $numValueFlow=1 m2.putAll("k", ImmutableList.of("a", x, "b")); sink(multimapValue(m2)); // $numValueFlow=1 m3.putAll(m1); sink(multimapValue(m3)); // $numValueFlow=1 m4.replaceValues("k", m1.replaceValues("k", ImmutableList.of("a"))); for (Map.Entry<String, String> e : m4.entries()) { sink(e.getValue()); // $numValueFlow=1 } m5.asMap().get("k").add(x); sink(multimapValue(m5)); // $ MISSING:numValueFlow=1 // depends on aliasing } void test6(Comparator<String> comp, SortedSet<String> sorS, SortedMap<String, String> sorM) { ImmutableSortedSet<String> s = ImmutableSortedSet.of(taint()); sink(element(s)); // $numValueFlow=1 sink(element(ImmutableSortedSet.copyOf(s))); // $numValueFlow=1 sink(element(ImmutableSortedSet.copyOf(comp, s))); // $numValueFlow=1 sorS.add(taint()); sink(element(ImmutableSortedSet.copyOfSorted(sorS))); // $numValueFlow=1 sink(element(ImmutableList.sortedCopyOf(s))); // $numValueFlow=1 sink(element(ImmutableList.sortedCopyOf(comp, s))); // $numValueFlow=1 ImmutableSortedMap<String, String> m = ImmutableSortedMap.of("k", taint()); sink(mapValue(m)); // $numValueFlow=1 sink(mapValue(ImmutableSortedMap.copyOf(m))); // $numValueFlow=1 sink(mapValue(ImmutableSortedMap.copyOf(m, comp))); // $numValueFlow=1 sorM.put("k", taint()); sink(mapValue(ImmutableSortedMap.copyOfSorted(sorM))); // $numValueFlow=1 } }
mit
Rodzillaa/rodzilla-android
app/src/main/java/rodzillaa/github/io/rodzilla/utils/APIUtil.java
171
package rodzillaa.github.io.rodzilla.utils; public class APIUtil { public static final String SERVER_URL = "http://ec2-54-174-96-216.compute-1.amazonaws.com:9000"; }
mit
chrisc36/weka-analyzer
src/main/java/weka/analyzers/mineData/CachedRuleDisjunction.java
645
package weka.analyzers.mineData; import java.util.BitSet; /** * The Disjunction of other cached rules. * * @param <T> the type of CachedRule contained in this RuleSet */ public class CachedRuleDisjunction<T extends CachedRule> extends CachedRuleSet<T> { /** * Construct a new empty RuleDisjunction that covers all Instances. * * @param numInstances number of instances this RuleSet should cover */ public CachedRuleDisjunction(int numInstances) { super(numInstances, "OR"); } @Override protected void addBitSet(BitSet other) { covered.or(other); } }
mit
elendil326/UWNLP
Assignment2/src/edu/berkeley/nlp/assignments/WordAlignmentTester.java
16171
package edu.berkeley.nlp.assignments; import edu.berkeley.nlp.util.*; import edu.berkeley.nlp.io.IOUtils; import java.util.*; import java.io.*; /** * Harness for testing word-level alignments. The code is hard-wired for the * aligment source to be english and the alignment target to be french (recall * that's the direction for translating INTO english in the noisy channel * model). * * Your projects will implement several methods of word-to-word alignment. * * @author Dan Klein */ public class WordAlignmentTester { static final String ENGLISH_EXTENSION = "e"; static final String FRENCH_EXTENSION = "f"; /** * A holder for a pair of sentences, each a list of strings. Sentences in * the test sets have integer IDs, as well, which are used to retreive the * gold standard alignments for those sentences. */ public static class SentencePair { final int sentenceID; final String sourceFile; final List<String> englishWords; final List<String> frenchWords; public int getSentenceID() { return sentenceID; } public String getSourceFile() { return sourceFile; } public List<String> getEnglishWords() { return englishWords; } public List<String> getFrenchWords() { return frenchWords; } public String toString() { StringBuilder sb = new StringBuilder(); for (int englishPosition = 0; englishPosition < englishWords.size(); englishPosition++) { String englishWord = englishWords.get(englishPosition); sb.append(englishPosition); sb.append(":"); sb.append(englishWord); sb.append(" "); } sb.append("\n"); for (int frenchPosition = 0; frenchPosition < frenchWords.size(); frenchPosition++) { String frenchWord = frenchWords.get(frenchPosition); sb.append(frenchPosition); sb.append(":"); sb.append(frenchWord); sb.append(" "); } sb.append("\n"); return sb.toString(); } public SentencePair(int sentenceID, String sourceFile, List<String> englishWords, List<String> frenchWords) { this.sentenceID = sentenceID; this.sourceFile = sourceFile; this.englishWords = englishWords; this.frenchWords = frenchWords; } } /** * Alignments serve two purposes, both to indicate your system's guessed * alignment, and to hold the gold standard alignments. Alignments map index * pairs to one of three values, unaligned, possibly aligned, and surely * aligned. Your alignment guesses should only contain sure and unaligned * pairs, but the gold alignments contain possible pairs as well. * * To build an alignemnt, start with an empty one and use * addAlignment(i,j,true). To display one, use the render method. */ public static class Alignment { final Set<Pair<Integer, Integer>> sureAlignments; final Set<Pair<Integer, Integer>> possibleAlignments; public boolean containsSureAlignment(int englishPosition, int frenchPosition) { return sureAlignments.contains(new Pair<Integer, Integer>(englishPosition, frenchPosition)); } public boolean containsPossibleAlignment(int englishPosition, int frenchPosition) { return possibleAlignments.contains(new Pair<Integer, Integer>(englishPosition, frenchPosition)); } public void addAlignment(int englishPosition, int frenchPosition, boolean sure) { Pair<Integer, Integer> alignment = new Pair<Integer, Integer>(englishPosition, frenchPosition); if (sure) sureAlignments.add(alignment); possibleAlignments.add(alignment); } public Alignment() { sureAlignments = new HashSet<Pair<Integer, Integer>>(); possibleAlignments = new HashSet<Pair<Integer, Integer>>(); } public static String render(Alignment alignment, SentencePair sentencePair) { return render(alignment, alignment, sentencePair); } public static String render(Alignment reference, Alignment proposed, SentencePair sentencePair) { StringBuilder sb = new StringBuilder(); for (int frenchPosition = 0; frenchPosition < sentencePair.getFrenchWords().size(); frenchPosition++) { for (int englishPosition = 0; englishPosition < sentencePair.getEnglishWords().size(); englishPosition++) { boolean sure = reference.containsSureAlignment(englishPosition, frenchPosition); boolean possible = reference.containsPossibleAlignment(englishPosition, frenchPosition); char proposedChar = ' '; if (proposed.containsSureAlignment(englishPosition, frenchPosition)) proposedChar = '#'; if (sure) { sb.append('['); sb.append(proposedChar); sb.append(']'); } else { if (possible) { sb.append('('); sb.append(proposedChar); sb.append(')'); } else { sb.append(' '); sb.append(proposedChar); sb.append(' '); } } } sb.append("| "); sb.append(sentencePair.getFrenchWords().get(frenchPosition)); sb.append('\n'); } for (int englishPosition = 0; englishPosition < sentencePair.getEnglishWords().size(); englishPosition++) { sb.append("---"); } sb.append("'\n"); boolean printed = true; int index = 0; while (printed) { printed = false; StringBuilder lineSB = new StringBuilder(); for (int englishPosition = 0; englishPosition < sentencePair.getEnglishWords().size(); englishPosition++) { String englishWord = sentencePair.getEnglishWords().get(englishPosition); if (englishWord.length() > index) { printed = true; lineSB.append(' '); lineSB.append(englishWord.charAt(index)); lineSB.append(' '); } else { lineSB.append(" "); } } index += 1; if (printed) { sb.append(lineSB); sb.append('\n'); } } return sb.toString(); } } /** * WordAligners have one method: alignSentencePair, which takes a sentence * pair and produces an alignment which specifies an english source for each * french word which is not aligned to "null". Explicit alignment to * position -1 is equivalent to alignment to "null". */ interface WordAligner { Alignment alignSentencePair(SentencePair sentencePair); } /** * Simple alignment baseline which maps french positions to english positions. * If the french sentence is longer, all final word map to null. */ static class BaselineWordAligner implements WordAligner { public Alignment alignSentencePair(SentencePair sentencePair) { Alignment alignment = new Alignment(); int numFrenchWords = sentencePair.getFrenchWords().size(); int numEnglishWords = sentencePair.getEnglishWords().size(); for (int frenchPosition = 0; frenchPosition < numFrenchWords; frenchPosition++) { int englishPosition = frenchPosition; if (englishPosition >= numEnglishWords) englishPosition = -1; alignment.addAlignment(englishPosition, frenchPosition, true); } return alignment; } } public static void main(String[] args) { // Parse command line flags and arguments Map<String,String> argMap = CommandLineUtils.simpleCommandLineParser(args); // Set up default parameters and settings String basePath = "."; int maxTrainingSentences = 0; boolean verbose = false; String dataset = "mini"; String model = "baseline"; // Update defaults using command line specifications if (argMap.containsKey("-path")) { basePath = argMap.get("-path"); System.out.println("Using base path: "+basePath); } if (argMap.containsKey("-sentences")) { maxTrainingSentences = Integer.parseInt(argMap.get("-sentences")); System.out.println("Using an additional "+maxTrainingSentences+" training sentences."); } if (argMap.containsKey("-data")) { dataset = argMap.get("-data"); System.out.println("Running with data: "+dataset); } else { System.out.println("No data set specified. Use -data [miniTest, validate, test]."); } if (argMap.containsKey("-model")) { model = argMap.get("-model"); System.out.println("Running with model: "+model); } else { System.out.println("No model specified. Use -model modelname."); } if (argMap.containsKey("-verbose")) { verbose = true; } // Read appropriate training and testing sets. List<SentencePair> trainingSentencePairs = new ArrayList<SentencePair>(); if (! dataset.equals("miniTest") && maxTrainingSentences > 0) trainingSentencePairs = readSentencePairs(basePath+"/training", maxTrainingSentences); List<SentencePair> testSentencePairs = new ArrayList<SentencePair>(); Map<Integer,Alignment> testAlignments = new HashMap<Integer, Alignment>(); if (dataset.equalsIgnoreCase("test")) { testSentencePairs = readSentencePairs(basePath+"/test", Integer.MAX_VALUE); testAlignments = readAlignments(basePath+"/answers/test.wa.nonullalign"); } else if (dataset.equalsIgnoreCase("validate")) { testSentencePairs = readSentencePairs(basePath+"/trial", Integer.MAX_VALUE); testAlignments = readAlignments(basePath+"/trial/trial.wa"); } else if (dataset.equalsIgnoreCase("miniTest")) { testSentencePairs = readSentencePairs(basePath+"/mini", Integer.MAX_VALUE); testAlignments = readAlignments(basePath+"/mini/mini.wa"); } else { throw new RuntimeException("Bad data set mode: "+ dataset+", use test, validate, or miniTest."); } trainingSentencePairs.addAll(testSentencePairs); // Build model WordAligner wordAligner = null; if (model.equalsIgnoreCase("baseline")) { wordAligner = new BaselineWordAligner(); } // TODO : build other alignment models // Test model test(wordAligner, testSentencePairs, testAlignments, verbose); } private static void test(WordAligner wordAligner, List<SentencePair> testSentencePairs, Map<Integer, Alignment> testAlignments, boolean verbose) { int proposedSureCount = 0; int proposedPossibleCount = 0; int sureCount = 0; int proposedCount = 0; for (SentencePair sentencePair : testSentencePairs) { Alignment proposedAlignment = wordAligner.alignSentencePair(sentencePair); Alignment referenceAlignment = testAlignments.get(sentencePair.getSentenceID()); if (referenceAlignment == null) throw new RuntimeException("No reference alignment found for sentenceID "+sentencePair.getSentenceID()); if (verbose) System.out.println("Alignment:\n"+Alignment.render(referenceAlignment,proposedAlignment,sentencePair)); for (int frenchPosition = 0; frenchPosition < sentencePair.getFrenchWords().size(); frenchPosition++) { for (int englishPosition = 0; englishPosition < sentencePair.getEnglishWords().size(); englishPosition++) { boolean proposed = proposedAlignment.containsSureAlignment(englishPosition, frenchPosition); boolean sure = referenceAlignment.containsSureAlignment(englishPosition, frenchPosition); boolean possible = referenceAlignment.containsPossibleAlignment(englishPosition, frenchPosition); if (proposed && sure) proposedSureCount += 1; if (proposed && possible) proposedPossibleCount += 1; if (proposed) proposedCount += 1; if (sure) sureCount += 1; } } } System.out.println("Precision: "+proposedPossibleCount/(double)proposedCount); System.out.println("Recall: "+proposedSureCount/(double)sureCount); System.out.println("AER: "+(1.0-(proposedSureCount+proposedPossibleCount)/(double)(sureCount+proposedCount))); } // BELOW HERE IS IO CODE private static Map<Integer, Alignment> readAlignments(String fileName) { Map<Integer,Alignment> alignments = new HashMap<Integer, Alignment>(); try { BufferedReader in = new BufferedReader(new FileReader(fileName)); while (in.ready()) { String line = in.readLine(); String[] words = line.split("\\s+"); if (words.length != 4) throw new RuntimeException("Bad alignment file "+fileName+", bad line was "+line); Integer sentenceID = Integer.parseInt(words[0]); Integer englishPosition = Integer.parseInt(words[1])-1; Integer frenchPosition = Integer.parseInt(words[2])-1; String type = words[3]; Alignment alignment = alignments.get(sentenceID); if (alignment == null) { alignment = new Alignment(); alignments.put(sentenceID, alignment); } alignment.addAlignment(englishPosition, frenchPosition, type.equals("S")); } } catch (IOException e) { throw new RuntimeException(e); } return alignments; } private static List<SentencePair> readSentencePairs(String path, int maxSentencePairs) { List<SentencePair> sentencePairs = new ArrayList<SentencePair>(); List<String> baseFileNames = getBaseFileNames(path); for (String baseFileName : baseFileNames) { if (sentencePairs.size() >= maxSentencePairs) continue; sentencePairs.addAll(readSentencePairs(baseFileName)); } return sentencePairs; } private static List<SentencePair> readSentencePairs(String baseFileName) { List<SentencePair> sentencePairs = new ArrayList<SentencePair>(); String englishFileName = baseFileName + "." + ENGLISH_EXTENSION; String frenchFileName = baseFileName + "." + FRENCH_EXTENSION; try { BufferedReader englishIn = new BufferedReader(new FileReader(englishFileName)); BufferedReader frenchIn = new BufferedReader(new FileReader(frenchFileName)); while (englishIn.ready() && frenchIn.ready()) { String englishLine = englishIn.readLine(); String frenchLine = frenchIn.readLine(); Pair<Integer,List<String>> englishSentenceAndID = readSentence(englishLine); Pair<Integer,List<String>> frenchSentenceAndID = readSentence(frenchLine); if (! englishSentenceAndID.getFirst().equals(frenchSentenceAndID.getFirst())) throw new RuntimeException("Sentence ID confusion in file "+baseFileName+", lines were:\n\t"+englishLine+"\n\t"+frenchLine); sentencePairs.add(new SentencePair(englishSentenceAndID.getFirst(), baseFileName, englishSentenceAndID.getSecond(), frenchSentenceAndID.getSecond())); } } catch (IOException e) { throw new RuntimeException(e); } return sentencePairs; } private static Pair<Integer, List<String>> readSentence(String line) { int id = -1; List<String> words = new ArrayList<String>(); String[] tokens = line.split("\\s+"); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (token.equals("<s")) continue; if (token.equals("</s>")) continue; if (token.startsWith("snum=")) { String idString = token.substring(5,token.length()-1); id = Integer.parseInt(idString); continue; } words.add(token.intern()); } return new Pair<Integer, List<String>>(id, words); } private static List<String> getBaseFileNames(String path) { List<File> englishFiles = IOUtils.getFilesUnder(path, new FileFilter() { public boolean accept(File pathname) { if (pathname.isDirectory()) return true; String name = pathname.getName(); return name.endsWith(ENGLISH_EXTENSION); } }); List<String> baseFileNames = new ArrayList<String>(); for (File englishFile : englishFiles) { String baseFileName = chop(englishFile.getAbsolutePath(), "."+ENGLISH_EXTENSION); baseFileNames.add(baseFileName); } return baseFileNames; } private static String chop(String name, String extension) { if (! name.endsWith(extension)) return name; return name.substring(0, name.length()-extension.length()); } }
mit
wknishio/variable-terminal
src/aircompressor/io/airlift/compress/Compressor.java
924
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.airlift.compress; public interface Compressor { int maxCompressedLength(int uncompressedSize); /** * @return number of bytes written to the output */ int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength); //void compress(ByteBuffer input, ByteBuffer output); }
mit
ifml/ifml-editor
plugins/IFMLEditor.editor/src/IFML/Core/presentation/CoreEditor.java
54335
/** */ package IFML.Core.presentation; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EventObject; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.util.LocalSelectionTransfer; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeColumn; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.IPartListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.ide.IGotoMarker; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.part.MultiPageEditorPart; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.contentoutline.ContentOutlinePage; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.ui.views.properties.IPropertySheetPage; import org.eclipse.ui.views.properties.PropertySheet; import org.eclipse.ui.views.properties.PropertySheetPage; import org.eclipse.emf.common.command.BasicCommandStack; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.common.command.CommandStack; import org.eclipse.emf.common.command.CommandStackListener; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.ui.MarkerHelper; import org.eclipse.emf.common.ui.ViewerPane; import org.eclipse.emf.common.ui.editor.ProblemEditorPart; import org.eclipse.emf.common.ui.viewer.IViewerProvider; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.provider.EcoreItemProviderAdapterFactory; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.util.EContentAdapter; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.emf.edit.domain.IEditingDomainProvider; import org.eclipse.emf.edit.provider.AdapterFactoryItemDelegator; import org.eclipse.emf.edit.provider.ComposedAdapterFactory; import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory; import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory; import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor; import org.eclipse.emf.edit.ui.celleditor.AdapterFactoryTreeEditor; import org.eclipse.emf.edit.ui.dnd.EditingDomainViewerDropAdapter; import org.eclipse.emf.edit.ui.dnd.LocalTransfer; import org.eclipse.emf.edit.ui.dnd.ViewerDragAdapter; import org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.emf.edit.ui.provider.UnwrappingSelectionProvider; import org.eclipse.emf.edit.ui.util.EditUIMarkerHelper; import org.eclipse.emf.edit.ui.util.EditUIUtil; import org.eclipse.emf.edit.ui.view.ExtendedPropertySheetPage; import IFML.Core.provider.CoreItemProviderAdapterFactory; import IFML.DataTypes.presentation.IFMLMetamodelEditorPlugin; import IFML.Extensions.provider.ExtensionsItemProviderAdapterFactory; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.uml2.uml.edit.providers.UMLItemProviderAdapterFactory; /** * This is an example of a Core model editor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class CoreEditor extends MultiPageEditorPart implements IEditingDomainProvider, ISelectionProvider, IMenuListener, IViewerProvider, IGotoMarker { /** * This keeps track of the editing domain that is used to track all changes to the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AdapterFactoryEditingDomain editingDomain; /** * This is the one adapter factory used for providing views of the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ComposedAdapterFactory adapterFactory; /** * This is the content outline page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IContentOutlinePage contentOutlinePage; /** * This is a kludge... * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IStatusLineManager contentOutlineStatusLineManager; /** * This is the content outline page's viewer. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TreeViewer contentOutlineViewer; /** * This is the property sheet page. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected List<PropertySheetPage> propertySheetPages = new ArrayList<PropertySheetPage>(); /** * This is the viewer that shadows the selection in the content outline. * The parent relation must be correctly defined for this to work. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TreeViewer selectionViewer; /** * This inverts the roll of parent and child in the content provider and show parents as a tree. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TreeViewer parentViewer; /** * This shows how a tree view works. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TreeViewer treeViewer; /** * This shows how a list view works. * A list viewer doesn't support icons. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ListViewer listViewer; /** * This shows how a table view works. * A table can be used as a list with icons. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TableViewer tableViewer; /** * This shows how a tree view with columns works. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected TreeViewer treeViewerWithColumns; /** * This keeps track of the active viewer pane, in the book. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ViewerPane currentViewerPane; /** * This keeps track of the active content viewer, which may be either one of the viewers in the pages or the content outline viewer. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Viewer currentViewer; /** * This listens to which ever viewer is active. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ISelectionChangedListener selectionChangedListener; /** * This keeps track of all the {@link org.eclipse.jface.viewers.ISelectionChangedListener}s that are listening to this editor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<ISelectionChangedListener> selectionChangedListeners = new ArrayList<ISelectionChangedListener>(); /** * This keeps track of the selection of the editor as a whole. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ISelection editorSelection = StructuredSelection.EMPTY; /** * The MarkerHelper is responsible for creating workspace resource markers presented * in Eclipse's Problems View. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MarkerHelper markerHelper = new EditUIMarkerHelper(); /** * This listens for when the outline becomes active * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IPartListener partListener = new IPartListener() { public void partActivated(IWorkbenchPart p) { if (p instanceof ContentOutline) { if (((ContentOutline)p).getCurrentPage() == contentOutlinePage) { getActionBarContributor().setActiveEditor(CoreEditor.this); setCurrentViewer(contentOutlineViewer); } } else if (p instanceof PropertySheet) { if (propertySheetPages.contains(((PropertySheet)p).getCurrentPage())) { getActionBarContributor().setActiveEditor(CoreEditor.this); handleActivate(); } } else if (p == CoreEditor.this) { handleActivate(); } } public void partBroughtToTop(IWorkbenchPart p) { // Ignore. } public void partClosed(IWorkbenchPart p) { // Ignore. } public void partDeactivated(IWorkbenchPart p) { // Ignore. } public void partOpened(IWorkbenchPart p) { // Ignore. } }; /** * Resources that have been removed since last activation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<Resource> removedResources = new ArrayList<Resource>(); /** * Resources that have been changed since last activation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<Resource> changedResources = new ArrayList<Resource>(); /** * Resources that have been saved. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<Resource> savedResources = new ArrayList<Resource>(); /** * Map to store the diagnostic associated with a resource. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Map<Resource, Diagnostic> resourceToDiagnosticMap = new LinkedHashMap<Resource, Diagnostic>(); /** * Controls whether the problem indication should be updated. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean updateProblemIndication = true; /** * Adapter used to update the problem indication when resources are demanded loaded. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EContentAdapter problemIndicationAdapter = new EContentAdapter() { @Override public void notifyChanged(Notification notification) { if (notification.getNotifier() instanceof Resource) { switch (notification.getFeatureID(Resource.class)) { case Resource.RESOURCE__IS_LOADED: case Resource.RESOURCE__ERRORS: case Resource.RESOURCE__WARNINGS: { Resource resource = (Resource)notification.getNotifier(); Diagnostic diagnostic = analyzeResourceProblems(resource, null); if (diagnostic.getSeverity() != Diagnostic.OK) { resourceToDiagnosticMap.put(resource, diagnostic); } else { resourceToDiagnosticMap.remove(resource); } if (updateProblemIndication) { getSite().getShell().getDisplay().asyncExec (new Runnable() { public void run() { updateProblemIndication(); } }); } break; } } } else { super.notifyChanged(notification); } } @Override protected void setTarget(Resource target) { basicSetTarget(target); } @Override protected void unsetTarget(Resource target) { basicUnsetTarget(target); resourceToDiagnosticMap.remove(target); if (updateProblemIndication) { getSite().getShell().getDisplay().asyncExec (new Runnable() { public void run() { updateProblemIndication(); } }); } } }; /** * This listens for workspace changes. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IResourceChangeListener resourceChangeListener = new IResourceChangeListener() { public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); try { class ResourceDeltaVisitor implements IResourceDeltaVisitor { protected ResourceSet resourceSet = editingDomain.getResourceSet(); protected Collection<Resource> changedResources = new ArrayList<Resource>(); protected Collection<Resource> removedResources = new ArrayList<Resource>(); public boolean visit(IResourceDelta delta) { if (delta.getResource().getType() == IResource.FILE) { if (delta.getKind() == IResourceDelta.REMOVED || delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() != IResourceDelta.MARKERS) { Resource resource = resourceSet.getResource(URI.createPlatformResourceURI(delta.getFullPath().toString(), true), false); if (resource != null) { if (delta.getKind() == IResourceDelta.REMOVED) { removedResources.add(resource); } else if (!savedResources.remove(resource)) { changedResources.add(resource); } } } return false; } return true; } public Collection<Resource> getChangedResources() { return changedResources; } public Collection<Resource> getRemovedResources() { return removedResources; } } final ResourceDeltaVisitor visitor = new ResourceDeltaVisitor(); delta.accept(visitor); if (!visitor.getRemovedResources().isEmpty()) { getSite().getShell().getDisplay().asyncExec (new Runnable() { public void run() { removedResources.addAll(visitor.getRemovedResources()); if (!isDirty()) { getSite().getPage().closeEditor(CoreEditor.this, false); } } }); } if (!visitor.getChangedResources().isEmpty()) { getSite().getShell().getDisplay().asyncExec (new Runnable() { public void run() { changedResources.addAll(visitor.getChangedResources()); if (getSite().getPage().getActiveEditor() == CoreEditor.this) { handleActivate(); } } }); } } catch (CoreException exception) { IFMLMetamodelEditorPlugin.INSTANCE.log(exception); } } }; /** * Handles activation of the editor or it's associated views. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void handleActivate() { // Recompute the read only state. // if (editingDomain.getResourceToReadOnlyMap() != null) { editingDomain.getResourceToReadOnlyMap().clear(); // Refresh any actions that may become enabled or disabled. // setSelection(getSelection()); } if (!removedResources.isEmpty()) { if (handleDirtyConflict()) { getSite().getPage().closeEditor(CoreEditor.this, false); } else { removedResources.clear(); changedResources.clear(); savedResources.clear(); } } else if (!changedResources.isEmpty()) { changedResources.removeAll(savedResources); handleChangedResources(); changedResources.clear(); savedResources.clear(); } } /** * Handles what to do with changed resources on activation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void handleChangedResources() { if (!changedResources.isEmpty() && (!isDirty() || handleDirtyConflict())) { if (isDirty()) { changedResources.addAll(editingDomain.getResourceSet().getResources()); } editingDomain.getCommandStack().flush(); updateProblemIndication = false; for (Resource resource : changedResources) { if (resource.isLoaded()) { resource.unload(); try { resource.load(Collections.EMPTY_MAP); } catch (IOException exception) { if (!resourceToDiagnosticMap.containsKey(resource)) { resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception)); } } } } if (AdapterFactoryEditingDomain.isStale(editorSelection)) { setSelection(StructuredSelection.EMPTY); } updateProblemIndication = true; updateProblemIndication(); } } /** * Updates the problems indication with the information described in the specified diagnostic. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void updateProblemIndication() { if (updateProblemIndication) { BasicDiagnostic diagnostic = new BasicDiagnostic (Diagnostic.OK, "IFMLEditor.editor", 0, null, new Object [] { editingDomain.getResourceSet() }); for (Diagnostic childDiagnostic : resourceToDiagnosticMap.values()) { if (childDiagnostic.getSeverity() != Diagnostic.OK) { diagnostic.add(childDiagnostic); } } int lastEditorPage = getPageCount() - 1; if (lastEditorPage >= 0 && getEditor(lastEditorPage) instanceof ProblemEditorPart) { ((ProblemEditorPart)getEditor(lastEditorPage)).setDiagnostic(diagnostic); if (diagnostic.getSeverity() != Diagnostic.OK) { setActivePage(lastEditorPage); } } else if (diagnostic.getSeverity() != Diagnostic.OK) { ProblemEditorPart problemEditorPart = new ProblemEditorPart(); problemEditorPart.setDiagnostic(diagnostic); problemEditorPart.setMarkerHelper(markerHelper); try { addPage(++lastEditorPage, problemEditorPart, getEditorInput()); setPageText(lastEditorPage, problemEditorPart.getPartName()); setActivePage(lastEditorPage); showTabs(); } catch (PartInitException exception) { IFMLMetamodelEditorPlugin.INSTANCE.log(exception); } } if (markerHelper.hasMarkers(editingDomain.getResourceSet())) { markerHelper.deleteMarkers(editingDomain.getResourceSet()); if (diagnostic.getSeverity() != Diagnostic.OK) { try { markerHelper.createMarkers(diagnostic); } catch (CoreException exception) { IFMLMetamodelEditorPlugin.INSTANCE.log(exception); } } } } } /** * Shows a dialog that asks if conflicting changes should be discarded. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean handleDirtyConflict() { return MessageDialog.openQuestion (getSite().getShell(), getString("_UI_FileConflict_label"), getString("_WARN_FileConflict")); } /** * This creates a model editor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CoreEditor() { super(); initializeEditingDomain(); } /** * This sets up the editing domain for the model editor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void initializeEditingDomain() { // Create an adapter factory that yields item providers. // adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); adapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new CoreItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ExtensionsItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new EcoreItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new UMLItemProviderAdapterFactory()); adapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); // Create the command stack that will notify this editor as commands are executed. // BasicCommandStack commandStack = new BasicCommandStack(); // Add a listener to set the most recent command's affected objects to be the selection of the viewer with focus. // commandStack.addCommandStackListener (new CommandStackListener() { public void commandStackChanged(final EventObject event) { getContainer().getDisplay().asyncExec (new Runnable() { public void run() { firePropertyChange(IEditorPart.PROP_DIRTY); // Try to select the affected objects. // Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand(); if (mostRecentCommand != null) { setSelectionToViewer(mostRecentCommand.getAffectedObjects()); } for (Iterator<PropertySheetPage> i = propertySheetPages.iterator(); i.hasNext(); ) { PropertySheetPage propertySheetPage = i.next(); if (propertySheetPage.getControl().isDisposed()) { i.remove(); } else { propertySheetPage.refresh(); } } } }); } }); // Create the editing domain with a special command stack. // editingDomain = new AdapterFactoryEditingDomain(adapterFactory, commandStack, new HashMap<Resource, Boolean>()); } /** * This is here for the listener to be able to call it. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void firePropertyChange(int action) { super.firePropertyChange(action); } /** * This sets the selection into whichever viewer is active. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSelectionToViewer(Collection<?> collection) { final Collection<?> theSelection = collection; // Make sure it's okay. // if (theSelection != null && !theSelection.isEmpty()) { Runnable runnable = new Runnable() { public void run() { // Try to select the items in the current content viewer of the editor. // if (currentViewer != null) { currentViewer.setSelection(new StructuredSelection(theSelection.toArray()), true); } } }; getSite().getShell().getDisplay().asyncExec(runnable); } } /** * This returns the editing domain as required by the {@link IEditingDomainProvider} interface. * This is important for implementing the static methods of {@link AdapterFactoryEditingDomain} * and for supporting {@link org.eclipse.emf.edit.ui.action.CommandAction}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EditingDomain getEditingDomain() { return editingDomain; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class ReverseAdapterFactoryContentProvider extends AdapterFactoryContentProvider { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReverseAdapterFactoryContentProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object [] getElements(Object object) { Object parent = super.getParent(object); return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object [] getChildren(Object object) { Object parent = super.getParent(object); return (parent == null ? Collections.EMPTY_SET : Collections.singleton(parent)).toArray(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean hasChildren(Object object) { Object parent = super.getParent(object); return parent != null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getParent(Object object) { return null; } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCurrentViewerPane(ViewerPane viewerPane) { if (currentViewerPane != viewerPane) { if (currentViewerPane != null) { currentViewerPane.showFocus(false); } currentViewerPane = viewerPane; } setCurrentViewer(currentViewerPane.getViewer()); } /** * This makes sure that one content viewer, either for the current page or the outline view, if it has focus, * is the current one. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCurrentViewer(Viewer viewer) { // If it is changing... // if (currentViewer != viewer) { if (selectionChangedListener == null) { // Create the listener on demand. // selectionChangedListener = new ISelectionChangedListener() { // This just notifies those things that are affected by the section. // public void selectionChanged(SelectionChangedEvent selectionChangedEvent) { setSelection(selectionChangedEvent.getSelection()); } }; } // Stop listening to the old one. // if (currentViewer != null) { currentViewer.removeSelectionChangedListener(selectionChangedListener); } // Start listening to the new one. // if (viewer != null) { viewer.addSelectionChangedListener(selectionChangedListener); } // Remember it. // currentViewer = viewer; // Set the editors selection based on the current viewer's selection. // setSelection(currentViewer == null ? StructuredSelection.EMPTY : currentViewer.getSelection()); } } /** * This returns the viewer as required by the {@link IViewerProvider} interface. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Viewer getViewer() { return currentViewer; } /** * This creates a context menu for the viewer and adds a listener as well registering the menu for extension. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void createContextMenuFor(StructuredViewer viewer) { MenuManager contextMenu = new MenuManager("#PopUp"); contextMenu.add(new Separator("additions")); contextMenu.setRemoveAllWhenShown(true); contextMenu.addMenuListener(this); Menu menu= contextMenu.createContextMenu(viewer.getControl()); viewer.getControl().setMenu(menu); getSite().registerContextMenu(contextMenu, new UnwrappingSelectionProvider(viewer)); int dndOperations = DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers = new Transfer[] { LocalTransfer.getInstance(), LocalSelectionTransfer.getTransfer(), FileTransfer.getInstance() }; viewer.addDragSupport(dndOperations, transfers, new ViewerDragAdapter(viewer)); viewer.addDropSupport(dndOperations, transfers, new EditingDomainViewerDropAdapter(editingDomain, viewer)); } /** * This is the method called to load a resource into the editing domain's resource set based on the editor's input. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createModel() { URI resourceURI = EditUIUtil.getURI(getEditorInput()); Exception exception = null; Resource resource = null; try { // Load the resource through the editing domain. // resource = editingDomain.getResourceSet().getResource(resourceURI, true); } catch (Exception e) { exception = e; resource = editingDomain.getResourceSet().getResource(resourceURI, false); } Diagnostic diagnostic = analyzeResourceProblems(resource, exception); if (diagnostic.getSeverity() != Diagnostic.OK) { resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception)); } editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter); } /** * Returns a diagnostic describing the errors and warnings listed in the resource * and the specified exception (if any). * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Diagnostic analyzeResourceProblems(Resource resource, Exception exception) { if (!resource.getErrors().isEmpty() || !resource.getWarnings().isEmpty()) { BasicDiagnostic basicDiagnostic = new BasicDiagnostic (Diagnostic.ERROR, "IFMLEditor.editor", 0, getString("_UI_CreateModelError_message", resource.getURI()), new Object [] { exception == null ? (Object)resource : exception }); basicDiagnostic.merge(EcoreUtil.computeDiagnostic(resource, true)); return basicDiagnostic; } else if (exception != null) { return new BasicDiagnostic (Diagnostic.ERROR, "IFMLEditor.editor", 0, getString("_UI_CreateModelError_message", resource.getURI()), new Object[] { exception }); } else { return Diagnostic.OK_INSTANCE; } } /** * This is the method used by the framework to install your own controls. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void createPages() { // Creates the model from the editor input // createModel(); // Only creates the other pages if there is something that can be edited // if (!getEditingDomain().getResourceSet().getResources().isEmpty()) { // Create a page for the selection tree view. // { ViewerPane viewerPane = new ViewerPane(getSite().getPage(), CoreEditor.this) { @Override public Viewer createViewer(Composite composite) { Tree tree = new Tree(composite, SWT.MULTI); TreeViewer newTreeViewer = new TreeViewer(tree); return newTreeViewer; } @Override public void requestActivation() { super.requestActivation(); setCurrentViewerPane(this); } }; viewerPane.createControl(getContainer()); selectionViewer = (TreeViewer)viewerPane.getViewer(); selectionViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory)); selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); selectionViewer.setInput(editingDomain.getResourceSet()); selectionViewer.setSelection(new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true); viewerPane.setTitle(editingDomain.getResourceSet()); new AdapterFactoryTreeEditor(selectionViewer.getTree(), adapterFactory); createContextMenuFor(selectionViewer); int pageIndex = addPage(viewerPane.getControl()); setPageText(pageIndex, getString("_UI_SelectionPage_label")); } // Create a page for the parent tree view. // { ViewerPane viewerPane = new ViewerPane(getSite().getPage(), CoreEditor.this) { @Override public Viewer createViewer(Composite composite) { Tree tree = new Tree(composite, SWT.MULTI); TreeViewer newTreeViewer = new TreeViewer(tree); return newTreeViewer; } @Override public void requestActivation() { super.requestActivation(); setCurrentViewerPane(this); } }; viewerPane.createControl(getContainer()); parentViewer = (TreeViewer)viewerPane.getViewer(); parentViewer.setAutoExpandLevel(30); parentViewer.setContentProvider(new ReverseAdapterFactoryContentProvider(adapterFactory)); parentViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); createContextMenuFor(parentViewer); int pageIndex = addPage(viewerPane.getControl()); setPageText(pageIndex, getString("_UI_ParentPage_label")); } // This is the page for the list viewer // { ViewerPane viewerPane = new ViewerPane(getSite().getPage(), CoreEditor.this) { @Override public Viewer createViewer(Composite composite) { return new ListViewer(composite); } @Override public void requestActivation() { super.requestActivation(); setCurrentViewerPane(this); } }; viewerPane.createControl(getContainer()); listViewer = (ListViewer)viewerPane.getViewer(); listViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory)); listViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); createContextMenuFor(listViewer); int pageIndex = addPage(viewerPane.getControl()); setPageText(pageIndex, getString("_UI_ListPage_label")); } // This is the page for the tree viewer // { ViewerPane viewerPane = new ViewerPane(getSite().getPage(), CoreEditor.this) { @Override public Viewer createViewer(Composite composite) { return new TreeViewer(composite); } @Override public void requestActivation() { super.requestActivation(); setCurrentViewerPane(this); } }; viewerPane.createControl(getContainer()); treeViewer = (TreeViewer)viewerPane.getViewer(); treeViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory)); treeViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); new AdapterFactoryTreeEditor(treeViewer.getTree(), adapterFactory); createContextMenuFor(treeViewer); int pageIndex = addPage(viewerPane.getControl()); setPageText(pageIndex, getString("_UI_TreePage_label")); } // This is the page for the table viewer. // { ViewerPane viewerPane = new ViewerPane(getSite().getPage(), CoreEditor.this) { @Override public Viewer createViewer(Composite composite) { return new TableViewer(composite); } @Override public void requestActivation() { super.requestActivation(); setCurrentViewerPane(this); } }; viewerPane.createControl(getContainer()); tableViewer = (TableViewer)viewerPane.getViewer(); Table table = tableViewer.getTable(); TableLayout layout = new TableLayout(); table.setLayout(layout); table.setHeaderVisible(true); table.setLinesVisible(true); TableColumn objectColumn = new TableColumn(table, SWT.NONE); layout.addColumnData(new ColumnWeightData(3, 100, true)); objectColumn.setText(getString("_UI_ObjectColumn_label")); objectColumn.setResizable(true); TableColumn selfColumn = new TableColumn(table, SWT.NONE); layout.addColumnData(new ColumnWeightData(2, 100, true)); selfColumn.setText(getString("_UI_SelfColumn_label")); selfColumn.setResizable(true); tableViewer.setColumnProperties(new String [] {"a", "b"}); tableViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory)); tableViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); createContextMenuFor(tableViewer); int pageIndex = addPage(viewerPane.getControl()); setPageText(pageIndex, getString("_UI_TablePage_label")); } // This is the page for the table tree viewer. // { ViewerPane viewerPane = new ViewerPane(getSite().getPage(), CoreEditor.this) { @Override public Viewer createViewer(Composite composite) { return new TreeViewer(composite); } @Override public void requestActivation() { super.requestActivation(); setCurrentViewerPane(this); } }; viewerPane.createControl(getContainer()); treeViewerWithColumns = (TreeViewer)viewerPane.getViewer(); Tree tree = treeViewerWithColumns.getTree(); tree.setLayoutData(new FillLayout()); tree.setHeaderVisible(true); tree.setLinesVisible(true); TreeColumn objectColumn = new TreeColumn(tree, SWT.NONE); objectColumn.setText(getString("_UI_ObjectColumn_label")); objectColumn.setResizable(true); objectColumn.setWidth(250); TreeColumn selfColumn = new TreeColumn(tree, SWT.NONE); selfColumn.setText(getString("_UI_SelfColumn_label")); selfColumn.setResizable(true); selfColumn.setWidth(200); treeViewerWithColumns.setColumnProperties(new String [] {"a", "b"}); treeViewerWithColumns.setContentProvider(new AdapterFactoryContentProvider(adapterFactory)); treeViewerWithColumns.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); createContextMenuFor(treeViewerWithColumns); int pageIndex = addPage(viewerPane.getControl()); setPageText(pageIndex, getString("_UI_TreeWithColumnsPage_label")); } getSite().getShell().getDisplay().asyncExec (new Runnable() { public void run() { setActivePage(0); } }); } // Ensures that this editor will only display the page's tab // area if there are more than one page // getContainer().addControlListener (new ControlAdapter() { boolean guard = false; @Override public void controlResized(ControlEvent event) { if (!guard) { guard = true; hideTabs(); guard = false; } } }); getSite().getShell().getDisplay().asyncExec (new Runnable() { public void run() { updateProblemIndication(); } }); } /** * If there is just one page in the multi-page editor part, * this hides the single tab at the bottom. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void hideTabs() { if (getPageCount() <= 1) { setPageText(0, ""); if (getContainer() instanceof CTabFolder) { ((CTabFolder)getContainer()).setTabHeight(1); Point point = getContainer().getSize(); getContainer().setSize(point.x, point.y + 6); } } } /** * If there is more than one page in the multi-page editor part, * this shows the tabs at the bottom. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void showTabs() { if (getPageCount() > 1) { setPageText(0, getString("_UI_SelectionPage_label")); if (getContainer() instanceof CTabFolder) { ((CTabFolder)getContainer()).setTabHeight(SWT.DEFAULT); Point point = getContainer().getSize(); getContainer().setSize(point.x, point.y - 6); } } } /** * This is used to track the active viewer. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void pageChange(int pageIndex) { super.pageChange(pageIndex); if (contentOutlinePage != null) { handleContentOutlineSelection(contentOutlinePage.getSelection()); } } /** * This is how the framework determines which interfaces we implement. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("rawtypes") @Override public Object getAdapter(Class key) { if (key.equals(IContentOutlinePage.class)) { return showOutlineView() ? getContentOutlinePage() : null; } else if (key.equals(IPropertySheetPage.class)) { return getPropertySheetPage(); } else if (key.equals(IGotoMarker.class)) { return this; } else { return super.getAdapter(key); } } /** * This accesses a cached version of the content outliner. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IContentOutlinePage getContentOutlinePage() { if (contentOutlinePage == null) { // The content outline is just a tree. // class MyContentOutlinePage extends ContentOutlinePage { @Override public void createControl(Composite parent) { super.createControl(parent); contentOutlineViewer = getTreeViewer(); contentOutlineViewer.addSelectionChangedListener(this); // Set up the tree viewer. // contentOutlineViewer.setContentProvider(new AdapterFactoryContentProvider(adapterFactory)); contentOutlineViewer.setLabelProvider(new AdapterFactoryLabelProvider(adapterFactory)); contentOutlineViewer.setInput(editingDomain.getResourceSet()); // Make sure our popups work. // createContextMenuFor(contentOutlineViewer); if (!editingDomain.getResourceSet().getResources().isEmpty()) { // Select the root object in the view. // contentOutlineViewer.setSelection(new StructuredSelection(editingDomain.getResourceSet().getResources().get(0)), true); } } @Override public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager, IStatusLineManager statusLineManager) { super.makeContributions(menuManager, toolBarManager, statusLineManager); contentOutlineStatusLineManager = statusLineManager; } @Override public void setActionBars(IActionBars actionBars) { super.setActionBars(actionBars); getActionBarContributor().shareGlobalActions(this, actionBars); } } contentOutlinePage = new MyContentOutlinePage(); // Listen to selection so that we can handle it is a special way. // contentOutlinePage.addSelectionChangedListener (new ISelectionChangedListener() { // This ensures that we handle selections correctly. // public void selectionChanged(SelectionChangedEvent event) { handleContentOutlineSelection(event.getSelection()); } }); } return contentOutlinePage; } /** * This accesses a cached version of the property sheet. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IPropertySheetPage getPropertySheetPage() { PropertySheetPage propertySheetPage = new ExtendedPropertySheetPage(editingDomain) { @Override public void setSelectionToViewer(List<?> selection) { CoreEditor.this.setSelectionToViewer(selection); CoreEditor.this.setFocus(); } @Override public void setActionBars(IActionBars actionBars) { super.setActionBars(actionBars); getActionBarContributor().shareGlobalActions(this, actionBars); } }; propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory)); propertySheetPages.add(propertySheetPage); return propertySheetPage; } /** * This deals with how we want selection in the outliner to affect the other views. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void handleContentOutlineSelection(ISelection selection) { if (currentViewerPane != null && !selection.isEmpty() && selection instanceof IStructuredSelection) { Iterator<?> selectedElements = ((IStructuredSelection)selection).iterator(); if (selectedElements.hasNext()) { // Get the first selected element. // Object selectedElement = selectedElements.next(); // If it's the selection viewer, then we want it to select the same selection as this selection. // if (currentViewerPane.getViewer() == selectionViewer) { ArrayList<Object> selectionList = new ArrayList<Object>(); selectionList.add(selectedElement); while (selectedElements.hasNext()) { selectionList.add(selectedElements.next()); } // Set the selection to the widget. // selectionViewer.setSelection(new StructuredSelection(selectionList)); } else { // Set the input to the widget. // if (currentViewerPane.getViewer().getInput() != selectedElement) { currentViewerPane.getViewer().setInput(selectedElement); currentViewerPane.setTitle(selectedElement); } } } } } /** * This is for implementing {@link IEditorPart} and simply tests the command stack. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isDirty() { return ((BasicCommandStack)editingDomain.getCommandStack()).isSaveNeeded(); } /** * This is for implementing {@link IEditorPart} and simply saves the model file. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void doSave(IProgressMonitor progressMonitor) { // Save only resources that have actually changed. // final Map<Object, Object> saveOptions = new HashMap<Object, Object>(); saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER); saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED); // Do the work within an operation because this is a long running activity that modifies the workbench. // WorkspaceModifyOperation operation = new WorkspaceModifyOperation() { // This is the method that gets invoked when the operation runs. // @Override public void execute(IProgressMonitor monitor) { // Save the resources to the file system. // boolean first = true; for (Resource resource : editingDomain.getResourceSet().getResources()) { if ((first || !resource.getContents().isEmpty() || isPersisted(resource)) && !editingDomain.isReadOnly(resource)) { try { long timeStamp = resource.getTimeStamp(); resource.save(saveOptions); if (resource.getTimeStamp() != timeStamp) { savedResources.add(resource); } } catch (Exception exception) { resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception)); } first = false; } } } }; updateProblemIndication = false; try { // This runs the options, and shows progress. // new ProgressMonitorDialog(getSite().getShell()).run(true, false, operation); // Refresh the necessary state. // ((BasicCommandStack)editingDomain.getCommandStack()).saveIsDone(); firePropertyChange(IEditorPart.PROP_DIRTY); } catch (Exception exception) { // Something went wrong that shouldn't. // IFMLMetamodelEditorPlugin.INSTANCE.log(exception); } updateProblemIndication = true; updateProblemIndication(); } /** * This returns whether something has been persisted to the URI of the specified resource. * The implementation uses the URI converter from the editor's resource set to try to open an input stream. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean isPersisted(Resource resource) { boolean result = false; try { InputStream stream = editingDomain.getResourceSet().getURIConverter().createInputStream(resource.getURI()); if (stream != null) { result = true; stream.close(); } } catch (IOException e) { // Ignore } return result; } /** * This always returns true because it is not currently supported. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSaveAsAllowed() { return true; } /** * This also changes the editor's input. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void doSaveAs() { SaveAsDialog saveAsDialog = new SaveAsDialog(getSite().getShell()); saveAsDialog.open(); IPath path = saveAsDialog.getResult(); if (path != null) { IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); if (file != null) { doSaveAs(URI.createPlatformResourceURI(file.getFullPath().toString(), true), new FileEditorInput(file)); } } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void doSaveAs(URI uri, IEditorInput editorInput) { (editingDomain.getResourceSet().getResources().get(0)).setURI(uri); setInputWithNotify(editorInput); setPartName(editorInput.getName()); IProgressMonitor progressMonitor = getActionBars().getStatusLineManager() != null ? getActionBars().getStatusLineManager().getProgressMonitor() : new NullProgressMonitor(); doSave(progressMonitor); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void gotoMarker(IMarker marker) { List<?> targetObjects = markerHelper.getTargetObjects(editingDomain, marker); if (!targetObjects.isEmpty()) { setSelectionToViewer(targetObjects); } } /** * This is called during startup. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void init(IEditorSite site, IEditorInput editorInput) { setSite(site); setInputWithNotify(editorInput); setPartName(editorInput.getName()); site.setSelectionProvider(this); site.getPage().addPartListener(partListener); ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener, IResourceChangeEvent.POST_CHANGE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setFocus() { if (currentViewerPane != null) { currentViewerPane.setFocus(); } else { getControl(getActivePage()).setFocus(); } } /** * This implements {@link org.eclipse.jface.viewers.ISelectionProvider}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void addSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.add(listener); } /** * This implements {@link org.eclipse.jface.viewers.ISelectionProvider}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void removeSelectionChangedListener(ISelectionChangedListener listener) { selectionChangedListeners.remove(listener); } /** * This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to return this editor's overall selection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ISelection getSelection() { return editorSelection; } /** * This implements {@link org.eclipse.jface.viewers.ISelectionProvider} to set this editor's overall selection. * Calling this result will notify the listeners. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setSelection(ISelection selection) { editorSelection = selection; for (ISelectionChangedListener listener : selectionChangedListeners) { listener.selectionChanged(new SelectionChangedEvent(this, selection)); } setStatusLineManager(selection); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setStatusLineManager(ISelection selection) { IStatusLineManager statusLineManager = currentViewer != null && currentViewer == contentOutlineViewer ? contentOutlineStatusLineManager : getActionBars().getStatusLineManager(); if (statusLineManager != null) { if (selection instanceof IStructuredSelection) { Collection<?> collection = ((IStructuredSelection)selection).toList(); switch (collection.size()) { case 0: { statusLineManager.setMessage(getString("_UI_NoObjectSelected")); break; } case 1: { String text = new AdapterFactoryItemDelegator(adapterFactory).getText(collection.iterator().next()); statusLineManager.setMessage(getString("_UI_SingleObjectSelected", text)); break; } default: { statusLineManager.setMessage(getString("_UI_MultiObjectSelected", Integer.toString(collection.size()))); break; } } } else { statusLineManager.setMessage(""); } } } /** * This looks up a string in the plugin's plugin.properties file. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static String getString(String key) { return IFMLMetamodelEditorPlugin.INSTANCE.getString(key); } /** * This looks up a string in plugin.properties, making a substitution. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static String getString(String key, Object s1) { return IFMLMetamodelEditorPlugin.INSTANCE.getString(key, new Object [] { s1 }); } /** * This implements {@link org.eclipse.jface.action.IMenuListener} to help fill the context menus with contributions from the Edit menu. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void menuAboutToShow(IMenuManager menuManager) { ((IMenuListener)getEditorSite().getActionBarContributor()).menuAboutToShow(menuManager); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EditingDomainActionBarContributor getActionBarContributor() { return (EditingDomainActionBarContributor)getEditorSite().getActionBarContributor(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IActionBars getActionBars() { return getActionBarContributor().getActionBars(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AdapterFactory getAdapterFactory() { return adapterFactory; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void dispose() { updateProblemIndication = false; ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceChangeListener); getSite().getPage().removePartListener(partListener); adapterFactory.dispose(); if (getActionBarContributor().getActiveEditor() == this) { getActionBarContributor().setActiveEditor(null); } for (PropertySheetPage propertySheetPage : propertySheetPages) { propertySheetPage.dispose(); } if (contentOutlinePage != null) { contentOutlinePage.dispose(); } super.dispose(); } /** * Returns whether the outline view should be presented to the user. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected boolean showOutlineView() { return true; } }
mit
ShowKa/HanbaiKanri
src/main/java/com/showka/service/query/u05/i/UriageRirekiQuery.java
733
package com.showka.service.query.u05.i; import java.util.List; import com.showka.domain.u05.UriageRireki; import com.showka.domain.z00.Busho; import com.showka.entity.RUriage; import com.showka.value.TheDate; public interface UriageRirekiQuery { /** * 計上日と部署を指定しての売上を検索します。 * * @param busho * 顧客の主管理部署 * @param date * 計上日 * @return 未計上売上リスト(売上履歴) */ public List<RUriage> getEntityList(Busho busho, TheDate date); /** * 売上履歴取得. * * @param uriageId * 売上ID * @return 売上履歴 */ public UriageRireki get(String uriageId); }
mit
vieck/Udemy-Java-Square-One
Car/src/CarProject.java
1133
import java.util.Scanner; /** * Created by mvieck on 12/21/16. */ public class CarProject { Car[] cars = new Car[3]; public CarProject() { cars[0] = new Car("Ford",80, 7); cars[1] = new Car("Kia", 70, 6); cars[2] = new Car("Lexus", 60, 8); } public static void main(String[] args) { CarProject carProgram = new CarProject(); Scanner scanner = new Scanner(System.in); System.out.print("Enter in a car brand (Ford, Kia, Lexus): "); String brand = scanner.nextLine(); Car car; if (carProgram.cars[0].getBrand().equals(brand)) { car = carProgram.cars[0]; } else if (carProgram.cars[1].getBrand().equals(brand)) { car = carProgram.cars[1]; } else if (carProgram.cars[2].getBrand().equals(brand)) { car = carProgram.cars[2]; } else { System.out.println("Could not find the brand. Try Ford, Kia or Lexus"); return; } System.out.printf("Brand: %s, Speed: %d mph/kmh, Drive: %dth gear\n",car.getBrand(), car.getSpeed(), car.getDrive()); } }
mit
3203317/2013
nsp/digitalcampus/JWXT/Develop/trunk/project/cn.newcapec.function.digitalcampus.jwxt.jcxxgl/src/main/java/cn/newcapec/jwxt/jcxxgl/model/JwxtPkxtBjkb.java
3186
package cn.newcapec.jwxt.jcxxgl.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * JwxtPkxtBjkb entity. @author MyEclipse Persistence Tools */ @Entity @Table(name="JWXT_PKXT_BJKB" ,schema="JWXT" ) public class JwxtPkxtBjkb extends cn.newcapec.function.digitalcampus.common.model.AbstractModel implements java.io.Serializable { // Fields private String id; private String xnxqid; private String pkjxbid; private String bz; private String cjr; private String jlssdw; private Date whsj; private Date cjsj; // Constructors /** default constructor */ public JwxtPkxtBjkb() { } /** minimal constructor */ public JwxtPkxtBjkb(String id, String xnxqid, String pkjxbid, String cjr, String jlssdw, Date cjsj) { this.id = id; this.xnxqid = xnxqid; this.pkjxbid = pkjxbid; this.cjr = cjr; this.jlssdw = jlssdw; this.cjsj = cjsj; } /** full constructor */ public JwxtPkxtBjkb(String id, String xnxqid, String pkjxbid, String bz, String cjr, String jlssdw, Date whsj, Date cjsj) { this.id = id; this.xnxqid = xnxqid; this.pkjxbid = pkjxbid; this.bz = bz; this.cjr = cjr; this.jlssdw = jlssdw; this.whsj = whsj; this.cjsj = cjsj; } // Property accessors @Id @Column(name="ID", unique=true, nullable=false, length=32) public String getId() { return this.id; } public void setId(String id) { this.id = id; } @Column(name="XNXQID", nullable=false, length=32) public String getXnxqid() { return this.xnxqid; } public void setXnxqid(String xnxqid) { this.xnxqid = xnxqid; } @Column(name="PKJXBID", nullable=false, length=32) public String getPkjxbid() { return this.pkjxbid; } public void setPkjxbid(String pkjxbid) { this.pkjxbid = pkjxbid; } @Column(name="BZ", length=2000) public String getBz() { return this.bz; } public void setBz(String bz) { this.bz = bz; } @Column(name="CJR", nullable=false, length=32) public String getCjr() { return this.cjr; } public void setCjr(String cjr) { this.cjr = cjr; } @Column(name="JLSSDW", nullable=false, length=32) public String getJlssdw() { return this.jlssdw; } public void setJlssdw(String jlssdw) { this.jlssdw = jlssdw; } @Temporal(TemporalType.DATE) @Column(name="WHSJ", length=7) public Date getWhsj() { return this.whsj; } public void setWhsj(Date whsj) { this.whsj = whsj; } @Temporal(TemporalType.DATE) @Column(name="CJSJ", nullable=false, length=7) public Date getCjsj() { return this.cjsj; } public void setCjsj(Date cjsj) { this.cjsj = cjsj; } }
mit
jankronquist/rock-paper-scissors-in-java
src/test/java/com/jayway/rps/game/EventStringUtil.java
715
package com.jayway.rps.game; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.UUID; import com.jayway.es.api.Event; public class EventStringUtil { public static String toString(Event event) { String simpleName = event.getClass().getSimpleName(); Map<String, Object> values = new HashMap<String, Object>(); for (Field field : event.getClass().getFields()) { try { Object object = field.get(event); if (object instanceof UUID) { object = ((UUID)object).getLeastSignificantBits() % 255; } values.put(field.getName(), object); } catch (Exception e) { throw new RuntimeException(e); } } return simpleName + values; } }
mit
rafael2ll/Smash
SmashMusic/app/src/main/java/com/smash/player/Models/Artista.java
325
package com.smash.player.Models; import com.orm.*; public class Artista extends SugarRecord { public String name; public Artista() {} public Artista(Long id,String name){ setId(id);setName(name);save(); } public void setName(String name) { this.name = name; } public String getName() { return name; } }
mit
PhilippHeuer/twitch4j
rest-helix/src/main/java/com/github/twitch4j/helix/domain/ExtensionTransaction.java
2884
package com.github.twitch4j.helix.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; import lombok.AccessLevel; import lombok.Data; import lombok.NoArgsConstructor; import lombok.Setter; @Data @Setter(AccessLevel.PRIVATE) @NoArgsConstructor @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) @JsonIgnoreProperties(ignoreUnknown = true) public class ExtensionTransaction { /** * Unique identifier of the Bits in Extensions Transaction. */ private String id; /** * UTC timestamp when this transaction occurred. */ private String timestamp; /** * Twitch User ID of the channel the transaction occurred on. */ private String broadcasterId; /** * Twitch Display Name of the broadcaster. */ private String broadcasterName; /** * Twitch User ID of the user who generated the transaction. */ private String userId; /** * Twitch Display Name of the user who generated the transaction. */ private String userName; /** * Enum of the product type. Currently only BITS_IN_EXTENSION. */ private String productType; /** * Known "product_type" enum values. */ public static class ProductType { // "Currently" only valid product type public static String BITS_IN_EXTENSION = "BITS_IN_EXTENSION"; } /** * JSON Object representing the product acquired, as it looked at the time of the transaction. */ private ProductData productData; @Data @Setter(AccessLevel.PRIVATE) @NoArgsConstructor @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) @JsonIgnoreProperties(ignoreUnknown = true) public static class ProductData { /** * Unique identifier for the product across the extension. */ private String sku; /** * JSON Object representing the cost to acquire the product. */ private Cost cost; /** * Display Name of the product. */ @JsonProperty("displayName") private String displayName; /** * Flag used to indicate if the product is in development. Either true or false. */ @JsonProperty("inDevelopment") private Boolean inDevelopment; @Data @Setter(AccessLevel.PRIVATE) @NoArgsConstructor @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) @JsonIgnoreProperties(ignoreUnknown = true) public static class Cost { /** * Number of Bits required to acquire the product. */ private Integer amount; /** * Always the string “Bits”. */ private String type; /** * Known "type" enum values */ public static class CostType { // "Currently" only valid cost type. public static final String BITS = "bits"; } } } }
mit
Felorati/Thesis
code/Tests/Multiverse/multiverse-core/src/test/java/org/multiverse/stms/gamma/transactionalobjects/txnlong/GammaTxnLong_increment1WithAmountTest.java
7940
package org.multiverse.stms.gamma.transactionalobjects.txnlong; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.multiverse.api.LockMode; import org.multiverse.api.TxnFactory; import org.multiverse.api.exceptions.*; import org.multiverse.stms.gamma.GammaStm; import org.multiverse.stms.gamma.transactionalobjects.GammaTxnLong; import org.multiverse.stms.gamma.transactions.GammaTxn; import org.multiverse.stms.gamma.transactions.GammaTxnFactory; import org.multiverse.stms.gamma.transactions.fat.FatFixedLengthGammaTxnFactory; import org.multiverse.stms.gamma.transactions.fat.FatMonoGammaTxnFactory; import org.multiverse.stms.gamma.transactions.fat.FatVariableLengthGammaTxnFactory; import java.util.Collection; import static java.util.Arrays.asList; import static org.junit.Assert.fail; import static org.multiverse.TestUtils.*; import static org.multiverse.api.TxnThreadLocal.clearThreadLocalTxn; import static org.multiverse.api.TxnThreadLocal.setThreadLocalTxn; import static org.multiverse.stms.gamma.GammaTestUtils.*; @RunWith(Parameterized.class) public class GammaTxnLong_increment1WithAmountTest { private final GammaTxnFactory transactionFactory; private final GammaStm stm; public GammaTxnLong_increment1WithAmountTest(GammaTxnFactory transactionFactory) { this.transactionFactory = transactionFactory; this.stm = transactionFactory.getConfig().getStm(); } @Before public void setUp() { clearThreadLocalTxn(); } @Parameterized.Parameters public static Collection<TxnFactory[]> configs() { return asList( new TxnFactory[]{new FatVariableLengthGammaTxnFactory(new GammaStm())}, new TxnFactory[]{new FatFixedLengthGammaTxnFactory(new GammaStm())}, new TxnFactory[]{new FatMonoGammaTxnFactory(new GammaStm())} ); } @Test public void whenSuccess() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); ref.increment(5); tx.commit(); assertIsCommitted(tx); assertVersionAndValue(ref, initialVersion + 1, initialValue + 5); } @Test public void whenReadonlyTransaction_thenReadonlyException() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn tx = stm.newTxnFactoryBuilder() .setReadonly(true) .setSpeculative(false) .newTransactionFactory() .newTxn(); setThreadLocalTxn(tx); try { ref.increment(5); fail(); } catch (ReadonlyException expected) { } assertIsAborted(tx); assertVersionAndValue(ref, initialVersion, initialValue); } @Test public void whenReadLockAcquiredByOther_thenIncrementSucceedsButCommitFails() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn otherTx = transactionFactory.newTxn(); ref.getLock().acquire(otherTx, LockMode.Read); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); ref.increment(5); try { tx.commit(); fail(); } catch (ReadWriteConflict expected) { } assertIsAborted(tx); assertVersionAndValue(ref, initialVersion, initialValue); assertRefHasReadLock(ref, otherTx); assertReadLockCount(ref, 1); } @Test public void whenWriteLockAcquiredByOther_thenIncrementSucceedsButCommitFails() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn otherTx = transactionFactory.newTxn(); ref.getLock().acquire(otherTx, LockMode.Write); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); ref.increment(5); try { tx.commit(); fail(); } catch (ReadWriteConflict expected) { } assertIsAborted(tx); assertVersionAndValue(ref, initialVersion, initialValue); assertRefHasWriteLock(ref, otherTx); } @Test public void whenExclusiveLockAcquiredByOther_thenIncrementSucceedsButCommitFails() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn otherTx = transactionFactory.newTxn(); ref.getLock().acquire(otherTx, LockMode.Exclusive); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); ref.increment(5); try { tx.commit(); fail(); } catch (ReadWriteConflict expected) { } assertIsAborted(tx); assertVersionAndValue(ref, initialVersion, initialValue); assertRefHasExclusiveLock(ref, otherTx); } @Test public void whenCommittedTransactionFound() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); tx.commit(); try { ref.increment(5); fail(); } catch (DeadTxnException expected) { } assertIsCommitted(tx); assertVersionAndValue(ref, initialVersion, initialValue); } @Test public void whenAbortedTransactionFound_thenDeadTxnException() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); tx.abort(); try { ref.increment(5); fail(); } catch (DeadTxnException expected) { } assertIsAborted(tx); assertVersionAndValue(ref, initialVersion, initialValue); } @Test public void whenPreparedTransactionFound_thenPreparedTxnException() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); tx.prepare(); try { ref.increment(5); fail(); } catch (PreparedTxnException expected) { } assertIsAborted(tx); assertVersionAndValue(ref, initialVersion, initialValue); } @Test public void whenNoTransaction_thenTxnMandatoryException() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); try { ref.increment(5); fail(); } catch (TxnMandatoryException expected) { } assertVersionAndValue(ref, initialVersion, initialValue); } @Test public void whenListenersAvailable() { long initialValue = 10; GammaTxnLong ref = new GammaTxnLong(stm, initialValue); long initialVersion = ref.getVersion(); long amount = 4; TxnLongAwaitThread thread = new TxnLongAwaitThread(ref, initialValue + amount); thread.start(); sleepMs(500); GammaTxn tx = transactionFactory.newTxn(); setThreadLocalTxn(tx); ref.increment(amount); tx.commit(); joinAll(thread); assertVersionAndValue(ref, initialVersion + 1, initialValue + amount); } }
mit
accelazh/EngineV2
EngineV2_Branch/src/com/accela/ObjectStreams/HPObjectOutputStream.java
2842
package com.accela.ObjectStreams; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import com.accela.ObjectStreams.support.ObjectOutputStreamSupport; /** * * Ò»¡¢HP¶ÔÏóÊä³öÁ÷(ÎÒÆðµÄÃû×Ö)¡£Õâ¸ö¶ÔÏóÊä³öÁ÷ÓÉ·´Éäд³É¡£ * ¿ÉÒÔ¶ÁÈ¡»òÊä³ö£º * 1¡¢¶ÁȡӵÓпÉÒÔͨ¹ý·´ÉäÀûÓù¹Ô캯ÊýÀ´´´½¨µÄ¶ÔÏó¡£¹¹Ô캯Êý¿ÉÒÔ * ÊÇ˽Óеģ¬×îºÃÊÇÎ޲ι¹Ô캯Êý£¬µ«ÊÇÓвÎÊýµÄ¹¹Ô캯ÊýÒ²¿ÉÒÔ£¬ * Ö»ÊÇËٶȸüÂý¡£ * 2¡¢Êý×éÀàÐÍ£¬ÎÞÂÛÊý×éÔªËØÊÇ»ù±¾ÀàÐÍ»¹ÊǶÔÏóÀàÐÍ¡£ * null¡£ * 3¡¢Ã¶¾Ù±äÁ¿ * 4¡¢Äܹ»Ê¶±ðÉùÃ÷ΪtransientµÄ¶ÔÏóÀàÐ͵Ä×ֶΣ¬ÔÚÊä³öµÄʱºò»á×Ô¶¯ * дΪnull * 5¡¢Äܹ»Ê¶±ðʵÏÖÁËCollection»òMap½Ó¿ÚµÄ¶ÔÏó£¬ÓÃÓÅ»¯µÄ·½Ê½Êä³ö¡£ * µ«ÊǶÔÓÚËüÃÇ»áºöÂÔÈ¥ÖеÄtransient×ֶΣ¬µ±×÷ûÓÐÉùÃ÷transient * µÄ×Ö¶ÎÊä³ö * 6¡¢Äܹ»Êä³öºÍ¶ÁÈ¡´æÔÚÑ­»·ÒýÓõĶÔÏó * * ¶þ¡¢Óëjava.io.ObjectInputStreamºÍjava.io.ObjectOutputStreamµÄÇø±ð£º * 1¡¢Èç¹ûÔÚÎļþÖÐдÈëÒ»¸ö¶ÔÏó£¬ÓÃjava.io.ObjectInputStream¶ÁÈ¡ÎÞÂÛ * ¶àÉٴΣ¬¶¼Ö»»áÉú³ÉÒ»¸öʵÀý¡£ÕâÔÚÍøÂçÖз¢ËͶÔÏóµÄʱºò»áµ¼Ö·¢ËͶÔÏó * ·½·¢ËÍÒ»¸ö¶ÔÏóºó£¬¸ü¸Ä¸Ã¶ÔÏó£¬ÔÙ·¢ËÍ£¬¶ø½ÓÊÕ¶ÔÏó·½Ö»ÄܽÓÊÕÒ»´Î£¬ºó * ÐøµÄ½ÓÊÕ·µ»ØµÄ¶¼ÊǵÚÒ»´Î½ÓÊյĶÔÏó¡£ * 2¡¢ÓëObjectPoolÅäºÏ£¬ÓÅ»¯ÁËн¨¶ÔÏóʱµÄÄÚ´æ·ÖÅä¡£µ±·¢ËÍͬÀàÐÍµÄ¶Ô * ÏóµÄʱºò£¬Èç¹ûÿ10ms¿Ë¡һ¸±±¾²¢·¢ËÍÒ»´Î(Èç¹û²»¿Ë¡£¬java.io.ObjectInputStream£¬ * ¾ÍÖ»ÄܽÓÊÕµÚÒ»´Î·¢Ë͵ĶÔÏó)£¬Ê¹ÓÃjava.io.ObjectInputStream½ÓÊÕ¶ÔÏó * µÄʱºò»áн¨´óÁ¿¶ÔÏóʵÀý£¬¼´Ê¹ÊÍ·ÅÒ²ÄÑÒÔ±»Á¢¼´»ØÊÕ¡£¶øÊ¹ÓÃHPObjectInputStream * Ôò¿ÉÒÔÓë¶ÔÏó³ØÅäºÏ£¬ÀûÓÃÊͷŵôµÄ¶ÔÏ󣬱ÜÃâÖØ¸´Ð½¨ÊµÀý¡£ * * Èý¡¢ÐèҪעÒâµÄµØ·½£º * 1¡¢HPObjectOutputStreamºÍHPObjectInputStreamÓëjava.io.ObjectInputStream * ºÍjava.io.ObjectOutputStream²¢²»ÄܼæÈÝ¡£ÓÃÒ»ÖÖÊä³öÁ÷дµÄ¶ÔÏó£¬ÁíÒ»ÖÖÊäÈëÁ÷ * ²»ÄܶÁÈ¡¡£ * 2¡¢HPObjectOutputStreamºÍHPObjectInputStreamʹÓ÷´Éäд³É£¬·´ÉäÊÇÆäÐÔÄܵį¿ * ¾±£¬¾¡¹Ü¶ÔÏó³Ø¿ÉÒÔ´ó´óµØÓÅ»¯ÆäЧÂÊ¡£HPObjectInputStreamʹÓ÷´Éä¹¹Ô캯ÊýÀ´Ð * ½¨¶ÔϵÄǸö£¬Èç¹ûûÓÐÎ޲ι¹Ô캯Êý£¬HPObjectInputStream¾Í»áÓÃÊÔ̽²ÎÊý²âÊÔÆäËûµÄ * Óвι¹Ô캯Êý£¬À´ÊÔͼн¨¶ÔÏóʵÀý¡£Õâ»ØÔì³ÉÐÔÄÜÀË·Ñ£¬½¨ÒéÔÚ²»±ãʹÓÃÓвι¹Ô캯Êý * µÄÇé¿öÏ£¬¸øÐèÒªÊä³öµÄÀàдһ¸ö˽ÓеÄÎ޲ι¹Ô캯Êý¡£ * 3¡¢HPObjectOutputStreamºÍHPObjectInputStreamʹÓ÷´ÉäÀ´·ÃÎʶÔÏóµÄ¹¹Ô캯ÊýºÍ×Ö * ¶Î£¬µ«ÊÇÈç¹û¶ÔÏóÊÇÓÃÁËSecurityManagerÀ´½ûÖ¹£¬ÄÄÅÂʹÓÃsetAccessible(true)·½·¨£¬ * Ò²ÎÞ·¨·ÃÎʵϰ£¬HPObjectOutputStreamºÍHPObjectInputStream¾Í»áÅ׳öÒì³£¡£ * * ËÄ¡¢Î´½â¾öµÄBUG * 1¡¢ÔÚʹÓÃÖз¢ÏÖ£¬µ±Ê¹ÓÃHPObjectOutputStreamºÍHPObjectInputStreamʱ£¬¼«ÉÙÇé¿öÏ£¬ * »áËæ»úµÄ·¢ÉúConcurrentModificationException¡£Ô­Òò²»Ã÷£¬¿ÉÄܺͶÔд¼¯ºÏÀàÓйء£ * * */ public class HPObjectOutputStream extends DataOutputStream { private ObjectOutputStreamSupport support = new ObjectOutputStreamSupport(); public HPObjectOutputStream(OutputStream out) { super(out); } public void writeObject(Object object) throws IOException { support.writeObject(object, this); } }
mit
carlos-sancho-ramirez/android-java-langbook
app/src/main/java/sword/langbook3/android/DefinitionEditorActivity.java
6567
package sword.langbook3.android; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import sword.collections.ImmutableHashSet; import sword.collections.ImmutableSet; import sword.langbook3.android.db.AcceptationId; import sword.langbook3.android.db.AcceptationIdBundler; import sword.langbook3.android.db.AlphabetId; import sword.langbook3.android.db.ConceptId; import sword.langbook3.android.db.ConceptIdParceler; import sword.langbook3.android.db.LangbookDbChecker; public final class DefinitionEditorActivity extends Activity implements View.OnClickListener { private static final int REQUEST_CODE_PICK_BASE = 1; private static final int REQUEST_CODE_PICK_COMPLEMENT = 2; private interface SavedKeys { String STATE = "state"; } public interface ResultKeys { String VALUES = "values"; } public static void open(Activity activity, int requestCode) { final Intent intent = new Intent(activity, DefinitionEditorActivity.class); activity.startActivityForResult(intent, requestCode); } private State _state; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.definition_editor_activity); if (savedInstanceState != null) { _state = savedInstanceState.getParcelable(SavedKeys.STATE); } else { _state = new State(); } findViewById(R.id.baseConceptChangeButton).setOnClickListener(this); findViewById(R.id.complementsAddButton).setOnClickListener(this); findViewById(R.id.saveButton).setOnClickListener(this); updateUi(); } private void updateUi() { final LangbookDbChecker checker = DbManager.getInstance().getManager(); final AlphabetId preferredAlphabet = LangbookPreferences.getInstance().getPreferredAlphabet(); final TextView baseConceptTextView = findViewById(R.id.baseConceptText); final String text = (_state.baseConcept == null)? null : checker.readConceptText(_state.baseConcept, preferredAlphabet); baseConceptTextView.setText(text); final LinearLayout complementsPanel = findViewById(R.id.complementsPanel); complementsPanel.removeAllViews(); final LayoutInflater inflater = LayoutInflater.from(this); for (ConceptId complementConcept : _state.complements) { inflater.inflate(R.layout.definition_editor_complement_entry, complementsPanel, true); final TextView textView = complementsPanel.getChildAt(complementsPanel.getChildCount() - 1).findViewById(R.id.text); textView.setText(checker.readConceptText(complementConcept, preferredAlphabet)); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.baseConceptChangeButton: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_BASE); return; case R.id.complementsAddButton: AcceptationPickerActivity.open(this, REQUEST_CODE_PICK_COMPLEMENT); return; case R.id.saveButton: saveAndFinish(); return; } } private void saveAndFinish() { if (_state.baseConcept == null) { Toast.makeText(this, R.string.baseConceptMissing, Toast.LENGTH_SHORT).show(); } else { final Intent intent = new Intent(); intent.putExtra(ResultKeys.VALUES, _state); setResult(RESULT_OK, intent); finish(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PICK_BASE && resultCode == RESULT_OK && data != null) { final LangbookDbChecker checker = DbManager.getInstance().getManager(); final AcceptationId pickedAcceptation = AcceptationIdBundler.readAsIntentExtra(data, AcceptationPickerActivity.ResultKeys.STATIC_ACCEPTATION); _state.baseConcept = (pickedAcceptation != null)? checker.conceptFromAcceptation(pickedAcceptation) : null; updateUi(); } else if (requestCode == REQUEST_CODE_PICK_COMPLEMENT && resultCode == RESULT_OK && data != null) { final LangbookDbChecker checker = DbManager.getInstance().getManager(); final AcceptationId pickedAcceptation = AcceptationIdBundler.readAsIntentExtra(data, AcceptationPickerActivity.ResultKeys.STATIC_ACCEPTATION); _state.complements = _state.complements.add(checker.conceptFromAcceptation(pickedAcceptation)); updateUi(); } } @Override public void onSaveInstanceState(Bundle outBundle) { outBundle.putParcelable(SavedKeys.STATE, _state); } public static final class State implements Parcelable { public ConceptId baseConcept; public ImmutableSet<ConceptId> complements = ImmutableHashSet.empty(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { ConceptIdParceler.write(dest, baseConcept); final int complementCount = (complements != null)? complements.size() : 0; dest.writeInt(complementCount); if (complementCount > 0) { for (ConceptId complement : complements) { ConceptIdParceler.write(dest, complement); } } } public static final Creator<State> CREATOR = new Creator<State>() { @Override public State createFromParcel(Parcel in) { final State state = new State(); state.baseConcept = ConceptIdParceler.read(in); final int complementCount = in.readInt(); for (int i = 0; i < complementCount; i++) { state.complements = state.complements.add(ConceptIdParceler.read(in)); } return state; } @Override public State[] newArray(int size) { return new State[size]; } }; } }
mit
dirtyfilthy/dirtyfilthy-bouncycastle
net/dirtyfilthy/bouncycastle/crypto/agreement/DHAgreement.java
3319
package net.dirtyfilthy.bouncycastle.crypto.agreement; import java.math.BigInteger; import java.security.SecureRandom; import net.dirtyfilthy.bouncycastle.crypto.AsymmetricCipherKeyPair; import net.dirtyfilthy.bouncycastle.crypto.CipherParameters; import net.dirtyfilthy.bouncycastle.crypto.generators.DHKeyPairGenerator; import net.dirtyfilthy.bouncycastle.crypto.params.AsymmetricKeyParameter; import net.dirtyfilthy.bouncycastle.crypto.params.DHKeyGenerationParameters; import net.dirtyfilthy.bouncycastle.crypto.params.DHParameters; import net.dirtyfilthy.bouncycastle.crypto.params.DHPrivateKeyParameters; import net.dirtyfilthy.bouncycastle.crypto.params.DHPublicKeyParameters; import net.dirtyfilthy.bouncycastle.crypto.params.ParametersWithRandom; /** * a Diffie-Hellman key exchange engine. * <p> * note: This uses MTI/A0 key agreement in order to make the key agreement * secure against passive attacks. If you're doing Diffie-Hellman and both * parties have long term public keys you should look at using this. For * further information have a look at RFC 2631. * <p> * It's possible to extend this to more than two parties as well, for the moment * that is left as an exercise for the reader. */ public class DHAgreement { private DHPrivateKeyParameters key; private DHParameters dhParams; private BigInteger privateValue; private SecureRandom random; public void init( CipherParameters param) { AsymmetricKeyParameter kParam; if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; this.random = rParam.getRandom(); kParam = (AsymmetricKeyParameter)rParam.getParameters(); } else { this.random = new SecureRandom(); kParam = (AsymmetricKeyParameter)param; } if (!(kParam instanceof DHPrivateKeyParameters)) { throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters"); } this.key = (DHPrivateKeyParameters)kParam; this.dhParams = key.getParameters(); } /** * calculate our initial message. */ public BigInteger calculateMessage() { DHKeyPairGenerator dhGen = new DHKeyPairGenerator(); dhGen.init(new DHKeyGenerationParameters(random, dhParams)); AsymmetricCipherKeyPair dhPair = dhGen.generateKeyPair(); this.privateValue = ((DHPrivateKeyParameters)dhPair.getPrivate()).getX(); return ((DHPublicKeyParameters)dhPair.getPublic()).getY(); } /** * given a message from a given party and the corresponding public key, * calculate the next message in the agreement sequence. In this case * this will represent the shared secret. */ public BigInteger calculateAgreement( DHPublicKeyParameters pub, BigInteger message) { if (!pub.getParameters().equals(dhParams)) { throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters."); } BigInteger p = dhParams.getP(); return message.modPow(key.getX(), p).multiply(pub.getY().modPow(privateValue, p)).mod(p); } }
mit
shangyantao/dmapp
data-app/src/main/java/com/sap/data/app/entity/system/Event.java
1588
package com.sap.data.app.entity.system; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.GenericGenerator; import com.sap.data.app.entity.task.Task; @Entity //表名与类名不相同时重新定义表名. @Table(name = "DM_EVENT") //默认的缓存策略. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Event { private String eventId; private String eventName; /* private Task task; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="task_id") public Task getTask() { return task; } public void setTask(Task task) { this.task = task; }*/ public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } private String eventDes; private String comments; @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid") public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getEventDes() { return eventDes; } public void setEventDes(String eventDes) { this.eventDes = eventDes; } public String getComments() { return comments; } public void setComments(String comments) { this.comments = comments; } }
mit
magx2/jSupla
protocol-java/src/main/java/pl/grzeslowski/jsupla/protocoljava/api/parsers/cs/ChannelNewValueBParser.java
325
package pl.grzeslowski.jsupla.protocoljava.api.parsers.cs; import pl.grzeslowski.jsupla.protocol.api.structs.cs.SuplaChannelNewValueB; import pl.grzeslowski.jsupla.protocoljava.api.entities.cs.ChannelNewValueB; public interface ChannelNewValueBParser extends ClientServerParser<ChannelNewValueB, SuplaChannelNewValueB> { }
mit
PuumPuumPuum/jrpg
dominio/src/main/java/mergame/individuos/Atacable.java
106
package main.java.mergame.individuos; public interface Atacable { public void serAtacado(int danio); }
mit
jinsen47/iCharge
Client/app/src/main/java/com/icharge/api/IChargeServerAPI.java
470
package com.icharge.api; import com.icharge.beans.KnowListBean; import com.icharge.beans.LocationListBean; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; /** * Created by Jinsen on 15/5/23. */ public interface IChargeServerAPI { @GET("/api/articles") void getArticles(Callback<KnowListBean> response); @GET("/api/chargers/{city}") void getChargers(@Path("city") String city, Callback<LocationListBean> response); }
mit
sussexcoursedata/course_data_project
src/main/java/org/purl/dc/terms/TGN.java
1062
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.06.29 at 10:15:17 AM BST // package org.purl.dc.terms; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import org.purl.dc.elements._1.SimpleLiteral; /** * <p>Java class for TGN complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TGN"> * &lt;simpleContent> * &lt;restriction base="&lt;http://purl.org/dc/elements/1.1/>SimpleLiteral"> * &lt;/restriction> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TGN") public class TGN extends SimpleLiteral { }
mit