repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
kutsyy/com.kutsyy.lvspod
src/com/kutsyy/lvspod/OrdinalSpatialDataAgumentationPlot.java
11328
/* * put your module comment here * formatted with JxBeauty (c) johann.langhofer@nextra.at */ package com.kutsyy.lvspod; import java.awt.*; import java.awt.event.*; import javax.swing.*; import com.kutsyy.util.*; //import com.borland.jbcl.layout.*; /** * Title: com.kutsyy.lvspod Description: This library is set of rutins for * Laten Variable model for Spatialy dependent Ordinal Data Copyright: * Copyright (c) 2000 Company: The University of Michigan * *@author Vadim Kutsyy *@created January 8, 2001 *@version 1.0 */ /** * Title: com.kutsyy.lvspod Description: This library is set of rutins for * Laten Variable model for Spatialy dependent Ordinal Data Copyright: * Copyright (c) 2000 Company: The University of Michigan * * Title: com.kutsyy.lvspod Description: This library is set of rutins for * Laten Variable model for Spatialy dependent Ordinal Data Copyright: * Copyright (c) 2000 Company: The University of Michigan * *@author Vadim Kutsyy *@author Vadim Kutsyy *@created January 8, 2001 *@version 1.0 */ public class OrdinalSpatialDataAgumentationPlot extends JFrame { /** * Description of the Field */ public boolean stopDataAugmentation = false; JPanel contentPane; JMenuBar jMenuBar = new JMenuBar(); JMenu jMenuFile = new JMenu(); JMenuItem jMenuFileExit = new JMenuItem(); JMenu jMenuHelp = new JMenu(); JMenuItem jMenuHelpAbout = new JMenuItem(); JLabel statusBar = new JLabel(); BorderLayout borderLayoutMain = new BorderLayout(); JPanel jPanelPlot = new JPanel(); GridBagLayout gridBagLayout1 = new GridBagLayout(); JButton jButtonStop = new JButton(); JPanel jPanelStopBar = new JPanel(); JProgressBar jProgressBarX = new JProgressBar(); JProgressBar jProgressBarPhi = new JProgressBar(); JPanel jPanelBar = new JPanel(); CardLayout cardLayout1 = new CardLayout(); JSplitPane jSplitPaneButton = new JSplitPane(); JButton jButtonQuit = new JButton(); JMenuItem jMenuFileStop = new JMenuItem(); double q1Phi, q2Phi, q3Phi, meanPhi, xScale, yScale; double[] Phi; int current = 0, total; JPanel jPanelText = new JPanel(); JTextArea jTextAreaMean = new JTextArea(); JTextArea jTextAreaQ1 = new JTextArea(); JTextArea jTextAreaQ2 = new JTextArea(); JTextArea jTextAreaQ3 = new JTextArea(); /** * Construct the frame */ public OrdinalSpatialDataAgumentationPlot() { enableEvents(AWTEvent.WINDOW_EVENT_MASK); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } validate(); setVisible(true); } /** * put your documentation comment here * *@param phi *@param m */ public void initialize(double[] phi, int m) { try { meanPhi = Stat.mean(phi); xScale = jPanelPlot.getWidth() / (double) m; yScale = jPanelPlot.getHeight() / 2.0; total = m; current = 0; statusBar.setText("0/" + total); jPanelPlot.repaint(); jPanelPlot.setBackground(Color.yellow); jProgressBarPhi.setMaximum(m); jProgressBarPhi.setValue(0); jProgressBarX.setMaximum(m); jProgressBarX.setValue(0); stopDataAugmentation = false; } catch (Exception e) { e.printStackTrace(); } } /** * put your documentation comment here * *@param phi */ public void update(double[] phi) { //jPanelPlot.getGraphics().setColor(Color.black); //jPanelPlot.getGraphics().drawLine((int)((current++)*xScale),(int)((1-meanPhi)*yScale),(int)(current*xScale),(int)((1-(meanPhi=Stat.mean(phi)))*yScale)); meanPhi = Stat.mean(phi); statusBar.setText(current + "/" + total); jTextAreaMean.setText("Mean=" + Math.round(meanPhi * 1000) / 1000.0); jProgressBarPhi.setValue(0); jProgressBarX.setValue(0); Phi = (double[]) phi; java.util.Arrays.sort(Phi); //jPanelPlot.getGraphics().setColor(Color.blue); if (current == total) { current = 0; jPanelPlot.repaint(); jPanelPlot.setBackground(Color.yellow); } jPanelPlot.getGraphics().drawLine((int) ((current) * xScale), (int) ((1 - q2Phi) * yScale), (int) ((current + 1) * xScale), (int) ((1 - (q2Phi = Phi[(int) (2 * Phi.length / 4.0)])) * yScale)); //jPanelPlot.getGraphics().setColor(Color.red); jPanelPlot.getGraphics().drawLine((int) ((current) * xScale), (int) ((1 - q1Phi) * yScale), (int) ((current + 1) * xScale), (int) ((1 - (q1Phi = Phi[(int) (Phi.length / 4.0)])) * yScale)); jPanelPlot.getGraphics().drawLine((int) ((current) * xScale), (int) ((1 - q3Phi) * yScale), (int) ((current + 1) * xScale), (int) ((1 - (q3Phi = Phi[(int) (3 * Phi.length / 4.0)])) * yScale)); jTextAreaQ2.setText(" Q2=" + Math.round(q2Phi * 1000) / 1000.0); jTextAreaQ1.setText(" Q1=" + Math.round(q1Phi * 1000) / 1000.0); jTextAreaQ3.setText(" Q3=" + Math.round(q3Phi * 1000) / 1000.0); current++; } /** * File | Exit action performed * *@param e Description of Parameter */ public void jMenuFileExit_actionPerformed(ActionEvent e) { System.exit(0); } /** * Help | About action performed * *@param e Description of Parameter */ public void jMenuHelpAbout_actionPerformed(ActionEvent e) { OrdinalSpatialDataAgumentationPlot_AboutBox dlg = new OrdinalSpatialDataAgumentationPlot_AboutBox(this); Dimension dlgSize = dlg.getPreferredSize(); Dimension frmSize = getSize(); Point loc = getLocation(); dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y); dlg.setModal(true); dlg.show(); } /** * Overridden so we can exit when window is closed * *@param e Description of Parameter */ protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { jMenuFileExit_actionPerformed(null); } } /** * Component initialization * *@exception Exception Description of Exception */ private void jbInit() throws Exception { //setIconImage(Toolkit.getDefaultToolkit().createImage(OrdinalSpatialDataAgumentationPlot.class.getResource("[Your Icon]"))); contentPane = (JPanel) this.getContentPane(); contentPane.setLayout(borderLayoutMain); this.setSize(new Dimension(500, 250)); this.setTitle("Data Agumentation Plot"); statusBar.setBackground(Color.lightGray); statusBar.setOpaque(true); statusBar.setToolTipText("Status bar display current information"); statusBar.setText(" Status"); jMenuFile.setText("File"); jMenuFileExit.setText("Exit"); jMenuFileExit.addActionListener( new ActionListener() { /** * put your documentation comment here * *@param e */ public void actionPerformed(ActionEvent e) { System.exit(0); } }); jMenuHelp.setText("Help"); jMenuHelpAbout.setText("About"); jMenuHelpAbout.addActionListener( new ActionListener() { /** * put your documentation comment here * *@param e */ public void actionPerformed(ActionEvent e) { jMenuHelpAbout_actionPerformed(e); } }); contentPane.setBackground(Color.white); //contentPane.setMinimumSize(new Dimension(700, 500)); // jPanelPlot.setBackground(Color.yellow); // jPanelPlot.setBorder(BorderFactory.createLineBorder(Color.black)); // jPanelPlot.setSize(600,200); // //jPanelPlot.setLocation(25,125); //jMeanPhi.setText("Mean(Phi)=0"); jButtonStop.removeAll(); jButtonStop.setBackground(Color.red); jButtonStop.setFont(new java.awt.Font("Dialog", 1, 14)); jButtonStop.setBorder(BorderFactory.createRaisedBevelBorder()); jButtonStop.setToolTipText("To stop Data Augmentation Click Here"); jButtonStop.setHorizontalTextPosition(SwingConstants.CENTER); jButtonStop.setText("Stop"); jButtonStop.setVerticalAlignment(SwingConstants.BOTTOM); jButtonStop.addMouseListener( new java.awt.event.MouseAdapter() { /** * put your documentation comment here * *@param e */ public void mouseClicked(MouseEvent e) { stopDataAugmentation = true; } }); jButtonQuit.addMouseListener( new java.awt.event.MouseAdapter() { /** * put your documentation comment here * *@param e */ public void mouseClicked(MouseEvent e) { System.exit(0); } }); jPanelStopBar.setBackground(Color.white); jPanelStopBar.setDoubleBuffered(false); jPanelStopBar.setMinimumSize(new Dimension(10, 30)); jPanelStopBar.setLayout(new BorderLayout()); jProgressBarX.setBackground(Color.cyan); jProgressBarX.setBorder(BorderFactory.createLineBorder(Color.black)); jProgressBarX.setMinimumSize(new Dimension(10, 5)); jProgressBarX.setToolTipText(""); jProgressBarX.setMaximum(10000); jProgressBarPhi.setToolTipText(""); jProgressBarPhi.setMaximum(10000); jProgressBarPhi.setMinimumSize(new Dimension(10, 5)); jProgressBarPhi.setBorder(BorderFactory.createLineBorder(Color.black)); jProgressBarPhi.setBackground(Color.cyan); jPanelBar.setBackground(Color.white); jPanelBar.setLayout(new GridLayout(2, 1)); jSplitPaneButton.setOrientation(JSplitPane.VERTICAL_SPLIT); jSplitPaneButton.setBackground(Color.white); jSplitPaneButton.setForeground(Color.white); jSplitPaneButton.setBorder(null); jSplitPaneButton.setDividerSize(0); jSplitPaneButton.setLeftComponent(null); jSplitPaneButton.setTopComponent(jButtonStop); jButtonQuit.setBackground(Color.red); jButtonQuit.setFont(new java.awt.Font("Dialog", 1, 16)); jButtonQuit.setBorder(BorderFactory.createRaisedBevelBorder()); jButtonQuit.setText("Quit"); jMenuFileStop.addActionListener( new ActionListener() { /** * put your documentation comment here * *@param e */ public void actionPerformed(ActionEvent e) { stopDataAugmentation = true; } }); jMenuFileStop.setActionCommand("Stop"); jMenuFileStop.setText("Stop"); // jQ1Phi.setText("Q1(phi)=0"); // jQ3Phi.setText("Q3(phi)="); // jQ2Phi.setText("Q2(phi)"); // jQ2Phi.setToolTipText(""); jPanelText.setBackground(Color.white); jTextAreaMean.setText("Mean=0.000"); jTextAreaQ1.setText("Q1=0.000"); jTextAreaQ2.setText("Q2=0.000"); jTextAreaQ3.setText("Q3=0.000"); jPanelPlot.setBackground(Color.yellow); jMenuFile.add(jMenuFileStop); jMenuFile.add(jMenuFileExit); jMenuHelp.add(jMenuHelpAbout); jMenuBar.add(jMenuFile); jMenuBar.add(jMenuHelp); this.setJMenuBar(jMenuBar); contentPane.add(statusBar, BorderLayout.SOUTH); contentPane.add(jPanelPlot, BorderLayout.CENTER); contentPane.add(jPanelStopBar, BorderLayout.NORTH); jPanelStopBar.add(jPanelBar, BorderLayout.WEST); jPanelBar.add(jProgressBarX, BorderLayout.WEST); jPanelBar.add(jProgressBarPhi, BorderLayout.CENTER); jPanelStopBar.add(jSplitPaneButton, BorderLayout.EAST); jSplitPaneButton.add(jButtonStop, JSplitPane.TOP); jSplitPaneButton.add(jButtonQuit, JSplitPane.BOTTOM); jPanelText.setLayout(new GridLayout(2, 2)); jPanelStopBar.add(jPanelText, BorderLayout.CENTER); jPanelText.add(jTextAreaMean, null); jPanelText.add(jTextAreaQ1, null); jPanelText.add(jTextAreaQ2, null); jPanelText.add(jTextAreaQ3, null); } // protected void stop(){ // stopDataAugmentation=true; // } // protected void quit(){ // if(stopDataAugmentation) System.exit(0); // } // void jMenuFileStop_actionPerformed(ActionEvent e) { // stopDataAugmentation=true; // // } }
apache-2.0
datancoffee/sirocco
src/main/java/sirocco/indexer/dictionaries/en/NegatorDictionary.java
1561
/******************************************************************************* * Copyright 2008 and onwards Sergei Sokolenko, Alexey Shevchuk, * Sergey Shevchook, and Roman Khnykin. * * This product includes software developed at * Cuesense 2008-2011 (http://www.cuesense.com/). * * This product includes software developed by * Sergei Sokolenko (@datancoffee) 2008-2017. * * 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. * * Author(s): * Sergei Sokolenko (@datancoffee) *******************************************************************************/ package sirocco.indexer.dictionaries.en; import java.io.InputStream; import sirocco.indexer.FloatVector; import sirocco.indexer.FloatVectorFactory; import sirocco.indexer.dictionaries.GenericDictionary; public class NegatorDictionary extends GenericDictionary<FloatVector> { public NegatorDictionary(InputStream dictionarystream) throws Exception { super(dictionarystream, new FloatVectorFactory()); } }
apache-2.0
diyanfilipov/potlach-client
src/com/android/potlach/ui/SearchResultsActivity.java
6289
package com.android.potlach.ui; import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.GridView; import android.widget.TextView; import com.android.potlach.R; import com.android.potlach.entity.Gift; import com.android.potlach.task.SearchGiftsTask; import com.android.potlach.ui.adapter.GiftGridAdapter; import com.android.potlach.ui.fragment.GiftsFragment; import java.util.ArrayList; import java.util.List; public class SearchResultsActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener{ private static final String TAG = SearchResultsActivity.class.getSimpleName(); private TextView txtQuery; private GiftGridAdapter adapter; private SwipeRefreshLayout swipeRefreshLayout; private int currentPage = 0; private int lastAddedCount = 0; private boolean refreshing; private boolean loadedAllData; private String query; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_results); // get the action bar // ActionBar actionBar = getActionBar(); // Enabling Back navigation on Action Bar icon // actionBar.setDisplayHomeAsUpEnabled(true); // txtQuery = (TextView) findViewById(R.id.txtQuery); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { // setIntent(intent); // handleIntent(intent); } /** * Handling intent data */ private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); getActionBar().setTitle(query); final GridView gridView = (GridView) findViewById(R.id.grid); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); swipeRefreshLayout.setOnRefreshListener(this); swipeRefreshLayout.setColorScheme( android.R.color.holo_green_dark, android.R.color.holo_red_dark, android.R.color.holo_blue_dark, android.R.color.holo_orange_dark); if(adapter == null) { adapter = new GiftGridAdapter(this, new ArrayList<Gift>()); } gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d(TAG, "Clicked on position=" + position); Intent viewGiftIntent = new Intent(); viewGiftIntent.setClass(SearchResultsActivity.this, ViewGiftActivity.class); viewGiftIntent.putExtra("giftId", adapter.getItemId(position)); startActivity(viewGiftIntent); } }); gridView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // Log.d(TAG, String.valueOf(gridView.getHeight() + " " + view.getBottom())); // View lastGridChild = gridView.getChildAt(gridView.getChildCount() - 1); // if(lastGridChild != null) { // int diff = (lastGridChild.getBottom() - (view.getHeight() + view.getScrollY())); // if (diff == 0 && !refreshing && !loadedAllData) { // Log.d(TAG, "GridView end reached."); // performRefresh(true, false); // } // } if (firstVisibleItem + visibleItemCount >= totalItemCount && !refreshing && !loadedAllData) { // End has been reached // Toast.makeText(getActivity(), "END REACHED", Toast.LENGTH_SHORT).show(); Log.d(TAG, "GridView end reached."); performRefresh(true, false); } } }); performRefresh(true, false); } } @Override public void onRefresh() { performRefresh(false, true); } private void performRefresh(boolean loadNewData, boolean overrideGifts){ if(loadNewData && !refreshing){ startListGiftTask(overrideGifts, currentPage, 15); // new ListGiftsTask("admin", null, overrideGifts, this).execute(currentPage, 15); currentPage += 1; }else if(!refreshing) { if(adapter.getCount() == 0){ startListGiftTask(overrideGifts, currentPage, 15); // new ListGiftsTask("admin", null, overrideGifts, this).execute(currentPage, 15); currentPage += 1; }else{ startListGiftTask(overrideGifts, 0, adapter.getCount() + lastAddedCount); // new ListGiftsTask("admin", null, overrideGifts, this).execute(0, adapter.getCount() + lastAddedCount); } } } private void startListGiftTask(boolean overrideGifts, int page, int size){ refreshing = true; swipeRefreshLayout.setRefreshing(true); new SearchGiftsTask(query, overrideGifts, this).execute(page, size); } public void displaySearchResults(List<Gift> gifts, boolean overrideData) { if(!gifts.isEmpty()) { Log.d(TAG, "Searching finished. Refreshing Grid with " + gifts.size() + " items."); adapter.onDataChanged(gifts, overrideData); lastAddedCount = gifts.size(); loadedAllData = false; if(lastAddedCount < 15){ loadedAllData = true; } }else{ loadedAllData = true; } refreshing = false; swipeRefreshLayout.setRefreshing(false); } }
apache-2.0
preemynence/SpringProjectExamples
springStarterProject/src/main/java/springStarterProject/model/Student.java
1437
package springStarterProject.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Students") public class Student implements Serializable { /** * */ private static final long serialVersionUID = -4291575996786546686L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column private String name; @Column private int rollNumber; @Column private float cpi; public Student() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRollNumber() { return rollNumber; } public void setRollNumber(int rollNumber) { this.rollNumber = rollNumber; } public float getCpi() { return cpi; } public void setCpi(float cpi) { this.cpi = cpi; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", rollNumber=" + rollNumber + ", cpi=" + cpi + '}'; } }
apache-2.0
chensy-and/maksmaigin
maksmaigin/app/src/main/java/com/csy/maksmaigin/robot/util/SystemBarTintManager.java
19434
package com.csy.maksmaigin.robot.util; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout.LayoutParams; import java.lang.reflect.Method; /** * Class to manage status and navigation bar tint effects when using KitKat * translucent system UI modes. * */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class SystemBarTintManager { static { // Android allows a system property to override the presence of the navigation bar. // Used by the emulator. // See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { try { Class c = Class.forName("android.os.SystemProperties"); Method m = c.getDeclaredMethod("get", String.class); m.setAccessible(true); sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys"); } catch (Throwable e) { sNavBarOverride = null; } } } /** * The default system bar tint color value. */ public static final int DEFAULT_TINT_COLOR = 0x99000000; private static String sNavBarOverride; private final SystemBarConfig mConfig; private boolean mStatusBarAvailable; private boolean mNavBarAvailable; private boolean mStatusBarTintEnabled; private boolean mNavBarTintEnabled; private View mStatusBarTintView; private View mNavBarTintView; /** * Constructor. Call this in the host activity onCreate method after its * content view has been set. You should always create new instances when * the host activity is recreated. * * @param activity The host activity. */ @TargetApi(19) public SystemBarTintManager(Activity activity) { Window win = activity.getWindow(); ViewGroup decorViewGroup = (ViewGroup) win.getDecorView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // check theme attrs int[] attrs = {android.R.attr.windowTranslucentStatus, android.R.attr.windowTranslucentNavigation}; TypedArray a = activity.obtainStyledAttributes(attrs); try { mStatusBarAvailable = a.getBoolean(0, false); mNavBarAvailable = a.getBoolean(1, false); } finally { a.recycle(); } // check window flags WindowManager.LayoutParams winParams = win.getAttributes(); int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if ((winParams.flags & bits) != 0) { mStatusBarAvailable = true; } bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; if ((winParams.flags & bits) != 0) { mNavBarAvailable = true; } } mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable); // device might not have virtual navigation keys if (!mConfig.hasNavigtionBar()) { mNavBarAvailable = false; } if (mStatusBarAvailable) { setupStatusBarView(activity, decorViewGroup); } if (mNavBarAvailable) { setupNavBarView(activity, decorViewGroup); } } /** * Enable tinting of the system status bar. * * If the platform is running Jelly Bean or earlier, or translucent system * UI modes have not been enabled in either the theme or via window flags, * then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setStatusBarTintEnabled(boolean enabled) { mStatusBarTintEnabled = enabled; if (mStatusBarAvailable) { mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * Enable tinting of the system navigation bar. * * If the platform does not have soft navigation keys, is running Jelly Bean * or earlier, or translucent system UI modes have not been enabled in either * the theme or via window flags, then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setNavigationBarTintEnabled(boolean enabled) { mNavBarTintEnabled = enabled; if (mNavBarAvailable) { mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * Apply the specified color tint to all system UI bars. * * @param color The color of the background tint. */ public void setTintColor(int color) { setStatusBarTintColor(color); setNavigationBarTintColor(color); } /** * Apply the specified drawable or color resource to all system UI bars. * * @param res The identifier of the resource. */ public void setTintResource(int res) { setStatusBarTintResource(res); setNavigationBarTintResource(res); } /** * Apply the specified drawable to all system UI bars. * * @param drawable The drawable to use as the background, or null to remove it. */ public void setTintDrawable(Drawable drawable) { setStatusBarTintDrawable(drawable); setNavigationBarTintDrawable(drawable); } /** * Apply the specified alpha to all system UI bars. * * @param alpha The alpha to use */ public void setTintAlpha(float alpha) { setStatusBarAlpha(alpha); setNavigationBarAlpha(alpha); } /** * Apply the specified color tint to the system status bar. * * @param color The color of the background tint. */ public void setStatusBarTintColor(int color) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system status bar. * * @param res The identifier of the resource. */ public void setStatusBarTintResource(int res) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system status bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setStatusBarTintDrawable(Drawable drawable) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system status bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setStatusBarAlpha(float alpha) { if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mStatusBarTintView.setAlpha(alpha); } } /** * Apply the specified color tint to the system navigation bar. * * @param color The color of the background tint. */ public void setNavigationBarTintColor(int color) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system navigation bar. * * @param res The identifier of the resource. */ public void setNavigationBarTintResource(int res) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system navigation bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setNavigationBarTintDrawable(Drawable drawable) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system navigation bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setNavigationBarAlpha(float alpha) { if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mNavBarTintView.setAlpha(alpha); } } /** * Get the system bar configuration. * * @return The system bar configuration for the current device configuration. */ public SystemBarConfig getConfig() { return mConfig; } /** * Is tinting enabled for the system status bar? * * @return True if enabled, False otherwise. */ public boolean isStatusBarTintEnabled() { return mStatusBarTintEnabled; } /** * Is tinting enabled for the system navigation bar? * * @return True if enabled, False otherwise. */ public boolean isNavBarTintEnabled() { return mNavBarTintEnabled; } private void setupStatusBarView(Context context, ViewGroup decorViewGroup) { mStatusBarTintView = new View(context); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight()); params.gravity = Gravity.TOP; if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) { params.rightMargin = mConfig.getNavigationBarWidth(); } mStatusBarTintView.setLayoutParams(params); mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mStatusBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mStatusBarTintView); } private void setupNavBarView(Context context, ViewGroup decorViewGroup) { mNavBarTintView = new View(context); LayoutParams params; if (mConfig.isNavigationAtBottom()) { params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight()); params.gravity = Gravity.BOTTOM; } else { params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT); params.gravity = Gravity.RIGHT; } mNavBarTintView.setLayoutParams(params); mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mNavBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mNavBarTintView); } /** * Class which describes system bar sizing and other characteristics for the current * device configuration. * */ public static class SystemBarConfig { private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height"; private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height"; private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape"; private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width"; private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar"; private final boolean mTranslucentStatusBar; private final boolean mTranslucentNavBar; private final int mStatusBarHeight; private final int mActionBarHeight; private final boolean mHasNavigationBar; private final int mNavigationBarHeight; private final int mNavigationBarWidth; private final boolean mInPortrait; private final float mSmallestWidthDp; private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) { Resources res = activity.getResources(); mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT); mSmallestWidthDp = getSmallestWidthDp(activity); mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME); mActionBarHeight = getActionBarHeight(activity); mNavigationBarHeight = getNavigationBarHeight(activity); mNavigationBarWidth = getNavigationBarWidth(activity); mHasNavigationBar = (mNavigationBarHeight > 0); mTranslucentStatusBar = translucentStatusBar; mTranslucentNavBar = traslucentNavBar; } @TargetApi(14) private int getActionBarHeight(Context context) { int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics()); } return result; } @TargetApi(14) private int getNavigationBarHeight(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (hasNavBar(context)) { String key; if (mInPortrait) { key = NAV_BAR_HEIGHT_RES_NAME; } else { key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME; } return getInternalDimensionSize(res, key); } } return result; } @TargetApi(14) private int getNavigationBarWidth(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (hasNavBar(context)) { return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME); } } return result; } @TargetApi(14) private boolean hasNavBar(Context context) { Resources res = context.getResources(); int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android"); if (resourceId != 0) { boolean hasNav = res.getBoolean(resourceId); // check override flag (see static block) if ("1".equals(sNavBarOverride)) { hasNav = false; } else if ("0".equals(sNavBarOverride)) { hasNav = true; } return hasNav; } else { // fallback return !ViewConfiguration.get(context).hasPermanentMenuKey(); } } private int getInternalDimensionSize(Resources res, String key) { int result = 0; int resourceId = res.getIdentifier(key, "dimen", "android"); if (resourceId > 0) { result = res.getDimensionPixelSize(resourceId); } return result; } @SuppressLint("NewApi") private float getSmallestWidthDp(Activity activity) { DisplayMetrics metrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); } else { // TODO this is not correct, but we don't really care pre-kitkat activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } float widthDp = metrics.widthPixels / metrics.density; float heightDp = metrics.heightPixels / metrics.density; return Math.min(widthDp, heightDp); } /** * Should a navigation bar appear at the bottom of the screen in the current * device configuration? A navigation bar may appear on the right side of * the screen in certain configurations. * * @return True if navigation should appear at the bottom of the screen, False otherwise. */ public boolean isNavigationAtBottom() { return (mSmallestWidthDp >= 600 || mInPortrait); } /** * Get the height of the system status bar. * * @return The height of the status bar (in pixels). */ public int getStatusBarHeight() { return mStatusBarHeight; } /** * Get the height of the action bar. * * @return The height of the action bar (in pixels). */ public int getActionBarHeight() { return mActionBarHeight; } /** * Does this device have a system navigation bar? * * @return True if this device uses soft key navigation, False otherwise. */ public boolean hasNavigtionBar() { return mHasNavigationBar; } /** * Get the height of the system navigation bar. * * @return The height of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarHeight() { return mNavigationBarHeight; } /** * Get the width of the system navigation bar when it is placed vertically on the screen. * * @return The width of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarWidth() { return mNavigationBarWidth; } /** * Get the layout inset for any system UI that appears at the top of the screen. * * @param withActionBar True to include the height of the action bar, False otherwise. * @return The layout inset (in pixels). */ public int getPixelInsetTop(boolean withActionBar) { return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0); } /** * Get the layout inset for any system UI that appears at the bottom of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetBottom() { if (mTranslucentNavBar && isNavigationAtBottom()) { return mNavigationBarHeight; } else { return 0; } } /** * Get the layout inset for any system UI that appears at the right of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetRight() { if (mTranslucentNavBar && !isNavigationAtBottom()) { return mNavigationBarWidth; } else { return 0; } } } }
apache-2.0
angel-git/wso2is-springoauth
src/main/java/com/yenlo/oauth/OAuth2ServerConfiguration.java
4345
package com.yenlo.oauth; import com.yenlo.oauth.token.ws.OAuth2TokenValidationService; import com.yenlo.oauth.token.ws.OAuthAdminService; import com.yenlo.oauth.token.ws.WSWso2TokenStore; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.ws.transport.http.HttpUrlConnectionMessageSender; import sun.misc.BASE64Encoder; import javax.sql.DataSource; import java.io.IOException; import java.net.HttpURLConnection; /** * OAuth2 Resource Server configuration * Created by Gavalda on 2/27/2015. */ @Configuration @EnableResourceServer public class OAuth2ServerConfiguration extends ResourceServerConfigurerAdapter { private static final String APPROVED_APPLICATION = "serviceProvider"; @Override public void configure(ResourceServerSecurityConfigurer resources) { //JDBC //TokenStore wso2TokenStore = new JdbcWso2TokenStore(wso2OauthDataSource()); //WS TokenStore wso2TokenStore = new WSWso2TokenStore(oAuthAdminServiceClient(marshaller()), oAuth2TokenValidationService(marshaller())); //EXAMPLE: DO NOT DO THIS System.setProperty("javax.net.ssl.trustStore", "C:/dev/wso2is-5.0.0/repository/resources/security/wso2carbon.jks"); System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon"); System.setProperty("javax.net.ssl.trustStoreType", "JKS"); resources.tokenStore(wso2TokenStore); } @Override public void configure(HttpSecurity http) throws Exception { //sets the authority as the application name defined in wso2 http .authorizeRequests() .antMatchers("/greeting").hasAuthority(APPROVED_APPLICATION); } @Bean @ConfigurationProperties(prefix = "spring.datasource_oauth") public DataSource wso2OauthDataSource() { return DataSourceBuilder.create().build(); } private Jaxb2Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("wso2.services"); return marshaller; } private HttpUrlConnectionMessageSender messageSender() { return new HttpUrlConnectionMessageSender() { @Override protected void prepareConnection(HttpURLConnection connection) throws IOException { BASE64Encoder enc = new sun.misc.BASE64Encoder(); String userpassword = "admin:admin"; String encodedAuthorization = enc.encode(userpassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " + encodedAuthorization); super.prepareConnection(connection); } }; } private OAuthAdminService oAuthAdminServiceClient(Jaxb2Marshaller marshaller) { OAuthAdminService client = new OAuthAdminService(); client.setDefaultUri("https://localhost:9443/services/OAuthAdminService.OAuthAdminServiceHttpsSoap11Endpoint/"); client.setMarshaller(marshaller); client.setUnmarshaller(marshaller); client.setMessageSender(messageSender()); return client; } private OAuth2TokenValidationService oAuth2TokenValidationService(Jaxb2Marshaller marshaller) { OAuth2TokenValidationService client = new OAuth2TokenValidationService(); client.setDefaultUri("https://localhost:9443/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/"); client.setMarshaller(marshaller); client.setUnmarshaller(marshaller); client.setMessageSender(messageSender()); return client; } }
apache-2.0
Shulander/hackerrank
src/main/java/us/vicentini/hackerrank/algorithms/strings/Pangrams.java
1720
/* * 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 us.vicentini.hackerrank.algorithms.strings; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/pangrams * https://www.hackerrank.com/challenges/pangrams/submissions/code/19399361 * * Sample Input * Input #1 * We promptly judged antique ivory buckles for the next prize * Input #2 * We promptly judged antique ivory buckles for the prize * * Sample Output * Output #1 * pangram * Output #2 * not pangram * * @author Shulander */ public class Pangrams { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); System.out.println(isPangrams(str)?"pangram":"not pangram"); } private static boolean isPangrams(String str) { str = str.toLowerCase(); int charAValue = Character.getNumericValue('a'); int charZValue = Character.getNumericValue('z'); boolean allChars[] = new boolean[charZValue - charAValue + 1]; for (int i = 0; i < allChars.length; i++) { allChars[i] = false; } char[] array = str.toCharArray(); for (char b : array) { int charValue = Character.getNumericValue(b); if (charValue >= charAValue && charValue <= charZValue) { allChars[charValue-charAValue] = true; } } for (int i = 0; i < allChars.length; i++) { if(!allChars[i]) { return false; } } return true; } }
apache-2.0
jesse-gallagher/Miscellany
frostillicus.wrapbootstrap.ace_1.3/src/frostillicus/wrapbootstrap/ace1_3/renderkit/outline/AceBreadCrumbsRenderer.java
587
package frostillicus.wrapbootstrap.ace1_3.renderkit.outline; import javax.faces.context.FacesContext; import com.ibm.xsp.extlib.component.outline.AbstractOutline; import com.ibm.xsp.extlib.renderkit.html_extended.outline.AbstractOutlineRenderer; import com.ibm.xsp.extlib.tree.ITreeRenderer; public class AceBreadCrumbsRenderer extends AbstractOutlineRenderer { @Override protected ITreeRenderer findTreeRenderer(final FacesContext context, final AbstractOutline outline) { return new frostillicus.wrapbootstrap.ace1_3.renderkit.outline.tree.AceBreadCrumbsRenderer(outline); } }
apache-2.0
jetdario/hrms
src/java/com/openhris/employee/EmployeePersonalInformation.java
28498
/* * 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 com.openhris.employee; import com.hrms.classes.GlobalVariables; import com.hrms.utilities.ConvertionUtilities; import com.openhris.commons.DropDownComponent; import com.openhris.commons.UploadImage; import com.openhris.model.Employee; import com.openhris.model.PersonalInformation; import com.openhris.model.PostEmploymentInformationBean; import com.openhris.service.EmployeeCurrentStatusService; import com.openhris.service.PersonalInformationService; import com.openhris.serviceprovider.EmployeeCurrentStatusServiceImpl; import com.openhris.serviceprovider.EmployeeServiceImpl; import com.openhris.serviceprovider.PersonalInformationServiceImpl; import com.openhris.service.EmployeeService; import com.vaadin.Application; import com.vaadin.terminal.Sizeable; import com.vaadin.terminal.StreamResource; import com.vaadin.terminal.ThemeResource; import com.vaadin.ui.AbstractLayout; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.ComboBox; import com.vaadin.ui.ComponentContainer; import com.vaadin.ui.DateField; import com.vaadin.ui.Embedded; import com.vaadin.ui.GridLayout; import com.vaadin.ui.Panel; import com.vaadin.ui.PopupDateField; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import com.vaadin.ui.themes.Reindeer; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Date; import java.util.List; /** * * @author jet */ public class EmployeePersonalInformation extends VerticalLayout{ GridLayout glayout; private String employeeId = null; private Application application; DropDownComponent dropDownComponent = new DropDownComponent(); PersonalInformation personalInformation; PersonalInformationService piService = new PersonalInformationServiceImpl(); ConvertionUtilities convertionUtilities = new ConvertionUtilities(); EmployeeCurrentStatusService employeeCurrentStatusService = new EmployeeCurrentStatusServiceImpl(); EmployeeService employeeService = new EmployeeServiceImpl(); Embedded avatar; TextField fnField; TextField mnField; TextField lnField; TextField companyIdField; PopupDateField dobField; TextField pobField; ComboBox genderBox; ComboBox civilStatusBox; TextField citizenshipField; TextField heightField; TextField weightField; TextField religionField; TextField spouseNameField; TextField spouseOccupationField; TextField spouseOfficeAddressField; TextField fathersNameField; TextField fathersOccupationField; TextField mothersNameField; TextField mothersOccupationField; TextField parentsAddressField; TextField dialectSpeakWriteField; TextField contactPersonNameField; TextField contactPersonAddressField; TextField contactPersonNoField; TextField skillsField; TextField hobbyField; public EmployeePersonalInformation(){} public EmployeePersonalInformation(String employeeId, Application application){ this.employeeId = employeeId; this.application = application; init(); addComponent(layout()); setComponentAlignment(glayout, Alignment.TOP_CENTER); } public void init(){ setSpacing(true); setMargin(true); setSizeFull(); setImmediate(true); } public ComponentContainer layout(){ glayout = new GridLayout(4, 19); glayout.setSpacing(true); glayout.setWidth("600px"); glayout.setHeight("100%"); final Panel imagePanel = new Panel(); imagePanel.setStyleName("light"); AbstractLayout panelLayout = (AbstractLayout) imagePanel.getContent(); panelLayout.setMargin(false); imagePanel.setWidth("100px"); avatar = new Embedded(null, new ThemeResource("../myTheme/img/fnc.jpg")); avatar.setImmediate(true); avatar.setWidth(90, Sizeable.UNITS_PIXELS); avatar.setHeight(90, Sizeable.UNITS_PIXELS); avatar.addStyleName("logo-img"); imagePanel.addComponent(avatar); glayout.addComponent(avatar, 0, 0, 0, 1); glayout.setComponentAlignment(imagePanel, Alignment.MIDDLE_CENTER); Button uploadPhotoBtn = new Button("Upload.."); uploadPhotoBtn.setWidth("100%"); uploadPhotoBtn.setStyleName(Reindeer.BUTTON_SMALL); uploadPhotoBtn.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { if(getEmployeeId() == null){ getWindow().showNotification("You did not select and Employee!", Window.Notification.TYPE_WARNING_MESSAGE); return; } Window uploadImage = new UploadImage(imagePanel, avatar, getEmployeeId()); uploadImage.setWidth("450px"); if(uploadImage.getParent() == null){ getWindow().addWindow(uploadImage); } uploadImage.setModal(true); uploadImage.center(); } }); glayout.addComponent(uploadPhotoBtn, 0, 2); glayout.setComponentAlignment(uploadPhotoBtn, Alignment.MIDDLE_CENTER); fnField = createTextField("Firstname: "); glayout.addComponent(fnField, 1, 0); glayout.setComponentAlignment(fnField, Alignment.MIDDLE_LEFT); mnField = createTextField("Middlename: "); glayout.addComponent(mnField, 2, 0); glayout.setComponentAlignment(mnField, Alignment.MIDDLE_LEFT); lnField = createTextField("Lastname: "); glayout.addComponent(lnField, 3, 0); glayout.setComponentAlignment(lnField, Alignment.MIDDLE_LEFT); companyIdField = createTextField("Employee ID: "); companyIdField.setEnabled(false); glayout.addComponent(companyIdField, 1, 1, 2, 1); glayout.setComponentAlignment(companyIdField, Alignment.MIDDLE_LEFT); dobField = new PopupDateField("Date of Birth: "); dobField.addStyleName("mydate"); dobField.setDateFormat("MM/dd/yyyy"); dobField.setWidth("100%"); dobField.setResolution(DateField.RESOLUTION_DAY); glayout.addComponent(dobField, 1, 2); glayout.setComponentAlignment(dobField, Alignment.MIDDLE_LEFT); pobField = createTextField("Birth Place: "); pobField.setValue("N/A"); glayout.addComponent(pobField, 2, 2, 3, 2); glayout.setComponentAlignment(pobField, Alignment.MIDDLE_LEFT); genderBox = dropDownComponent.populateGenderList(new ComboBox()); genderBox.setWidth("100%"); glayout.addComponent(genderBox, 1, 3); glayout.setComponentAlignment(genderBox, Alignment.MIDDLE_LEFT); civilStatusBox = dropDownComponent.populateCivilStatusList(new ComboBox()); civilStatusBox.setWidth("100%"); glayout.addComponent(civilStatusBox, 2, 3); glayout.setComponentAlignment(civilStatusBox, Alignment.MIDDLE_LEFT); citizenshipField = createTextField("Citizenship: "); citizenshipField.setValue("N/A"); glayout.addComponent(citizenshipField, 3, 3); glayout.setComponentAlignment(citizenshipField, Alignment.MIDDLE_LEFT); heightField = createTextField("Height(cm):"); heightField.setValue(0.0); glayout.addComponent(heightField, 1, 4); glayout.setComponentAlignment(heightField, Alignment.MIDDLE_LEFT); weightField = createTextField("Weight(kg): "); weightField.setValue(0.0); glayout.addComponent(weightField, 2, 4); glayout.setComponentAlignment(weightField, Alignment.MIDDLE_LEFT); religionField = createTextField("Religion: "); religionField.setValue("N/A"); glayout.addComponent(religionField, 3, 4); glayout.setComponentAlignment(religionField, Alignment.MIDDLE_LEFT); spouseNameField = createTextField("Spouse Name: "); spouseNameField.setValue("N/A"); glayout.addComponent(spouseNameField, 1, 5, 2, 5); glayout.setComponentAlignment(spouseNameField, Alignment.MIDDLE_LEFT); spouseOccupationField = createTextField("Spouse Occupation: "); spouseOccupationField.setValue("N/A"); glayout.addComponent(spouseOccupationField, 3, 5); glayout.setComponentAlignment(spouseOccupationField, Alignment.MIDDLE_LEFT); spouseOfficeAddressField = createTextField("Spouse Office Address: "); spouseOfficeAddressField.setValue("N/A"); glayout.addComponent(spouseOfficeAddressField, 1, 6, 3, 6); glayout.setComponentAlignment(spouseOfficeAddressField, Alignment.MIDDLE_LEFT); fathersNameField = createTextField("Father's Name: "); fathersNameField.setValue("N/A"); glayout.addComponent(fathersNameField, 1, 7, 2, 7); glayout.setComponentAlignment(fathersNameField, Alignment.MIDDLE_LEFT); fathersOccupationField = createTextField("Father's Occupation: "); fathersOccupationField.setValue("N/A"); glayout.addComponent(fathersOccupationField, 3, 7); glayout.setComponentAlignment(fathersOccupationField, Alignment.MIDDLE_LEFT); mothersNameField = createTextField("Mother's Maiden Name: "); mothersNameField.setValue("N/A"); glayout.addComponent(mothersNameField, 1, 8, 2, 8); glayout.setComponentAlignment(mothersNameField, Alignment.MIDDLE_LEFT); mothersOccupationField = createTextField("Mother's Occupation: "); mothersOccupationField.setValue("N/A"); glayout.addComponent(mothersOccupationField, 3, 8); glayout.setComponentAlignment(mothersOccupationField, Alignment.MIDDLE_LEFT); parentsAddressField = createTextField("Parents Address"); parentsAddressField.setValue("N/A"); glayout.addComponent(parentsAddressField, 1, 9, 3, 9); glayout.setComponentAlignment(parentsAddressField, Alignment.MIDDLE_LEFT); dialectSpeakWriteField = createTextField("Language or Dialect you can speak or write: "); dialectSpeakWriteField.setValue("N/A"); glayout.addComponent(dialectSpeakWriteField, 1, 10, 3, 10); glayout.setComponentAlignment(dialectSpeakWriteField, Alignment.MIDDLE_LEFT); contactPersonNameField = createTextField("Contact Person: "); contactPersonNameField.setValue("N/A"); glayout.addComponent(contactPersonNameField, 1, 11); glayout.setComponentAlignment(contactPersonNameField, Alignment.MIDDLE_LEFT); contactPersonAddressField = createTextField("Contact Person's Address: "); contactPersonAddressField.setValue("N/A"); glayout.addComponent(contactPersonAddressField, 2, 11, 3, 11); glayout.setComponentAlignment(contactPersonAddressField, Alignment.MIDDLE_LEFT); contactPersonNoField = createTextField("Contact Person's Tel No: "); contactPersonNoField.setValue("N/A"); glayout.addComponent(contactPersonNoField, 1, 12); glayout.setComponentAlignment(contactPersonNoField, Alignment.MIDDLE_LEFT); skillsField = createTextField("Skills: "); skillsField.setValue("N/A"); glayout.addComponent(skillsField, 2, 12); glayout.setComponentAlignment(skillsField, Alignment.MIDDLE_LEFT); hobbyField = createTextField("Hobbies"); hobbyField.setValue("N/A"); glayout.addComponent(hobbyField, 3, 12); glayout.setComponentAlignment(hobbyField, Alignment.MIDDLE_LEFT); if(employeeId != null){ personalInformation = piService.getPersonalInformationData(employeeId); final byte[] image = personalInformation.getImage(); if(image != null){ StreamResource.StreamSource imageSource = new StreamResource.StreamSource(){ @Override public InputStream getStream() { return new ByteArrayInputStream(image); } }; StreamResource imageResource = new StreamResource(imageSource, personalInformation.getFirstname()+".jpg", getThisApplication()); imageResource.setCacheTime(0); avatar.setSource(imageResource); } fnField.setValue(personalInformation.getFirstname().toUpperCase()); mnField.setValue(personalInformation.getMiddlename().toUpperCase()); lnField.setValue(personalInformation.getLastname().toUpperCase()); companyIdField.setValue(employeeId); dobField.setValue(personalInformation.getDob()); pobField.setValue(personalInformation.getPob()); if(personalInformation.getCivilStatus() != null){ Object civilStatusId = civilStatusBox.addItem(); civilStatusBox.setItemCaption(civilStatusId, personalInformation.getCivilStatus()); civilStatusBox.setValue(civilStatusId); } if(personalInformation.getGender() != null){ Object genderId = genderBox.addItem(); genderBox.setItemCaption(genderId, personalInformation.getGender()); genderBox.setValue(genderId); } citizenshipField.setValue(personalInformation.getCitizenship()); heightField.setValue(personalInformation.getHeight()); weightField.setValue(personalInformation.getWeight()); religionField.setValue(personalInformation.getReligion()); spouseNameField.setValue(personalInformation.getSpouseName()); spouseOccupationField.setValue(personalInformation.getSpouseOccupation()); spouseOfficeAddressField.setValue(personalInformation.getSpouseOfficeAddress()); fathersNameField.setValue(personalInformation.getFathersName()); fathersOccupationField.setValue(personalInformation.getFathersOccupation()); mothersNameField.setValue(personalInformation.getMothersName()); mothersOccupationField.setValue(personalInformation.getMothersOccupation()); parentsAddressField.setValue(personalInformation.getParentsAddress()); dialectSpeakWriteField.setValue(personalInformation.getDialectSpeakWrite()); contactPersonNameField.setValue(personalInformation.getContactPersonName()); contactPersonAddressField.setValue(personalInformation.getContactPersonAddress()); contactPersonNoField.setValue(personalInformation.getContactPersonNo()); skillsField.setValue(personalInformation.getSkills()); hobbyField.setValue(personalInformation.getHobby()); } Button removeBtn = new Button("REMOVE EMPLOYEE"); removeBtn.setWidth("100%"); boolean visible = false; if(GlobalVariables.getUserRole()== null){ visible = false; } else if (GlobalVariables.getUserRole().equals("hr") || GlobalVariables.getUserRole().equals("administrator")){ visible = true; } removeBtn.setVisible(visible); removeBtn.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { if(!GlobalVariables.getUserRole().equals("administrator")){ getWindow().showNotification("You need to an ADMINISTRATOR to perform this ACTION.", Window.Notification.TYPE_WARNING_MESSAGE); return; } Window window = getRemoveWindow(getEmployeeId()); window.setModal(true); if(window.getParent() == null){ getWindow().addWindow(window); } window.center(); } }); glayout.addComponent(removeBtn, 1, 13); Button saveButton = new Button("UPDATE EMPLOYEE's INFORMATION"); saveButton.setWidth("100%"); saveButton.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { if(dobField.getValue() == null || dobField.getValue().toString().isEmpty()){ getWindow().showNotification("Date of Birth Required!", Window.Notification.TYPE_ERROR_MESSAGE); return; } if(heightField.getValue() == null || heightField.getValue().toString().isEmpty()){ getWindow().showNotification("Null/Empty Value for Height is not ALLOWED!", Window.Notification.TYPE_ERROR_MESSAGE); return; } else { if(!convertionUtilities.checkInputIfDouble(heightField.getValue().toString())){ getWindow().showNotification("Enter a numeric format for Height!", Window.Notification.TYPE_ERROR_MESSAGE); return; } } if(weightField.getValue() == null || weightField.getValue().toString().isEmpty()){ getWindow().showNotification("Null/Empty Value for Weight is not ALLOWED!", Window.Notification.TYPE_ERROR_MESSAGE); return; } else { if(!convertionUtilities.checkInputIfDouble(weightField.getValue().toString())){ getWindow().showNotification("Enter a numeric format for Weight!", Window.Notification.TYPE_ERROR_MESSAGE); return; } } if(genderBox.getValue() == null || genderBox.getValue().toString().isEmpty()){ getWindow().showNotification("Select a Gender!", Window.Notification.TYPE_ERROR_MESSAGE); return; } if(civilStatusBox.getValue() == null || civilStatusBox.getValue().toString().isEmpty()){ getWindow().showNotification("Select Civil Status!", Window.Notification.TYPE_ERROR_MESSAGE); return; } PersonalInformation pi = new PersonalInformation(); pi.setFirstname(fnField.getValue().toString().toLowerCase().trim()); pi.setMiddlename(mnField.getValue().toString().toLowerCase().trim()); pi.setLastname(lnField.getValue().toString().toLowerCase().trim()); pi.setEmployeeId(employeeId); pi.setDob((Date) dobField.getValue()); pi.setPob((pobField.getValue() == null) ? "N/A" : pobField.getValue().toString().toLowerCase().trim()); pi.setHeight(convertionUtilities.convertStringToDouble(heightField.getValue().toString())); pi.setWeight(convertionUtilities.convertStringToDouble(weightField.getValue().toString())); if(convertionUtilities.checkInputIfInteger(genderBox.getValue().toString())){ pi.setGender(genderBox.getItemCaption(genderBox.getValue())); } else { pi.setGender(genderBox.getValue().toString()); } if(convertionUtilities.checkInputIfInteger(civilStatusBox.getValue().toString())){ pi.setCivilStatus(civilStatusBox.getItemCaption(civilStatusBox.getValue())); } else { pi.setCivilStatus(civilStatusBox.getValue().toString()); } pi.setCitizenship((citizenshipField.getValue() == null) ? "N/A" : citizenshipField.getValue().toString()); pi.setReligion((religionField.getValue() == null)? "N/A" : religionField.getValue().toString()); pi.setSpouseName((spouseNameField.getValue() == null) ? "N/A" : spouseNameField.getValue().toString()); pi.setSpouseOccupation((spouseOccupationField.getValue() == null) ? "N/A" : spouseOccupationField.getValue().toString()); pi.setSpouseOfficeAddress((spouseOfficeAddressField.getValue() == null) ? "N/A" : spouseOfficeAddressField.getValue().toString()); pi.setFathersName((fathersNameField.getValue() == null) ? "N/A" : fathersNameField.getValue().toString()); pi.setFathersOccupation((fathersOccupationField.getValue() == null) ? "N/A" : fathersOccupationField.getValue().toString()); pi.setMothersName((mothersNameField.getValue() == null) ? "N/A" : mothersNameField.getValue().toString()); pi.setMothersOccupation((mothersOccupationField.getValue() == null) ? "N/A" : mothersOccupationField.getValue().toString()); pi.setParentsAddress((parentsAddressField.getValue() == null) ? "N/A" : parentsAddressField.getValue().toString()); pi.setDialectSpeakWrite((dialectSpeakWriteField.getValue() == null) ? "N/A" : dialectSpeakWriteField.getValue().toString()); pi.setContactPersonName((contactPersonNameField.getValue() == null) ? "N/A" : contactPersonNameField.getValue().toString()); pi.setContactPersonAddress((contactPersonAddressField.getValue() == null) ? "N/A" : contactPersonAddressField.getValue().toString()); pi.setContactPersonNo((contactPersonNoField.getValue() == null) ? "N/A" : contactPersonNoField.getValue().toString()); pi.setSkills((skillsField.getValue() == null) ? "N/A" : skillsField.getValue().toString()); pi.setHobby((hobbyField.getValue() == null) ? "N/A" : hobbyField.getValue().toString()); pi.setEmployeeId(getEmployeeId()); // boolean result = piService.updatePersonalInformation(pi, "UPDATE PERSONAL INFORMATION"); Window window = updatePersonalInformationConfirmation(pi); window.setModal(true); if(window.getParent() == null){ getWindow().addWindow(window); } window.center(); // if(result){ // getWindow().showNotification("Information Updated", Window.Notification.TYPE_TRAY_NOTIFICATION); // } else { // getWindow().showNotification("SQL Error", Window.Notification.TYPE_ERROR_MESSAGE); // } } }); if(GlobalVariables.getUserRole().equals("administrator") || GlobalVariables.getUserRole().equals("hr")){ saveButton.setEnabled(true); } else { saveButton.setEnabled(false); } glayout.addComponent(saveButton, 2, 13, 3, 13); glayout.setColumnExpandRatio(1, .10f); glayout.setColumnExpandRatio(2, .10f); glayout.setColumnExpandRatio(3, .10f); return glayout; } private Window getRemoveWindow(String employeeId){ VerticalLayout vlayout = new VerticalLayout(); vlayout.setSpacing(true); vlayout.setMargin(true); final Window window = new Window("REMOVE EMPLOYEE", vlayout); window.setWidth("350px"); Button removeBtn = new Button("Are you sure your want to remove this Employee?"); removeBtn.setWidth("100%"); removeBtn.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { EmployeeMainUI employeeMainUI = new EmployeeMainUI(GlobalVariables.getUserRole(), 0); boolean result = employeeCurrentStatusService.removeEmployee(getEmployeeId()); if(result){ clearFields(); employeeMainUI.employeesTable(getEmployeeList(0)); (window.getParent()).removeWindow(window); } else { getWindow().showNotification("Cannot Remove Employee, Contact your DBA!", Window.Notification.TYPE_ERROR_MESSAGE); } } }); window.addComponent(removeBtn); return window; } private Window updatePersonalInformationConfirmation(final PersonalInformation pi){ VerticalLayout vlayout = new VerticalLayout(); vlayout.setSpacing(true); vlayout.setMargin(true); final Window window = new Window("UPDATE WINDOW", vlayout); window.setWidth("350px"); final TextArea remarks = new TextArea("Remarks"); remarks.setWidth("100%"); remarks.setRows(3); window.addComponent(remarks); Button removeBtn = new Button("UPDATE EMPLOYEE?"); removeBtn.setWidth("100%"); removeBtn.addListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { if(remarks.getValue() == null || remarks.getValue().toString().trim().isEmpty()){ getWindow().showNotification("Add remarks!", Window.Notification.TYPE_ERROR_MESSAGE); return; } boolean result = piService.updatePersonalInformation(pi, remarks.getValue().toString().trim()); if(result){ getWindow().showNotification("Information Updated", Window.Notification.TYPE_TRAY_NOTIFICATION); (window.getParent()).removeWindow(window); } else { getWindow().showNotification("SQL Error", Window.Notification.TYPE_ERROR_MESSAGE); } } }); window.addComponent(removeBtn); return window; } public String getEmployeeId(){ return employeeId; } private TextField createTextField(String str){ TextField t = new TextField(); t.setCaption(str); t.setWidth("100%"); t.setStyleName(Reindeer.TEXTFIELD_SMALL); t.setNullSettingAllowed(true); return t; } public List<Employee> getEmployeeList(int branchId){ return employeeService.getEmployeePerBranch(branchId); } public Application getThisApplication(){ return application; } public void clearFields(){ fnField.setValue(""); mnField.setValue(""); lnField.setValue(""); companyIdField.setValue(""); dobField.setValue(new Date()); pobField.setValue(""); genderBox.removeAllItems(); genderBox = dropDownComponent.populateGenderList(genderBox); civilStatusBox.removeAllItems(); civilStatusBox = dropDownComponent.populateCivilStatusList(civilStatusBox); citizenshipField.setValue(""); heightField.setValue(""); weightField.setValue(""); religionField.setValue(""); spouseNameField.setValue(""); spouseOccupationField.setValue(""); spouseOfficeAddressField.setValue(""); fathersNameField.setValue(""); fathersOccupationField.setValue(""); mothersNameField.setValue(""); mothersOccupationField.setValue(""); parentsAddressField.setValue(""); dialectSpeakWriteField.setValue(""); contactPersonNameField.setValue(""); contactPersonAddressField.setValue(""); contactPersonNoField.setValue(""); skillsField.setValue(""); hobbyField.setValue(""); } }
apache-2.0
KAMP-Research/KAMP4APS
edu.kit.ipd.sdq.kamp4aps.aps.tests/src/edu/kit/ipd/sdq/kamp4aps/model/aPS/MechanicalComponents/tests/GripperPartTest.java
1717
/** */ package edu.kit.ipd.sdq.kamp4aps.model.aPS.MechanicalComponents.tests; import edu.kit.ipd.sdq.kamp4aps.model.aPS.ComponentRepository.tests.MechanicalAssemblyTest; import edu.kit.ipd.sdq.kamp4aps.model.aPS.MechanicalComponents.GripperPart; import edu.kit.ipd.sdq.kamp4aps.model.aPS.MechanicalComponents.MechanicalComponentsFactory; import junit.textui.TestRunner; /** * <!-- begin-user-doc --> * A test case for the model object '<em><b>Gripper Part</b></em>'. * <!-- end-user-doc --> * @generated */ public class GripperPartTest extends MechanicalAssemblyTest { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static void main(String[] args) { TestRunner.run(GripperPartTest.class); } /** * Constructs a new Gripper Part test case with the given name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public GripperPartTest(String name) { super(name); } /** * Returns the fixture for this Gripper Part test case. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected GripperPart getFixture() { return (GripperPart)fixture; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#setUp() * @generated */ @Override protected void setUp() throws Exception { setFixture(MechanicalComponentsFactory.eINSTANCE.createGripperPart()); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see junit.framework.TestCase#tearDown() * @generated */ @Override protected void tearDown() throws Exception { setFixture(null); } } //GripperPartTest
apache-2.0
copper-engine/copper-engine
projects/copper-coreengine/src/main/java/org/copperengine/core/audit/BatchingAuditTrail.java
7381
/* * Copyright 2002-2015 SCOOP Software GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.copperengine.core.audit; import java.util.Date; import org.copperengine.core.Acknowledge; import org.copperengine.core.batcher.Batcher; import org.copperengine.core.batcher.CommandCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Fast db based audit trail implementation. It is possible to extend the COPPER audit trail with custom attributes. * See JUnitTest {@code BatchingAuditTrailTest.testCustomTable()} for an example. * * @author austermann */ public class BatchingAuditTrail extends AbstractAuditTrail { private static final Logger logger = LoggerFactory.getLogger(BatchingAuditTrail.class); private Batcher batcher; /** * returns immediately after queueing the log message * * @param logLevel * the level on that the audit trail event is recorded (might be used for filtering) * @param occurrence * timestamp of the audit trail event * @param conversationId * conversation id embraces all audit trail events for one business process (might be the same for a * whole business transaction over a range of involved systems) * @param context * the context of the audit trail event (e.g. a camel route, a workflow task, ...) * @param instanceId * workflow id for a single workflow * @param correlationId * correlates a request response pair (e.g. workflow calls another workflow, workflow calls a camel * route, ...) * @param transactionId * Same ID vor several conversations, that belongs to the same transaction. Example: ExecuteOrder * (conversation 1), ChangeOrder (conversation 2) and CancelOrder (conversation 3) that all belongs to * transaction 77. When transaction 77 can be deleted, all conversations for this transaction can be * deleted. * @param _message * a message describing the audit trail event * @param messageType * type of the message, e.g. XML, used for message rendering in the COPPER monitor */ public void asynchLog(int logLevel, Date occurrence, String conversationId, String context, String instanceId, String correlationId, String transactionId, String _message, String messageType) { this.asynchLog(new AuditTrailEvent(logLevel, occurrence, conversationId, context, instanceId, correlationId, transactionId, _message, messageType, null)); } /** * returns immediately after queueing the log message * * @param logLevel * the level on that the audit trail event is recorded (might be used for filtering) * @param occurrence * timestamp of the audit trail event * @param conversationId * conversation id embraces all audit trail events for one business process (might be the same for a * whole business transaction over a range of involved systems) * @param context * the context of the audit trail event (e.g. a camel route, a workflow task, ...) * @param instanceId * workflow id for a single workflow * @param correlationId * correlates a request response pair (e.g. workflow calls another workflow, workflow calls a camel * route, ...) * @param transactionId * Same ID vor several conversations, that belongs to the same transaction. Example: ExecuteOrder * (conversation 1), ChangeOrder (conversation 2) and CancelOrder (conversation 3) that all belongs to * transaction 77. When transaction 77 can be deleted, all conversations for this transaction can be * deleted. * @param _message * a message describing the audit trail event * @param messageType * type of the message, e.g. XML, used for message rendering in the COPPER monitor * @param cb * callback called when logging succeeded or failed. */ public void asynchLog(int logLevel, Date occurrence, String conversationId, String context, String instanceId, String correlationId, String transactionId, String _message, String messageType, final AuditTrailCallback cb) { this.asynchLog(new AuditTrailEvent(logLevel, occurrence, conversationId, context, instanceId, correlationId, transactionId, _message, messageType, null), cb); } /** * returns immediately after queueing the log message * @param e * the AuditTrailEvent to be logged */ public void asynchLog(AuditTrailEvent e) { doLog(e, new Acknowledge.BestEffortAcknowledge(), false); } /** * returns immediately after queueing the log message * @param e * the AuditTrailEvent to be logged * @param cb * callback called when logging succeeded or failed. */ public void asynchLog(final AuditTrailEvent e, final AuditTrailCallback cb) { CommandCallback<BatchInsertIntoAutoTrail.Command> callback = new CommandCallback<BatchInsertIntoAutoTrail.Command>() { @Override public void commandCompleted() { cb.done(); } @Override public void unhandledException(Exception e) { cb.error(e); } }; doLog(e, false, callback); } protected boolean doLog(AuditTrailEvent e, final Acknowledge ack, boolean immediate) { CommandCallback<BatchInsertIntoAutoTrail.Command> callback = new CommandCallback<BatchInsertIntoAutoTrail.Command>() { @Override public void commandCompleted() { ack.onSuccess(); } @Override public void unhandledException(Exception e) { ack.onException(e); } }; return doLog(e, immediate, callback); } protected boolean doLog(AuditTrailEvent e, boolean immediate, CommandCallback<BatchInsertIntoAutoTrail.Command> callback) { if (isEnabled(e.logLevel)) { logger.debug("doLog({})", e); e.setMessage(messagePostProcessor.serialize(e.message)); batcher.submitBatchCommand(createBatchCommand(e, immediate, callback)); return true; } return false; } @Override public void synchLog(final AuditTrailEvent event) { Acknowledge.DefaultAcknowledge ack = new Acknowledge.DefaultAcknowledge(); if (doLog(event, ack, true)) { ack.waitForAcknowledge(); } } public void setBatcher(Batcher batcher) { this.batcher = batcher; } }
apache-2.0
dreajay/jCodes
jCodes-ganymed-ssh2/src/main/java/com/jcodes/ganymed/SimpleVerifier.java
1428
package com.jcodes.ganymed; import ch.ethz.ssh2.KnownHosts; import ch.ethz.ssh2.ServerHostKeyVerifier; class SimpleVerifier implements ServerHostKeyVerifier { KnownHosts database; /* * This class is being used by the UsingKnownHosts.java example. */ public SimpleVerifier(KnownHosts database) { if (database == null) throw new IllegalArgumentException(); this.database = database; } public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception { int result = database.verifyHostkey(hostname, serverHostKeyAlgorithm, serverHostKey); switch (result) { case KnownHosts.HOSTKEY_IS_OK: return true; // We are happy case KnownHosts.HOSTKEY_IS_NEW: // Unknown host? Blindly accept the key and put it into the cache. // Well, you definitely can do better (e.g., ask the user). // The following call will ONLY put the key into the memory cache! // To save it in a known hosts file, also call "KnownHosts.addHostkeyToFile(...)" database.addHostkey(new String[] { hostname }, serverHostKeyAlgorithm, serverHostKey); return true; case KnownHosts.HOSTKEY_HAS_CHANGED: // Close the connection if the hostkey has changed. // Better: ask user and add new key to database. return false; default: throw new IllegalStateException(); } } }
apache-2.0
klon/jtrade
src/main/java/com/ib/client/ScannerSubscription.java
4097
/* Copyright (C) 2013 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ package com.ib.client; public class ScannerSubscription { public final static int NO_ROW_NUMBER_SPECIFIED = -1; private int m_numberOfRows = NO_ROW_NUMBER_SPECIFIED; private String m_instrument; private String m_locationCode; private String m_scanCode; private double m_abovePrice = Double.MAX_VALUE; private double m_belowPrice = Double.MAX_VALUE; private int m_aboveVolume = Integer.MAX_VALUE; private int m_averageOptionVolumeAbove = Integer.MAX_VALUE; private double m_marketCapAbove = Double.MAX_VALUE; private double m_marketCapBelow = Double.MAX_VALUE; private String m_moodyRatingAbove; private String m_moodyRatingBelow; private String m_spRatingAbove; private String m_spRatingBelow; private String m_maturityDateAbove; private String m_maturityDateBelow; private double m_couponRateAbove = Double.MAX_VALUE; private double m_couponRateBelow = Double.MAX_VALUE; private String m_excludeConvertible; private String m_scannerSettingPairs; private String m_stockTypeFilter; // Get public int numberOfRows() { return m_numberOfRows; } public String instrument() { return m_instrument; } public String locationCode() { return m_locationCode; } public String scanCode() { return m_scanCode; } public double abovePrice() { return m_abovePrice; } public double belowPrice() { return m_belowPrice; } public int aboveVolume() { return m_aboveVolume; } public int averageOptionVolumeAbove() { return m_averageOptionVolumeAbove; } public double marketCapAbove() { return m_marketCapAbove; } public double marketCapBelow() { return m_marketCapBelow; } public String moodyRatingAbove() { return m_moodyRatingAbove; } public String moodyRatingBelow() { return m_moodyRatingBelow; } public String spRatingAbove() { return m_spRatingAbove; } public String spRatingBelow() { return m_spRatingBelow; } public String maturityDateAbove() { return m_maturityDateAbove; } public String maturityDateBelow() { return m_maturityDateBelow; } public double couponRateAbove() { return m_couponRateAbove; } public double couponRateBelow() { return m_couponRateBelow; } public String excludeConvertible() { return m_excludeConvertible; } public String scannerSettingPairs() { return m_scannerSettingPairs; } public String stockTypeFilter() { return m_stockTypeFilter; } // Set public void numberOfRows(int num) { m_numberOfRows = num; } public void instrument(String txt) { m_instrument = txt; } public void locationCode(String txt) { m_locationCode = txt; } public void scanCode(String txt) { m_scanCode = txt; } public void abovePrice(double price) { m_abovePrice = price; } public void belowPrice(double price) { m_belowPrice = price; } public void aboveVolume(int volume) { m_aboveVolume = volume; } public void averageOptionVolumeAbove(int volume) { m_averageOptionVolumeAbove = volume; } public void marketCapAbove(double cap) { m_marketCapAbove = cap; } public void marketCapBelow(double cap) { m_marketCapBelow = cap; } public void moodyRatingAbove(String r) { m_moodyRatingAbove = r; } public void moodyRatingBelow(String r) { m_moodyRatingBelow = r; } public void spRatingAbove(String r) { m_spRatingAbove = r; } public void spRatingBelow(String r) { m_spRatingBelow = r; } public void maturityDateAbove(String d) { m_maturityDateAbove = d; } public void maturityDateBelow(String d) { m_maturityDateBelow = d; } public void couponRateAbove(double r) { m_couponRateAbove = r; } public void couponRateBelow(double r) { m_couponRateBelow = r; } public void excludeConvertible(String c) { m_excludeConvertible = c; } public void scannerSettingPairs(String val) { m_scannerSettingPairs = val; } public void stockTypeFilter(String val) { m_stockTypeFilter = val; } }
apache-2.0
wilkinsona/spring-social-facebook
spring-social-facebook/src/main/java/org/springframework/social/facebook/api/impl/json/EducationEntryMixin.java
1370
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.facebook.api.impl.json; import java.util.List; import org.springframework.social.facebook.api.Reference; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Annotated mixin to add Jackson annotations to EducationEntry. * @author Craig Walls */ @JsonIgnoreProperties(ignoreUnknown = true) abstract class EducationEntryMixin extends FacebookObjectMixin { @JsonCreator EducationEntryMixin( @JsonProperty("school") Reference school, @JsonProperty("year") Reference year, @JsonProperty("concentration") List<Reference> concentration, @JsonProperty("type") String type) {} }
apache-2.0
stari4ek/ExoPlayer
library/ui/src/main/java/com/google/android/exoplayer2/ui/TrackSelectionDialogBuilder.java
9338
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.ui; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector; import com.google.android.exoplayer2.trackselection.DefaultTrackSelector.SelectionOverride; import com.google.android.exoplayer2.trackselection.MappingTrackSelector.MappedTrackInfo; import com.google.android.exoplayer2.trackselection.TrackSelectionUtil; import com.google.android.exoplayer2.util.Assertions; import java.util.Collections; import java.util.List; /** Builder for a dialog with a {@link TrackSelectionView}. */ public final class TrackSelectionDialogBuilder { /** Callback which is invoked when a track selection has been made. */ public interface DialogCallback { /** * Called when tracks are selected. * * @param isDisabled Whether the renderer is disabled. * @param overrides List of selected track selection overrides for the renderer. */ void onTracksSelected(boolean isDisabled, List<SelectionOverride> overrides); } private final Context context; private final CharSequence title; private final MappedTrackInfo mappedTrackInfo; private final int rendererIndex; private final DialogCallback callback; private boolean allowAdaptiveSelections; private boolean allowMultipleOverrides; private boolean showDisableOption; @Nullable private TrackNameProvider trackNameProvider; private boolean isDisabled; private List<SelectionOverride> overrides; /** * Creates a builder for a track selection dialog. * * @param context The context of the dialog. * @param title The title of the dialog. * @param mappedTrackInfo The {@link MappedTrackInfo} containing the track information. * @param rendererIndex The renderer index in the {@code mappedTrackInfo} for which the track * selection is shown. * @param callback The {@link DialogCallback} invoked when a track selection has been made. */ public TrackSelectionDialogBuilder( Context context, CharSequence title, MappedTrackInfo mappedTrackInfo, int rendererIndex, DialogCallback callback) { this.context = context; this.title = title; this.mappedTrackInfo = mappedTrackInfo; this.rendererIndex = rendererIndex; this.callback = callback; overrides = Collections.emptyList(); } /** * Creates a builder for a track selection dialog which automatically updates a {@link * DefaultTrackSelector}. * * @param context The context of the dialog. * @param title The title of the dialog. * @param trackSelector A {@link DefaultTrackSelector} whose current selection is used to set up * the dialog and which is updated when new tracks are selected in the dialog. * @param rendererIndex The renderer index in the {@code trackSelector} for which the track * selection is shown. */ public TrackSelectionDialogBuilder( Context context, CharSequence title, DefaultTrackSelector trackSelector, int rendererIndex) { this.context = context; this.title = title; this.mappedTrackInfo = Assertions.checkNotNull(trackSelector.getCurrentMappedTrackInfo()); this.rendererIndex = rendererIndex; TrackGroupArray rendererTrackGroups = mappedTrackInfo.getTrackGroups(rendererIndex); DefaultTrackSelector.Parameters selectionParameters = trackSelector.getParameters(); isDisabled = selectionParameters.getRendererDisabled(rendererIndex); SelectionOverride override = selectionParameters.getSelectionOverride(rendererIndex, rendererTrackGroups); overrides = override == null ? Collections.emptyList() : Collections.singletonList(override); this.callback = (newIsDisabled, newOverrides) -> trackSelector.setParameters( TrackSelectionUtil.updateParametersWithOverride( selectionParameters, rendererIndex, rendererTrackGroups, newIsDisabled, newOverrides.isEmpty() ? null : newOverrides.get(0))); } /** * Sets whether the selection is initially shown as disabled. * * @param isDisabled Whether the selection is initially shown as disabled. * @return This builder, for convenience. */ public TrackSelectionDialogBuilder setIsDisabled(boolean isDisabled) { this.isDisabled = isDisabled; return this; } /** * Sets the initial selection override to show. * * @param override The initial override to show, or null for no override. * @return This builder, for convenience. */ public TrackSelectionDialogBuilder setOverride(@Nullable SelectionOverride override) { return setOverrides( override == null ? Collections.emptyList() : Collections.singletonList(override)); } /** * Sets the list of initial selection overrides to show. * * <p>Note that only the first override will be used unless {@link * #setAllowMultipleOverrides(boolean)} is set to {@code true}. * * @param overrides The list of initial overrides to show. There must be at most one override for * each track group. * @return This builder, for convenience. */ public TrackSelectionDialogBuilder setOverrides(List<SelectionOverride> overrides) { this.overrides = overrides; return this; } /** * Sets whether adaptive selections (consisting of more than one track) can be made. * * <p>For the selection view to enable adaptive selection it is necessary both for this feature to * be enabled, and for the target renderer to support adaptation between the available tracks. * * @param allowAdaptiveSelections Whether adaptive selection is enabled. * @return This builder, for convenience. */ public TrackSelectionDialogBuilder setAllowAdaptiveSelections(boolean allowAdaptiveSelections) { this.allowAdaptiveSelections = allowAdaptiveSelections; return this; } /** * Sets whether multiple overrides can be set and selected, i.e. tracks from multiple track groups * can be selected. * * @param allowMultipleOverrides Whether multiple track selection overrides are allowed. * @return This builder, for convenience. */ public TrackSelectionDialogBuilder setAllowMultipleOverrides(boolean allowMultipleOverrides) { this.allowMultipleOverrides = allowMultipleOverrides; return this; } /** * Sets whether an option is available for disabling the renderer. * * @param showDisableOption Whether the disable option is shown. * @return This builder, for convenience. */ public TrackSelectionDialogBuilder setShowDisableOption(boolean showDisableOption) { this.showDisableOption = showDisableOption; return this; } /** * Sets the {@link TrackNameProvider} used to generate the user visible name of each track and * updates the view with track names queried from the specified provider. * * @param trackNameProvider The {@link TrackNameProvider} to use, or null to use the default. */ public TrackSelectionDialogBuilder setTrackNameProvider( @Nullable TrackNameProvider trackNameProvider) { this.trackNameProvider = trackNameProvider; return this; } /** Builds the dialog. */ public AlertDialog build() { AlertDialog.Builder builder = new AlertDialog.Builder(context); // Inflate with the builder's context to ensure the correct style is used. LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext()); View dialogView = dialogInflater.inflate(R.layout.exo_track_selection_dialog, /* root= */ null); TrackSelectionView selectionView = dialogView.findViewById(R.id.exo_track_selection_view); selectionView.setAllowMultipleOverrides(allowMultipleOverrides); selectionView.setAllowAdaptiveSelections(allowAdaptiveSelections); selectionView.setShowDisableOption(showDisableOption); if (trackNameProvider != null) { selectionView.setTrackNameProvider(trackNameProvider); } selectionView.init(mappedTrackInfo, rendererIndex, isDisabled, overrides, /* listener= */ null); Dialog.OnClickListener okClickListener = (dialog, which) -> callback.onTracksSelected(selectionView.getIsDisabled(), selectionView.getOverrides()); return builder .setTitle(title) .setView(dialogView) .setPositiveButton(android.R.string.ok, okClickListener) .setNegativeButton(android.R.string.cancel, null) .create(); } }
apache-2.0
XDean/Java-EX
src/main/java/cn/xdean/jex/reflect/FunctionInterfaceUtil.java
11124
package cn.xdean.jex.reflect; import xdean.jex.log.Log; import xdean.jex.log.LogFactory; import java.lang.invoke.MethodHandles; import java.lang.reflect.*; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Stream; public class FunctionInterfaceUtil { private static final Log LOG = LogFactory.from(FunctionInterfaceUtil.class); /** * Get the method from a function interface * * @param clz * @return null if the given class is not a function interface */ public static <T> Method getFunctionInterfaceMethod(Class<?> clz) { if (!clz.isInterface()) { return null; } Method[] ms = Stream.of(clz.getMethods()) .filter(m -> !(m.isDefault() || m.isBridge() || m.isSynthetic() || Modifier.isStatic(m.getModifiers()))) .toArray(Method[]::new); if (ms.length != 1) { return null; } return ms[0]; } /** * Adapt a method to a function interface.<br> * For example: * * <pre> * <code> * static int increment(int i){ * return i+1; * } * Method m = ... * UnaryOperator&#60;Integer&#62; uo = methodToFunctionInterface(m, null, UnaryOperator.class);//work * UnaryOperator&#60;Integer&#62; uo = methodToFunctionInterface(m, null, UnaryOperator.class, Integer.class);//work and more safe * UnaryOperator&#60;Integer&#62; uo = methodToFunctionInterface(m, null, UnaryOperator.class, String.class);//return null * </code> * </pre> * * Note that only indeed adapted method can be converted. <br> * For example: {@code Integer function(Number)} can't adapt to {@code UnaryOperator<Integer>}, though any call to a * {@code UnaryOperator<Integer>} can delegate by the function. Because you can't define like: * * <pre> * <code> * interface Function extends UnaryOperator&#60;Integer&#62; { * &#64;Override * public Integer apply(Number t);//error * } * </code> * </pre> * * Now only ignored things is ParameterizedType. That means this method consider return type and parameter types as * raw type. * * @param method The method to adapt. Ensure the method can be access. * @param target The method's target. If the method is static, target should be null. * @param functionInterfaceClass The function interface to adapt to. * @param explicitGenericTypes If the function interface has generic type, you can specify them in order. If a * explicit type is null, it will be ignored. * @return Instance of the function interface. Or null if can't adapt to. Note that returned object is raw type. If * you don't specify explicit generic types, IllegalArgumentException(type mismatch) may happen when you call * it. */ @SuppressWarnings("unchecked") public static <T> T methodToFunctionInterface(Method method, Object target, Class<T> functionInterfaceClass, Class<?>... explicitGenericTypes) { Method functionMethod = getFunctionInterfaceMethod(functionInterfaceClass); if (functionMethod == null) { return null; } if (functionMethod.getParameterCount() != method.getParameterCount()) { return null; } // Map the explicit type Map<TypeVariable<?>, Class<?>> explicitTypeMap = new HashMap<>(); TypeVariable<Class<T>>[] typeParameters = functionInterfaceClass.getTypeParameters(); if (explicitGenericTypes.length > typeParameters.length) { throw new IllegalArgumentException("The explicit generic types are too many. Expect " + typeParameters.length); } for (int i = 0; i < explicitGenericTypes.length; i++) { explicitTypeMap.put(typeParameters[i], PrimitiveTypeUtil.toWrapper(explicitGenericTypes[i])); } // Map the generic reference Map<TypeVariable<?>, Type> typeVariableReference = GenericUtil.getGenericReferenceMap(functionInterfaceClass); Function<TypeVariable<?>, Class<?>> getActualTypeVariable = tv -> { Type next; while (true) { next = typeVariableReference.get(tv); if (next == null) { return explicitTypeMap.get(tv); } if (next instanceof Class<?>) { return (Class<?>) next; } tv = (TypeVariable<?>) next; } }; // Resolve return type Class<?> returnType = PrimitiveTypeUtil.toWrapper(method.getReturnType()); Type functionGenericReturnType = functionMethod.getGenericReturnType(); if (functionGenericReturnType instanceof ParameterizedType) { // TODO handle and match ParameterizedType functionGenericReturnType = ((ParameterizedType) functionGenericReturnType).getRawType(); } if (returnType == void.class && functionGenericReturnType == void.class) { } else if (functionGenericReturnType instanceof Class) { if (!PrimitiveTypeUtil.toWrapper((Class<?>) functionGenericReturnType).isAssignableFrom(returnType)) { return null; } } else if (functionGenericReturnType instanceof TypeVariable) { TypeVariable<?> tv = (TypeVariable<?>) functionGenericReturnType; Class<?> explicitType = getActualTypeVariable.apply(tv); if (explicitType != null) { if (!explicitType.equals(returnType)) { return null; } } else if (FunctionInterfaceUtil.matchTypeBounds(returnType, tv)) { explicitTypeMap.put(tv, returnType); } else { return null; } } else { LOG.warn().log("Can't handle GenericReturnType: {} with type {}", functionGenericReturnType, functionGenericReturnType.getClass()); return null; } // Resolve parameters Type[] functionParams = functionMethod.getGenericParameterTypes(); Class<?>[] params = method.getParameterTypes(); for (int i = 0; i < params.length; i++) { Type functionParamType = functionParams[i]; Class<?> paramType = PrimitiveTypeUtil.toWrapper(params[i]); if (functionParamType instanceof ParameterizedType) { // TODO handle and match ParameterizedType functionParamType = ((ParameterizedType) functionParamType).getRawType(); } if (functionParamType instanceof Class) { if (!paramType.isAssignableFrom( PrimitiveTypeUtil.toWrapper((Class<?>) functionParamType))) { return null; } } else if (functionParamType instanceof TypeVariable) { TypeVariable<?> tv = (TypeVariable<?>) functionParamType; Class<?> explicitType = getActualTypeVariable.apply(tv); if (explicitType != null) { if (!explicitType.equals(paramType)) { return null; } } else if (FunctionInterfaceUtil.matchTypeBounds(paramType, tv)) { explicitTypeMap.put(tv, paramType); } else { return null; } } else { LOG.warn().log("Can't handle GenericParameterType: {} with type {}", paramType, paramType.getClass()); return null; } } // Resolve throws List<Type> functionExceptionTypes = Arrays.asList(functionMethod.getGenericExceptionTypes()); for (Class<?> exceptionType : method.getExceptionTypes()) { if (Exception.class.isAssignableFrom(exceptionType) && !RuntimeException.class.isAssignableFrom(exceptionType) && !functionExceptionTypes.stream().anyMatch( functionThrowType -> { Class<?> functionThrowClass = null; if (functionThrowType instanceof Class) { functionThrowClass = (Class<?>) functionThrowType; } else if (functionThrowType instanceof TypeVariable) { Class<?> explicitType = explicitTypeMap.get(functionThrowType); if (explicitType == null) { return FunctionInterfaceUtil.matchTypeBounds(exceptionType, (TypeVariable<?>) functionThrowType); } else { functionThrowClass = explicitType; } } else { LOG.warn().log("Can't handle GenericException: {} with type {}", functionThrowType, functionThrowType.getClass()); return false; } return functionThrowClass.isAssignableFrom(exceptionType); })) { return null; } } return (T) Proxy.newProxyInstance( functionInterfaceClass.getClassLoader(), new Class[] { functionInterfaceClass }, (obj, m, args) -> { if (m.equals(functionMethod)) { return method.invoke(target, args); } Class<?> declaringClass = m.getDeclaringClass(); if (m.isDefault() || declaringClass.equals(Object.class)) { Object result; Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor( Class.class, int.class); constructor.setAccessible(true); result = constructor .newInstance(declaringClass, MethodHandles.Lookup.PRIVATE) .unreflectSpecial(m, declaringClass) .bindTo(obj) .invokeWithArguments(args); return (result); } return m.invoke(obj, args); }); } private static boolean matchTypeBounds(Class<?> clz, TypeVariable<?> tv) { Class<?> wrapClz = PrimitiveTypeUtil.toWrapper(clz); return FunctionInterfaceUtil.getAllBounds(tv).allMatch( c -> PrimitiveTypeUtil.toWrapper(c).isAssignableFrom(wrapClz)); } private static Stream<Class<?>> getAllBounds(TypeVariable<?> tv) { return Stream.of(tv.getBounds()) .flatMap(t -> { if (t instanceof Class) { return Stream.of((Class<?>) t); } else if (t instanceof TypeVariable) { return getAllBounds(((TypeVariable<?>) t)); } else { LOG.warn().log("Can't handle TypeVariable Bound: {} with type {}", t, t.getClass()); return Stream.empty(); } }); } // private static Map<TypeVariable<?>, Type> getTypeVariableReference(Class<?> clz) { // HashMap<TypeVariable<?>, Type> map = new HashMap<>(); // if (clz.getSuperclass() != null) { // map.putAll(getTypeVariableReference(clz.getSuperclass())); // } // Arrays.asList(clz.getInterfaces()).forEach(c -> map.putAll(getTypeVariableReference(c))); // Stream.concat(Stream.of(clz.getGenericSuperclass()), Stream.of(clz.getGenericInterfaces())) // .filter(not(null)) // .forEach(c -> { // if (c instanceof Class) { // } else if (c instanceof ParameterizedType) { // Type[] actualTypeArguments = ((ParameterizedType) c).getActualTypeArguments(); // TypeVariable<?>[] implTypeParams = ((Class<?>) ((ParameterizedType) c).getRawType()) // .getTypeParameters(); // for (int i = 0; i < actualTypeArguments.length; i++) { // map.put(implTypeParams[i], actualTypeArguments[i]); // } // } else { // log.warn("Unknown Generic Type: {} with type {}", c, c.getClass()); // } // }); // return map; // } }
apache-2.0
TremoloSecurity/OpenUnison
unison/unison-auth-u2f/src/main/java/com/google/u2f/key/UserPresenceVerifier.java
1144
/******************************************************************************* * Copyright 2018 Tremolo Security, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ // Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd package com.google.u2f.key; public interface UserPresenceVerifier { public static final byte USER_PRESENT_FLAG = (byte) 0x01; byte verifyUserPresence(); }
apache-2.0
mrdon/AMPS
plugin-module-codegen-engine/src/test/java/com/atlassian/plugins/codegen/modules/common/servlet/ServletContextParameterTest.java
1286
package com.atlassian.plugins.codegen.modules.common.servlet; import java.io.IOException; import com.atlassian.plugins.codegen.AbstractCodegenTestCase; import com.atlassian.plugins.codegen.modules.PluginModuleLocation; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertTrue; //TODO: update test to use Dom4J /** * @since 3.6 */ public class ServletContextParameterTest extends AbstractCodegenTestCase<ServletContextParameterProperties> { @Before public void runGenerator() throws Exception { setCreator(new ServletContextParameterModuleCreator()); setModuleLocation(new PluginModuleLocation.Builder(srcDir) .resourcesDirectory(resourcesDir) .testDirectory(testDir) .templateDirectory(templateDir) .build()); setProps(new ServletContextParameterProperties("MY Param Name")); creator.createModule(moduleLocation, props); } @Test public void pluginXmlContainsModule() throws IOException { String pluginXmlContent = FileUtils.readFileToString(pluginXml); assertTrue("module not found in plugin xml", pluginXmlContent.contains("<servlet-context-param")); } }
apache-2.0
bwittman/shadow
src/test/java/shadow/test/typecheck/WarningTests.java
2314
package shadow.test.typecheck; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import shadow.Main; import shadow.typecheck.TypeCheckException; import shadow.typecheck.TypeCheckException.Error; import java.util.ArrayList; public class WarningTests { private final ArrayList<String> args = new ArrayList<>(); @BeforeEach public void setup() throws Exception { // args.add("-v"); args.add("--typecheck"); args.add("-w"); args.add("error"); String os = System.getProperty("os.name").toLowerCase(); args.add("-c"); if (os.contains("windows")) args.add("windows.json"); else if (os.contains("mac")) args.add("mac.json"); else args.add("linux.json"); } private void enforce(Error type) throws Exception { try { Main.run(args.toArray(new String[] {})); throw new Exception("Test failed"); } catch (TypeCheckException e) { if (!e.getError().equals(type)) throw new Exception("Test failed"); } } @Test public void testFieldNotUsed() throws Exception { args.add("tests-negative/warnings/field-not-used/Test.shadow"); enforce(Error.UNUSED_FIELD); } @Test public void testPrivateMethodNotUsed() throws Exception { args.add("tests-negative/warnings/private-method-not-used/Test.shadow"); enforce(Error.UNUSED_METHOD); } @Test public void testVariableNotUsed() throws Exception { args.add("tests-negative/warnings/variable-not-used/Test.shadow"); enforce(Error.UNUSED_VARIABLE); } @Test public void testImportNotUsed() throws Exception { args.add("tests-negative/warnings/import-not-used/Test.shadow"); enforce(Error.UNUSED_IMPORT); } @Test public void testNoImportsUsedFromDirectory() throws Exception { args.add("tests-negative/warnings/no-imports-used-from-directory/Test.shadow"); enforce(Error.UNUSED_IMPORT); } @Test public void testSomeImportsUsedFromDirectory() throws Exception { args.add("tests-negative/warnings/some-imports-used-from-directory/Test.shadow"); Main.run(args.toArray(new String[] {})); } @Test public void testImportsFromDirectoryCollide() throws Exception { args.add("tests-negative/warnings/imports-from-directory-collide/testing/Test.shadow"); enforce(Error.IMPORT_COLLIDES); } }
apache-2.0
SammysHP/cgeo
main/src/cgeo/geocaching/files/AbstractImportThread.java
4402
package cgeo.geocaching.files; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.StaticMapsProvider; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.Log; import android.os.Handler; import java.io.IOException; import java.util.Collection; import java.util.concurrent.CancellationException; abstract class AbstractImportThread extends Thread { final int listId; final Handler importStepHandler; final CancellableHandler progressHandler; protected AbstractImportThread(final int listId, final Handler importStepHandler, final CancellableHandler progressHandler) { this.listId = listId; this.importStepHandler = importStepHandler; this.progressHandler = progressHandler; } @Override public void run() { try { importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_START)); final Collection<Geocache> caches = doImport(); Log.i("Imported successfully " + caches.size() + " caches."); final SearchResult search = new SearchResult(caches); // Do not put imported caches into the cachecache. That would consume lots of memory for no benefit. if (Settings.isStoreOfflineMaps() || Settings.isStoreOfflineWpMaps()) { importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_STORE_STATIC_MAPS, R.string.gpx_import_store_static_maps, search.getCount(), getSourceDisplayName())); final boolean finishedWithoutCancel = importStaticMaps(search); // Skip last message if static maps where canceled if (!finishedWithoutCancel) { return; } } importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_FINISHED, search.getCount(), 0, getSourceDisplayName())); } catch (final IOException e) { Log.i("Importing caches failed - error reading data: ", e); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_FINISHED_WITH_ERROR, R.string.gpx_import_error_io, 0, e.getLocalizedMessage())); } catch (final ParserException e) { Log.i("Importing caches failed - data format error", e); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_FINISHED_WITH_ERROR, R.string.gpx_import_error_parser, 0, e.getLocalizedMessage())); } catch (final CancellationException ignored) { Log.i("Importing caches canceled"); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_CANCELED, getSourceDisplayName())); } catch (final Exception e) { Log.e("Importing caches failed - unknown error: ", e); importStepHandler.sendMessage(importStepHandler.obtainMessage(GPXImporter.IMPORT_STEP_FINISHED_WITH_ERROR, R.string.gpx_import_error_unexpected, 0, e.getLocalizedMessage())); } } protected abstract Collection<Geocache> doImport() throws IOException, ParserException; /** * Return a user presentable name of the imported source * * @return The import source display name */ protected abstract String getSourceDisplayName(); private boolean importStaticMaps(final SearchResult importedCaches) { int storedCacheMaps = 0; for (final String geocode : importedCaches.getGeocodes()) { final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS); if (cache != null) { Log.d("GPXImporter.ImportThread.importStaticMaps start downloadMaps for cache " + geocode); StaticMapsProvider.downloadMaps(cache).await(); } else { Log.d("GPXImporter.ImportThread.importStaticMaps: no data found for " + geocode); } storedCacheMaps++; if (progressHandler.isCancelled()) { return false; } progressHandler.sendMessage(progressHandler.obtainMessage(0, storedCacheMaps, 0)); } return true; } }
apache-2.0
Hebury/BioscoopCasus
app/src/main/java/io/github/hebury/bioscoopcasus/domain/Movie.java
2454
package io.github.hebury.bioscoopcasus.domain; import java.io.Serializable; import static android.R.attr.id; public class Movie implements Serializable { private double rating; private String duration; private String title; private String genre; private String description; private String releasedate; private String actors; private String language; private String posterURI, thumbnailURI; public Movie() { } public Movie(String title, String genre, String description, String duration, String actors, String releasedate, double rating, String thumbnailURI, String posterURI) { this.title = title; this.genre = genre; this.description = description; this.duration = duration; this.actors = actors; this.releasedate = releasedate; this.rating = rating; this.thumbnailURI = thumbnailURI; this.posterURI = posterURI; } public int getId() { return id; } public String getLanguage() { return language; } public double getRating() { return rating; } public void setLanguage(String language) { this.language = language; } public String getThumbnailURI() { return thumbnailURI; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setRating(double rating) { this.rating = rating; } public String getReleasedate() { return releasedate; } public void setReleasedate(String releasedate) { this.releasedate = releasedate; } public String getActors() { return actors; } public void setActors(String actors) { this.actors = actors; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getPosterURI() { return posterURI; } public void setPosterURI(String posterURI) { this.posterURI = posterURI; } }
apache-2.0
Intel-bigdata/OAP
oap-cache/oap/src/main/java/org/apache/spark/sql/execution/vectorized/ColumnVectorAllocator.java
553
package org.apache.spark.sql.execution.vectorized; import org.apache.spark.memory.MemoryMode; import org.apache.spark.sql.types.StructType; import org.apache.spark.sql.vectorized.ColumnVector; public class ColumnVectorAllocator { public static ColumnVector[] allocateColumns( MemoryMode memoryMode, int capacity, StructType schema) { if (memoryMode == MemoryMode.OFF_HEAP) { return OffHeapColumnVector.allocateColumns(capacity, schema); } else { return OapOnHeapColumnVector.allocateColumns(capacity, schema); } } }
apache-2.0
BonDyka/abondarev
jun/chapter_005pro/src/test/java/ru/job4j/list/CheckCycleTest.java
1376
package ru.job4j.list; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * The class created for testing CheckCycle class. * * @author abondarev. * @since 04.09.2017 */ public class CheckCycleTest { /** * Test method hasCycle() when cycle exist. */ @Test public void whenListHasCycleShouldReturnTrue() { Node<Integer> first = new Node<>(1); Node<Integer> second = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); first.setNext(second); second.setNext(third); third.setNext(four); four.setNext(first); CheckCycle checker = new CheckCycle(); boolean result = checker.hasCycle(first); assertTrue(result); } /** * Test method hasCycle() when there is no cycle. */ @Test public void whenListHasNoCycleShouldReturnTrue() { Node<Integer> first = new Node<>(1); Node<Integer> second = new Node<>(2); Node<Integer> third = new Node<>(3); Node<Integer> four = new Node<>(4); first.setNext(second); second.setNext(third); third.setNext(four); CheckCycle checker = new CheckCycle(); boolean result = checker.hasCycle(first); assertFalse(result); } }
apache-2.0
abodabi/difido-reports
difido-reports-common/src/main/java/il/co/topq/difido/model/execution/MachineNode.java
756
package il.co.topq.difido.model.execution; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.annotate.JsonIgnore; public class MachineNode extends NodeWithChildren<ScenarioNode> { @JsonIgnore private List<ScenarioNode> allScenarios; public MachineNode() { } public MachineNode(String name) { super(name); } @JsonIgnore @Override public void addChild(ScenarioNode scenario) { super.addChild(scenario); addSubScenario(scenario); } @JsonIgnore public void addSubScenario(ScenarioNode scenario) { if (null == allScenarios) { allScenarios = new ArrayList<ScenarioNode>(); } allScenarios.add(scenario); } @JsonIgnore public List<ScenarioNode> getAllScenarios() { return allScenarios; } }
apache-2.0
ChibiTomo/ApiVersioning
src/test/java/net/chibidevteam/apiversioning/test/unit/HelperTest.java
1368
package net.chibidevteam.apiversioning.test.unit; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import net.chibidevteam.apiversioning.exceptions.NoSupportedVersionException; import net.chibidevteam.apiversioning.util.ApiVersionCondition; import net.chibidevteam.apiversioning.util.Utils; import net.chibidevteam.apiversioning.util.helper.ApiPathHelper; public class HelperTest { @Before public void resetDefault() throws NoSupportedVersionException { Utils.resetDefaults(); Utils.applyConfig(); } @Test public void getPaths01() throws NoSupportedVersionException { String[] expecteds = new String[] {}; boolean useVersionVar = true; boolean useApiPath = true; String[] versions = new String[] {}; String[] supportedVersions = new String[] {}; Utils.applyConfig(); String[] paths = getPaths(versions, supportedVersions, useApiPath, useVersionVar); Assert.assertArrayEquals(expecteds, paths); } private String[] getPaths(String[] versions, String[] supportedVersions, boolean useApiPath, boolean useVersionVar) { ApiVersionCondition apiVersionCondition = new ApiVersionCondition(versions, supportedVersions); return ApiPathHelper.getPaths(apiVersionCondition, useApiPath, useVersionVar); } }
apache-2.0
OpenXIP/xip-app
src/edu/wustl/xipApplication/recist/RECISTManager.java
1457
/* Copyright (c) 2013, Washington University in St.Louis. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package edu.wustl.xipApplication.recist; import java.io.File; import java.util.List; import org.nema.dicom.wg23.ObjectLocator; import edu.wustl.xipApplication.wg23.ClientToHost; import edu.wustl.xipApplication.wg23.WG23DataModel; public interface RECISTManager { public abstract void parseAIMObjects(List<ObjectLocator> items); public abstract int getNumberOfTumors(); public abstract List<Tumor> getTumors(); public abstract Tumor getTumor(String tumorName); public abstract void setSOPInstanceUIDPrev(List<String> sopInstanceUIDPrev); public abstract void setSOPInstanceUIDCurr(List<String> sopInstanceUIDCurr); public abstract List<File> getAIMPrevious(); public abstract List<File> getAIMCurrent(); public abstract void setOutputDir(String outputDir); public abstract String getOutputDir(); }
apache-2.0
davide-maestroni/jroutine
object/src/main/java/com/github/dm/jrt/object/annotation/CoreInstances.java
2545
/* * Copyright 2016 Davide Maestroni * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.dm.jrt.object.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Through this annotation it is possible to indicate the size of the core pool of reusable * invocation instances. * <p> * This annotation is used to decorate methods that are to be invoked in an asynchronous way. * <br> * Note that the piece of code inside such methods will be automatically protected so to avoid * concurrency issues. Though, other parts of the code inside the same class will be not. * <br> * In order to prevent unexpected behaviors, it is advisable to avoid using the same class fields * (unless immutable) in protected and non-protected code, or to call synchronous methods through * routines as well. * <p> * Finally, be aware that a method might need to be made accessible in order to be called. That * means that, in case a {@link java.lang.SecurityManager} is installed, a security exception might * be raised based on the specific policy implemented. * <p> * Remember also that, in order for the annotation to properly work at run time, the following rules * must be added to the project Proguard file (if employed for shrinking or obfuscation): * <pre> * <code> * * -keepattributes RuntimeVisibleAnnotations * -keepclassmembers class ** { * &#64;com.github.dm.jrt.object.annotation.CoreInstances *; * } * </code> * </pre> * <p> * Created by davide-maestroni on 10/05/2015. * * @see com.github.dm.jrt.core.config.InvocationConfiguration InvocationConfiguration */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface CoreInstances { /** * The number of invocation instances which represents the core pool of reusable invocations. * * @return the instance number. */ int value(); }
apache-2.0
plasma147/lorraine-dto-test-gen
src/main/java/uk/co/optimisticpanda/gtest/dto/defaultfill/enggen/visit/DataEditorVisitor.java
1114
/* * Copyright 2009 Andy Lee. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package uk.co.optimisticpanda.gtest.dto.defaultfill.enggen.visit; import uk.co.optimisticpanda.gtest.dto.IDataEditor; /** * A Visitor that uses the passed in {@link IDataEditor} to edit the dtos that it visits * * @param <D> * @author Andy Lee */ public class DataEditorVisitor<D> implements IEngineVisitor<D> { private final IDataEditor<D> editor; public DataEditorVisitor(IDataEditor<D> editor) { this.editor = editor; } @Override public void visit(int index, D dto) { editor.edit(index, dto); } }
apache-2.0
googleapis/java-datacatalog
google-cloud-datacatalog/src/main/java/com/google/cloud/datacatalog/v1beta1/PolicyTagManagerSerializationSettings.java
8169
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.datacatalog.v1beta1; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.ClientSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.cloud.datacatalog.v1beta1.stub.PolicyTagManagerSerializationStubSettings; import java.io.IOException; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link PolicyTagManagerSerializationClient}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (datacatalog.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of importTaxonomies to 30 seconds: * * <pre>{@code * PolicyTagManagerSerializationSettings.Builder policyTagManagerSerializationSettingsBuilder = * PolicyTagManagerSerializationSettings.newBuilder(); * policyTagManagerSerializationSettingsBuilder * .importTaxonomiesSettings() * .setRetrySettings( * policyTagManagerSerializationSettingsBuilder * .importTaxonomiesSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * PolicyTagManagerSerializationSettings policyTagManagerSerializationSettings = * policyTagManagerSerializationSettingsBuilder.build(); * }</pre> */ @BetaApi @Generated("by gapic-generator-java") public class PolicyTagManagerSerializationSettings extends ClientSettings<PolicyTagManagerSerializationSettings> { /** Returns the object with the settings used for calls to importTaxonomies. */ public UnaryCallSettings<ImportTaxonomiesRequest, ImportTaxonomiesResponse> importTaxonomiesSettings() { return ((PolicyTagManagerSerializationStubSettings) getStubSettings()) .importTaxonomiesSettings(); } /** Returns the object with the settings used for calls to exportTaxonomies. */ public UnaryCallSettings<ExportTaxonomiesRequest, ExportTaxonomiesResponse> exportTaxonomiesSettings() { return ((PolicyTagManagerSerializationStubSettings) getStubSettings()) .exportTaxonomiesSettings(); } public static final PolicyTagManagerSerializationSettings create( PolicyTagManagerSerializationStubSettings stub) throws IOException { return new PolicyTagManagerSerializationSettings.Builder(stub.toBuilder()).build(); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return PolicyTagManagerSerializationStubSettings.defaultExecutorProviderBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return PolicyTagManagerSerializationStubSettings.getDefaultEndpoint(); } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return PolicyTagManagerSerializationStubSettings.getDefaultServiceScopes(); } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return PolicyTagManagerSerializationStubSettings.defaultCredentialsProviderBuilder(); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return PolicyTagManagerSerializationStubSettings.defaultGrpcTransportProviderBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return PolicyTagManagerSerializationStubSettings.defaultTransportChannelProvider(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return PolicyTagManagerSerializationStubSettings.defaultApiClientHeaderProviderBuilder(); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected PolicyTagManagerSerializationSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); } /** Builder for PolicyTagManagerSerializationSettings. */ public static class Builder extends ClientSettings.Builder<PolicyTagManagerSerializationSettings, Builder> { protected Builder() throws IOException { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(PolicyTagManagerSerializationStubSettings.newBuilder(clientContext)); } protected Builder(PolicyTagManagerSerializationSettings settings) { super(settings.getStubSettings().toBuilder()); } protected Builder(PolicyTagManagerSerializationStubSettings.Builder stubSettings) { super(stubSettings); } private static Builder createDefault() { return new Builder(PolicyTagManagerSerializationStubSettings.newBuilder()); } public PolicyTagManagerSerializationStubSettings.Builder getStubSettingsBuilder() { return ((PolicyTagManagerSerializationStubSettings.Builder) getStubSettings()); } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } /** Returns the builder for the settings used for calls to importTaxonomies. */ public UnaryCallSettings.Builder<ImportTaxonomiesRequest, ImportTaxonomiesResponse> importTaxonomiesSettings() { return getStubSettingsBuilder().importTaxonomiesSettings(); } /** Returns the builder for the settings used for calls to exportTaxonomies. */ public UnaryCallSettings.Builder<ExportTaxonomiesRequest, ExportTaxonomiesResponse> exportTaxonomiesSettings() { return getStubSettingsBuilder().exportTaxonomiesSettings(); } @Override public PolicyTagManagerSerializationSettings build() throws IOException { return new PolicyTagManagerSerializationSettings(this); } } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p215/Test4301.java
2343
package org.gradle.test.performance.mediummonolithicjavaproject.p215; import org.gradle.test.performance.mediummonolithicjavaproject.p214.Production4298; import org.gradle.test.performance.mediummonolithicjavaproject.p214.Production4299; import org.junit.Test; import static org.junit.Assert.*; public class Test4301 { Production4301 objectUnderTest = new Production4301(); @Test public void testProperty0() { Production4298 value = new Production4298(); objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { Production4299 value = new Production4299(); objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { Production4300 value = new Production4300(); objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
apache-2.0
pellcorp/fop
test/java/org/apache/fop/BasicTranscoderTestSuite.java
1249
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id: BasicTranscoderTestSuite.java 1178747 2011-10-04 10:09:01Z vhennebert $ */ package org.apache.fop; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * Test suite for basic functionality of FOP's transcoders. */ @RunWith(Suite.class) @SuiteClasses({ BasicPDFTranscoderTestCase.class, BasicPSTranscoderTestCase.class }) public class BasicTranscoderTestSuite { }
apache-2.0
jmnarloch/spring-security
config/src/main/java/org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.java
9662
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.springframework.security.config.annotation.web.socket; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver; import org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry; import org.springframework.security.messaging.access.expression.MessageExpressionVoter; import org.springframework.security.messaging.access.intercept.ChannelSecurityInterceptor; import org.springframework.security.messaging.access.intercept.MessageSecurityMetadataSource; import org.springframework.security.messaging.context.AuthenticationPrincipalArgumentResolver; import org.springframework.security.messaging.context.SecurityContextChannelInterceptor; import org.springframework.security.messaging.web.csrf.CsrfChannelInterceptor; import org.springframework.security.messaging.web.socket.server.CsrfTokenHandshakeInterceptor; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.HandshakeInterceptor; import org.springframework.web.socket.server.support.WebSocketHttpRequestHandler; import org.springframework.web.socket.sockjs.SockJsService; import org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler; import org.springframework.web.socket.sockjs.transport.TransportHandlingSockJsService; /** * Allows configuring WebSocket Authorization. * * <p> * For example: * </p> * * <pre> * &#064;Configuration * public class WebSocketSecurityConfig extends * AbstractSecurityWebSocketMessageBrokerConfigurer { * * &#064;Override * protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { * messages.simpDestMatchers(&quot;/user/queue/errors&quot;).permitAll() * .simpDestMatchers(&quot;/admin/**&quot;).hasRole(&quot;ADMIN&quot;).anyMessage() * .authenticated(); * } * } * </pre> * * * @since 4.0 * @author Rob Winch */ @Order(Ordered.HIGHEST_PRECEDENCE + 100) public abstract class AbstractSecurityWebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer implements SmartInitializingSingleton { private final WebSocketMessageSecurityMetadataSourceRegistry inboundRegistry = new WebSocketMessageSecurityMetadataSourceRegistry(); private ApplicationContext context; public void registerStompEndpoints(StompEndpointRegistry registry) { } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(new AuthenticationPrincipalArgumentResolver()); } @Override public final void configureClientInboundChannel(ChannelRegistration registration) { ChannelSecurityInterceptor inboundChannelSecurity = inboundChannelSecurity(); registration.setInterceptors(securityContextChannelInterceptor()); if (!sameOriginDisabled()) { registration.setInterceptors(csrfChannelInterceptor()); } if (inboundRegistry.containsMapping()) { registration.setInterceptors(inboundChannelSecurity); } customizeClientInboundChannel(registration); } private PathMatcher getDefaultPathMatcher() { try { return context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher(); } catch(NoSuchBeanDefinitionException e) { return new AntPathMatcher(); } } /** * <p> * Determines if a CSRF token is required for connecting. This protects against remote * sites from connecting to the application and being able to read/write data over the * connection. The default is false (the token is required). * </p> * <p> * Subclasses can override this method to disable CSRF protection * </p> * * @return false if a CSRF token is required for connecting, else true */ protected boolean sameOriginDisabled() { return false; } /** * Allows subclasses to customize the configuration of the {@link ChannelRegistration} * . * * @param registration the {@link ChannelRegistration} to customize */ protected void customizeClientInboundChannel(ChannelRegistration registration) { } @Bean public CsrfChannelInterceptor csrfChannelInterceptor() { return new CsrfChannelInterceptor(); } @Bean public ChannelSecurityInterceptor inboundChannelSecurity() { ChannelSecurityInterceptor channelSecurityInterceptor = new ChannelSecurityInterceptor( inboundMessageSecurityMetadataSource()); List<AccessDecisionVoter<? extends Object>> voters = new ArrayList<AccessDecisionVoter<? extends Object>>(); voters.add(new MessageExpressionVoter<Object>()); AffirmativeBased manager = new AffirmativeBased(voters); channelSecurityInterceptor.setAccessDecisionManager(manager); return channelSecurityInterceptor; } @Bean public SecurityContextChannelInterceptor securityContextChannelInterceptor() { return new SecurityContextChannelInterceptor(); } @Bean public MessageSecurityMetadataSource inboundMessageSecurityMetadataSource() { configureInbound(inboundRegistry); return inboundRegistry.createMetadataSource(); } /** * * @param messages */ protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { } private static class WebSocketMessageSecurityMetadataSourceRegistry extends MessageSecurityMetadataSourceRegistry { @Override public MessageSecurityMetadataSource createMetadataSource() { return super.createMetadataSource(); } @Override protected boolean containsMapping() { return super.containsMapping(); } @Override protected boolean isSimpDestPathMatcherConfigured() { return super.isSimpDestPathMatcherConfigured(); } } @Autowired public void setApplicationContext(ApplicationContext context) { this.context = context; } public void afterSingletonsInstantiated() { if (sameOriginDisabled()) { return; } String beanName = "stompWebSocketHandlerMapping"; SimpleUrlHandlerMapping mapping = context.getBean(beanName, SimpleUrlHandlerMapping.class); Map<String, Object> mappings = mapping.getHandlerMap(); for (Object object : mappings.values()) { if (object instanceof SockJsHttpRequestHandler) { SockJsHttpRequestHandler sockjsHandler = (SockJsHttpRequestHandler) object; SockJsService sockJsService = sockjsHandler.getSockJsService(); if (!(sockJsService instanceof TransportHandlingSockJsService)) { throw new IllegalStateException( "sockJsService must be instance of TransportHandlingSockJsService got " + sockJsService); } TransportHandlingSockJsService transportHandlingSockJsService = (TransportHandlingSockJsService) sockJsService; List<HandshakeInterceptor> handshakeInterceptors = transportHandlingSockJsService .getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<HandshakeInterceptor>( handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); transportHandlingSockJsService .setHandshakeInterceptors(interceptorsToSet); } else if (object instanceof WebSocketHttpRequestHandler) { WebSocketHttpRequestHandler handler = (WebSocketHttpRequestHandler) object; List<HandshakeInterceptor> handshakeInterceptors = handler .getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<HandshakeInterceptor>( handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); handler.setHandshakeInterceptors(interceptorsToSet); } else { throw new IllegalStateException( "Bean " + beanName + " is expected to contain mappings to either a SockJsHttpRequestHandler or a WebSocketHttpRequestHandler but got " + object); } } if (inboundRegistry.containsMapping() && !inboundRegistry.isSimpDestPathMatcherConfigured()) { PathMatcher pathMatcher = getDefaultPathMatcher(); inboundRegistry.simpDestPathMatcher(pathMatcher); } } }
apache-2.0
soundcloud/zipkin
zipkin-autoconfigure/storage-elasticsearch-aws/src/main/java/zipkin/autoconfigure/storage/elasticsearch/aws/ZipkinElasticsearchAwsStorageProperties.java
1555
/** * Copyright 2015-2018 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package zipkin.autoconfigure.storage.elasticsearch.aws; import java.io.Serializable; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("zipkin.storage.elasticsearch.aws") class ZipkinElasticsearchAwsStorageProperties implements Serializable { // for Spark jobs private static final long serialVersionUID = 0L; /** The name of a domain to look up by endpoint. Exclusive with hosts list. */ private String domain; /** * The optional region to search for the domain {@link #domain}. Defaults the usual * way (AWS_REGION, DEFAULT_AWS_REGION, etc.). */ private String region; public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = "".equals(domain) ? null : domain; } public String getRegion() { return region; } public void setRegion(String region) { this.region = "".equals(region) ? null : region; } }
apache-2.0
material-components/material-components-android
catalog/java/io/material/catalog/tabs/TabsAutoDemoFragment.java
3579
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.material.catalog.tabs; import io.material.catalog.R; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayout.Tab; import io.material.catalog.feature.DemoFragment; /** A fragment that displays a scrollable tabs demo for the Catalog app. */ public class TabsAutoDemoFragment extends DemoFragment { private static final String KEY_TABS = "TABS"; private int numTabs = 0; private String[] tabTitles; private TabLayout autoScrollableTabLayout; @Nullable @Override public View onCreateDemoView( LayoutInflater layoutInflater, @Nullable ViewGroup viewGroup, @Nullable Bundle bundle) { View view = layoutInflater.inflate( R.layout.cat_tabs_auto_fragment, viewGroup, false /* attachToRoot */); ViewGroup content = view.findViewById(R.id.content); View tabsContent = layoutInflater.inflate(getTabsContent(), content, false /* attachToRoot */); content.addView(tabsContent, 0); autoScrollableTabLayout = tabsContent.findViewById(R.id.auto_tab_layout); if (bundle != null) { autoScrollableTabLayout.removeAllTabs(); // Restore saved tabs String[] tabLabels = bundle.getStringArray(KEY_TABS); for (int i = 0; i < tabLabels.length; i++) { autoScrollableTabLayout.addTab(autoScrollableTabLayout.newTab().setText(tabLabels[i]), i); } } numTabs = autoScrollableTabLayout.getTabCount(); tabTitles = getContext().getResources().getStringArray(R.array.cat_tabs_titles); Button addButton = view.findViewById(R.id.add_tab_button); addButton.setOnClickListener( v -> { autoScrollableTabLayout.addTab( autoScrollableTabLayout.newTab().setText(tabTitles[numTabs % tabTitles.length])); numTabs += 1; }); Button removeButton = view.findViewById(R.id.remove_tab_button); removeButton.setOnClickListener( v -> { Tab tab = autoScrollableTabLayout.getTabAt(autoScrollableTabLayout.getTabCount() - 1); if (tab != null) { autoScrollableTabLayout.removeTab(tab); } numTabs = Math.max(0, numTabs - 1); }); return view; } @LayoutRes protected int getTabsContent() { return R.layout.cat_tabs_auto_content; } @Override public void onSaveInstanceState(@NonNull Bundle bundle) { super.onSaveInstanceState(bundle); String[] tabLabels = new String[autoScrollableTabLayout.getTabCount()]; for (int i = 0; i < autoScrollableTabLayout.getTabCount(); i++) { tabLabels[i] = autoScrollableTabLayout.getTabAt(i).getText().toString(); } bundle.putStringArray(KEY_TABS, tabLabels); } }
apache-2.0
twak/chordatlas
src/org/twak/viewTrace/Closer.java
2271
package org.twak.viewTrace; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.twak.utils.collections.MultiMapSet; public class Closer<E> { Map <E, Integer> map = new HashMap<>(); MultiMapSet <Integer, E> rev = new MultiMapSet<>(); // could be a single map! int nextInt = 0; public void add(E...es) { Set<Integer> toMerge = new HashSet<>(); Set<E> toMergeE = new HashSet<>(); for (E e : es) { Integer s = map.get(e); if (s != null) { toMerge.add( s ); toMergeE.addAll(rev.get(s)); } } if (toMerge.isEmpty()) { for (E e : es) { map.put(e, nextInt); rev.put(nextInt, e); } nextInt++; return; } int set = toMerge.stream().min( Double::compare ).get(); for (E e : toMergeE) { rev.remove(map.get(e), e); rev.put(set, e); map.put(e, set); } for (E e : es) { map.put(e, set); rev.put(set, e); } } public void add(Iterable<E> es) { Set<Integer> toMerge = new HashSet<>(); Set<E> toMergeE = new HashSet<>(); for (E e : es) { Integer s = map.get(e); if (s != null) { toMerge.add( s ); toMergeE.addAll(rev.get(s)); } } if (toMerge.isEmpty()) { for (E e : es) { map.put(e, nextInt); rev.put(nextInt, e); } nextInt++; return; } int set = toMerge.stream().min( Double::compare ).get(); for (E e : toMergeE) { rev.remove(map.get(e), e); rev.put(set, e); map.put(e, set); } for (E e : es) { map.put(e, set); rev.put(set, e); } } public Set<Set<E>> close() { Set<Set<E>> out = new HashSet(); for (Integer i : rev.keySet()) { Set<E> set = rev.get(i); if (!set.isEmpty()) out.add(new HashSet<>(set)); } return out; } public Map<E, Integer> findMap() { return new HashMap<E, Integer>( map ); } public static void main (String[] args) { Closer<Integer> closer = new Closer<>(); closer.add(1,2); closer.add(2,3); closer.add(4,5, 6, 7, 8); closer.add(8, 9); closer.add(8, 10); closer.add(-1, 1); closer.add(-11, -8); closer.add(-110, -8); for (Set<Integer> si : closer.close()) { si.stream().forEach( a -> System.out.print (a+" ") ); System.out.println(); } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/BatchStopResultJsonUnmarshaller.java
3163
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.medialive.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.medialive.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * BatchStopResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class BatchStopResultJsonUnmarshaller implements Unmarshaller<BatchStopResult, JsonUnmarshallerContext> { public BatchStopResult unmarshall(JsonUnmarshallerContext context) throws Exception { BatchStopResult batchStopResult = new BatchStopResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return batchStopResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("failed", targetDepth)) { context.nextToken(); batchStopResult.setFailed(new ListUnmarshaller<BatchFailedResultModel>(BatchFailedResultModelJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("successful", targetDepth)) { context.nextToken(); batchStopResult.setSuccessful(new ListUnmarshaller<BatchSuccessfulResultModel>(BatchSuccessfulResultModelJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return batchStopResult; } private static BatchStopResultJsonUnmarshaller instance; public static BatchStopResultJsonUnmarshaller getInstance() { if (instance == null) instance = new BatchStopResultJsonUnmarshaller(); return instance; } }
apache-2.0
FOC-framework/framework
foc/src/com/foc/db/migration/MigrationSourceGuiDetailsPanel.java
4357
/******************************************************************************* * Copyright 2016 Antoine Nicolas SAMAHA * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.foc.db.migration; import java.awt.GridBagConstraints; import com.foc.desc.FocObject; import com.foc.desc.field.FField; import com.foc.gui.FGTextField; import com.foc.gui.FPanel; import com.foc.gui.FValidationPanel; import com.foc.property.FProperty; import com.foc.property.FPropertyListener; @SuppressWarnings("serial") public class MigrationSourceGuiDetailsPanel extends FPanel{ public final static int VIEW_SELECTION = 2; private FPropertyListener sourceTypeListener = null; private MigrationSource migSource = null; private FPanel databasePanel = null; private FPanel directoryPanel = null; public MigrationSourceGuiDetailsPanel(FocObject obj, int viewID){ migSource = (MigrationSource) obj; if(viewID == VIEW_SELECTION){ setInsets(0, 0, 0, 0); FGTextField comp = (FGTextField) obj.getGuiComponent(MigrationSourceDesc.FLD_DESCRIPTION); comp.setEditable(false); add(comp, 1, 0); }else{ setMainPanelSising(FPanel.FILL_BOTH); if(migSource.isCreated()){ setFrameTitle("New Migration Source"); init_New(); }else{ setFrameTitle("Migration Source : "+migSource.getName()); init_Edit(); } FValidationPanel vPanel = showValidationPanel(true); vPanel.addSubject(migSource); } } private void init_New(){ int y = 0; add(migSource, FField.FLD_NAME, 0, y++); add(migSource, MigrationSourceDesc.FLD_DESCRIPTION, 0, y++); add(migSource, MigrationSourceDesc.FLD_DESTINATION_TABLE, 0, y++); } private void init_Edit(){ int y = 0; add(migSource, FField.FLD_NAME, 0, y++); add(migSource, MigrationSourceDesc.FLD_DESCRIPTION, 0, y++); add(migSource, MigrationSourceDesc.FLD_DESTINATION_TABLE, 0, y++); add(migSource, MigrationSourceDesc.FLD_SOURCE_TYPE, 0, y++); databasePanel = new FPanel(); databasePanel.add(migSource, MigrationSourceDesc.FLD_DATABASE, 0, 0); databasePanel.add(migSource, MigrationSourceDesc.FLD_TABLE_NAME, 0, 1); add(databasePanel, 0, y, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); directoryPanel = new FPanel(); directoryPanel.add(migSource, MigrationSourceDesc.FLD_DIRECTORY, 0, 0); directoryPanel.add(migSource, MigrationSourceDesc.FLD_FILE_NAME, 0, 1); add(directoryPanel, 0, y++, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); sourceTypeListener = new FPropertyListener(){ public void dispose() { } public void propertyModified(FProperty property) { databasePanel.setVisible(migSource.getSourceType() == MigrationSourceDesc.SOURCE_TYPE_DATABASE_TABLE); directoryPanel.setVisible(migSource.getSourceType() == MigrationSourceDesc.SOURCE_TYPE_COMMA_SEPARATED_FILE); } }; migSource.getFocProperty(MigrationSourceDesc.FLD_SOURCE_TYPE).addListener(sourceTypeListener); sourceTypeListener.propertyModified(migSource.getFocProperty(MigrationSourceDesc.FLD_SOURCE_TYPE)); MigFieldMapGuiBrowsePanel fldMapGuiDetails = new MigFieldMapGuiBrowsePanel(migSource.getMapFieldList(), FocObject.DEFAULT_VIEW_ID); add(fldMapGuiDetails, 0, y++, 2, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH); } public void dispose(){ super.dispose(); if(sourceTypeListener != null && migSource != null){ migSource.getFocProperty(MigrationSourceDesc.FLD_SOURCE_TYPE).removeListener(sourceTypeListener); sourceTypeListener.dispose(); } migSource = null; sourceTypeListener = null; databasePanel = null; directoryPanel = null; } }
apache-2.0
DwarfPlanetGames/mininggame
ios/src/ml/dpgames/mine/IOSLauncher.java
748
package ml.dpgames.mine; import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import ml.dpgames.mine.MGMain; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); return new IOSApplication(new MGMain(), config); } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, IOSLauncher.class); pool.close(); } }
apache-2.0
lperilla/jmeter-utilities
src/main/java/com/lperilla/jmeter/plugin/gui/component/JLabeledTextField.java
6851
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.lperilla.jmeter.plugin.gui.component; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * * @author lperilla * */ public class JLabeledTextField extends JPanel implements JLabeledField, FocusListener { private static final long serialVersionUID = 240L; private JLabel label; private JTextField textField; // Maybe move to vector if MT problems occur private final ArrayList<ChangeListener> changeListeners = new ArrayList<ChangeListener>(3); // A temporary cache for the focus listener private String oldValue = ""; /** * Default constructor, The label and the Text field are left empty. */ public JLabeledTextField() { this("", 20); } /** * Constructs a new component with the label displaying the passed text. * * @param pLabel * The text to in the label. */ public JLabeledTextField(String pLabel) { this(pLabel, 20); } public JLabeledTextField(String pLabel, int size) { super(); setTextField(createTextField(size)); setLabel(new JLabel(pLabel)); getLabel().setLabelFor(getTextField()); init(); } public JLabeledTextField(String pLabel, Color bk) { super(); setTextField(createTextField(20)); setLabel(new JLabel(pLabel)); getLabel().setBackground(bk); getLabel().setLabelFor(getTextField()); this.setBackground(bk); init(); } /** * Get the label {@link JLabel} followed by the text field @link * {@link JTextField}. */ public List<JComponent> getComponentList() { List<JComponent> comps = new LinkedList<JComponent>(); comps.add(getLabel()); comps.add(getTextField()); return comps; } /** {@inheritDoc} */ @Override public void setEnabled(boolean enable) { super.setEnabled(enable); getTextField().setEnabled(enable); } protected JTextField createTextField(int size) { return new JTextField(size); } /** * Initialises all of the components on this panel. */ private void init() { this.setLayout(new BorderLayout(5, 0)); // Register the handler for focus listening. This handler will // only notify the registered when the text changes from when // the focus is gained to when it is lost. this.getTextField().addFocusListener(this); // Add the sub components this.add(this.getLabel(), BorderLayout.WEST); this.add(this.getTextField(), BorderLayout.CENTER); } /** * Callback method when the focus to the Text Field component is lost. * * @param pFocusEvent * The focus event that occured. */ public void focusLost(FocusEvent pFocusEvent) { // Compare if the value has changed, since we received focus. if (!oldValue.equals(getTextField().getText())) { notifyChangeListeners(); } } /** * Catch what the value was when focus was gained. */ public void focusGained(FocusEvent pFocusEvent) { oldValue = this.getTextField().getText(); } /** * Set the text displayed in the label. * * @param pLabel * The new label text. */ public void setTextLabel(String pLabel) { getLabel().setText(pLabel); } /** * Set the text displayed in the Text Field. * * @param text * The new text to display in the text field. */ public void setText(String text) { getTextField().setText(text); } /** * Returns the text in the Text Field. * * @return The text in the Text Field. */ public String getText() { return getTextField().getText(); } /** * Returns the text of the label. * * @return The text of the label. */ public String getTextLabel() { return getLabel().getText(); } /** * Registers the text to display in a tool tip. The text displays when the * cursor lingers over the component. * * @param text * the string to display; if the text is null, the tool tip is * turned off for this component */ public void setToolTipText(String text) { this.getLabel().setToolTipText(text); this.getTextField().setToolTipText(text); } /** * Returns the tooltip string that has been set with setToolTipText * * @return the text of the tool tip */ public String getToolTipText() { if (getTextField() == null) { // Necessary to avoid NPE when testing serialisation return null; } return getTextField().getToolTipText(); } /** * Adds a change listener, that will be notified when the text in the text * field is changed. The ChangeEvent that will be passed to registered * listeners will contain this object as the source, allowing the new text * to be extracted using the {@link #getText() getText} method. * * @param pChangeListener * The listener to add */ public void addChangeListener(ChangeListener pChangeListener) { changeListeners.add(pChangeListener); } /** * Removes a change listener. * * @param pChangeListener * The change listener to remove. */ public void removeChangeListener(ChangeListener pChangeListener) { changeListeners.remove(pChangeListener); } /** * Notify all registered change listeners that the text in the text field * has changed. */ protected void notifyChangeListeners() { ChangeEvent ce = new ChangeEvent(this); for (int index = 0; index < changeListeners.size(); index++) { changeListeners.get(index).stateChanged(ce); } } @Override public void addKeyListener(KeyListener l) { if (l == null) return; this.getTextField().addKeyListener(l); } public JTextField getTextField() { return textField; } public void setTextField(JTextField textField) { this.textField = textField; } public JLabel getLabel() { return label; } public void setLabel(JLabel label) { this.label = label; } }
apache-2.0
lastaflute/lastaflute-test-fortress
src/main/java/org/docksidestage/app/web/withdrawal/WithdrawalAction.java
3853
package org.docksidestage.app.web.withdrawal; import javax.annotation.Resource; import org.docksidestage.app.web.base.FortressBaseAction; import org.docksidestage.app.web.signout.SignoutAction; import org.docksidestage.dbflute.exbhv.MemberBhv; import org.docksidestage.dbflute.exbhv.MemberWithdrawalBhv; import org.docksidestage.dbflute.exentity.Member; import org.docksidestage.dbflute.exentity.MemberWithdrawal; import org.docksidestage.mylasta.action.FortressMessages; import org.lastaflute.core.time.TimeManager; import org.lastaflute.core.util.LaStringUtil; import org.lastaflute.web.Execute; import org.lastaflute.web.response.HtmlResponse; /** * @author annie_pocket * @author jflute */ public class WithdrawalAction extends FortressBaseAction { // =================================================================================== // Attribute // ========= @Resource private TimeManager timeManager; @Resource private MemberBhv memberBhv; @Resource private MemberWithdrawalBhv memberWithdrawalBhv; // =================================================================================== // Execute // ======= @Execute public HtmlResponse index() { return asEntryHtml(); } @Execute public HtmlResponse confirm(WithdrawalForm form) { validate(form, messages -> moreValidation(form, messages), () -> { return asEntryHtml(); }); return asConfirmHtml(); } private void moreValidation(WithdrawalForm form, FortressMessages messages) { if (form.selectedReason == null && LaStringUtil.isEmpty(form.reasonInput)) { messages.addConstraintsRequiredMessage("selectedReason"); } } @Execute public HtmlResponse done(WithdrawalForm form) { validate(form, message -> {}, () -> { return asEntryHtml(); }); Integer memberId = getUserBean().get().getMemberId(); insertWithdrawal(form, memberId); updateStatusWithdrawal(memberId); return redirect(SignoutAction.class); } // =================================================================================== // Update // ====== private void insertWithdrawal(WithdrawalForm form, Integer memberId) { MemberWithdrawal withdrawal = new MemberWithdrawal(); withdrawal.setMemberId(memberId); withdrawal.setWithdrawalReasonCodeAsWithdrawalReason(form.selectedReason); withdrawal.setWithdrawalReasonInputText(form.reasonInput); withdrawal.setWithdrawalDatetime(timeManager.currentDateTime()); memberWithdrawalBhv.insert(withdrawal); } private void updateStatusWithdrawal(Integer memberId) { Member member = new Member(); member.setMemberId(memberId); member.setMemberStatusCode_Withdrawal(); memberBhv.updateNonstrict(member); } // =================================================================================== // Assist Logic // ============ private HtmlResponse asEntryHtml() { return asHtml(path_Withdrawal_WithdrawalEntryHtml); } private HtmlResponse asConfirmHtml() { return asHtml(path_Withdrawal_WithdrawalConfirmHtml); } }
apache-2.0
NationalSecurityAgency/ghidra
Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/service/FidMatch.java
1266
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.feature.fid.service; import ghidra.feature.fid.db.LibraryRecord; import ghidra.program.model.address.Address; /** * FidMatch is a container that holds the results of a FidService search, * comprised of the full path within the storage API where it's located. * */ public interface FidMatch extends FidMatchScore { /** * Returns the actual entry point of the matched function (in the searched program, not the FID library). * @return the entry point of the matched function */ Address getMatchedFunctionEntryPoint(); /** * Returns the library record for the potential match. * @return the library record */ LibraryRecord getLibraryRecord(); }
apache-2.0
ukupat/what-2-do
src/w2d/question/Question.java
185
package w2d.question; public abstract class Question { public String label; public String answer; public Question(String label) { this.label = label.replaceAll("\"", ""); } }
apache-2.0
masaki-yamakawa/geode
geode-apis-compatible-with-redis/src/acceptanceTest/java/org/apache/geode/redis/internal/executor/string/IncrByNativeRedisAcceptanceTest.java
1273
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.redis.internal.executor.string; import org.junit.ClassRule; import org.apache.geode.redis.NativeRedisClusterTestRule; public class IncrByNativeRedisAcceptanceTest extends AbstractIncrByIntegrationTest { @ClassRule public static NativeRedisClusterTestRule redis = new NativeRedisClusterTestRule(); @Override public int getPort() { return redis.getExposedPorts().get(0); } @Override public void flushAll() { redis.flushAll(); } }
apache-2.0
jiang111/ZhiHu-TopAnswer
app/src/androidTest/java/com/jiang/android/zhihu_topanswer/ExampleInstrumentedTest.java
770
package com.jiang.android.zhihu_topanswer; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.jiang.android.zhihu_topanswer", appContext.getPackageName()); } }
apache-2.0
fengjx/solo
src/main/java/org/b3log/solo/plugin/broadcast/ChanceProcessor.java
11148
/* * Copyright (c) 2010-2017, b3log.org & hacpai.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.b3log.solo.plugin.broadcast; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Future; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.b3log.latke.Keys; import org.b3log.latke.Latkes; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.renderer.JSONRenderer; import org.b3log.latke.urlfetch.HTTPRequest; import org.b3log.latke.urlfetch.HTTPResponse; import org.b3log.latke.urlfetch.URLFetchService; import org.b3log.latke.urlfetch.URLFetchServiceFactory; import org.b3log.latke.util.Requests; import org.b3log.latke.util.Strings; import org.b3log.solo.SoloServletListener; import org.b3log.solo.model.Option; import org.b3log.solo.service.OptionMgmtService; import org.b3log.solo.service.OptionQueryService; import org.b3log.solo.service.PreferenceQueryService; import org.b3log.solo.service.UserQueryService; import org.b3log.solo.util.QueryResults; import org.json.JSONObject; /** * Broadcast chance processor. * * @author <a href="http://88250.b3log.org">Liang Ding</a> * @version 1.0.0.10, Nov 20, 2015 * @since 0.6.0 */ @RequestProcessor public class ChanceProcessor { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ChanceProcessor.class.getName()); /** * Option management service. */ @Inject private OptionMgmtService optionMgmtService; /** * Option query service. */ @Inject private OptionQueryService optionQueryService; /** * URL fetch service. */ private final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService(); /** * User query service. */ @Inject private UserQueryService userQueryService; /** * Preference query service. */ @Inject private PreferenceQueryService preferenceQueryService; /** * URL of adding article to Rhythm. */ private static final URL ADD_BROADCAST_URL; static { try { ADD_BROADCAST_URL = new URL(SoloServletListener.B3LOG_RHYTHM_SERVE_PATH + "/broadcast"); } catch (final MalformedURLException e) { LOGGER.log(Level.ERROR, "Creates remote service address[rhythm add broadcast] error!"); throw new IllegalStateException(e); } } /** * Adds a broadcast chance to option repository. * * <p> * Renders the response with a json object, for example, * <pre> * { * "sc": boolean, * "msg": "" // optional * } * </pre> * </p> * * @param context the specified http request context * @param request the specified http servlet request * @param response the specified http servlet response * @throws Exception */ @RequestProcessing(value = "/console/plugins/b3log-broadcast/chance", method = HTTPRequestMethod.POST) public void addChance(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final JSONRenderer renderer = new JSONRenderer(); context.setRenderer(renderer); final JSONObject ret = new JSONObject(); renderer.setJSONObject(ret); try { // TODO: verify b3 key final String time = request.getParameter("time"); if (Strings.isEmptyOrNull(time)) { ret.put(Keys.STATUS_CODE, false); return; } final long expirationTime = Long.valueOf(time); final JSONObject option = new JSONObject(); option.put(Keys.OBJECT_ID, Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME); option.put(Option.OPTION_VALUE, expirationTime); option.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_BROADCAST); optionMgmtService.addOrUpdateOption(option); ret.put(Keys.STATUS_CODE, true); } catch (final Exception e) { final String msg = "Broadcast plugin exception"; LOGGER.log(Level.ERROR, msg, e); final JSONObject jsonObject = QueryResults.defaultResult(); renderer.setJSONObject(jsonObject); jsonObject.put(Keys.MSG, msg); } } /** * Dose the client has a broadcast chance. * * <p> * If the request come from a user not administrator, consider it is no broadcast chance. * </p> * * <p> * Renders the response with a json object, for example, * <pre> * { * "sc": boolean, // if has a chance, the value will be true * "broadcastChanceExpirationTime": long, // if has a chance, the value will larger then 0L * } * </pre> * </p> * * @param context the specified http request context * @param request the specified http servlet request * @param response the specified http servlet response * @throws Exception */ @RequestProcessing(value = "/console/plugins/b3log-broadcast/chance", method = HTTPRequestMethod.GET) public void hasChance(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (!userQueryService.isLoggedIn(request, response)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final JSONRenderer renderer = new JSONRenderer(); context.setRenderer(renderer); final JSONObject ret = new JSONObject(); renderer.setJSONObject(ret); if (!userQueryService.isAdminLoggedIn(request)) { ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, 0L); ret.put(Keys.STATUS_CODE, false); return; } try { final JSONObject option = optionQueryService.getOptionById(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME); if (null == option) { ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, 0L); ret.put(Keys.STATUS_CODE, false); return; } ret.put(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME, option.getLong(Option.OPTION_VALUE)); ret.put(Keys.STATUS_CODE, true); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Broadcast plugin exception", e); final JSONObject jsonObject = QueryResults.defaultResult(); renderer.setJSONObject(jsonObject); } } /** * Submits a broadcast. * * <p> * Renders the response with a json object, for example, * <pre> * { * "sc": boolean, * "msg": "" // optional * } * </pre> * </p> * * @param context the specified http request context * @param request the specified http servlet request, for example, * <pre> * { * "broadcast": { * "title": "", * "content": "", * "link": "" // optional * } * } * </pre> * @param response the specified http servlet response * @throws Exception */ @RequestProcessing(value = "/console/plugins/b3log-broadcast", method = HTTPRequestMethod.POST) public void submitBroadcast(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception { if (!userQueryService.isAdminLoggedIn(request)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } final JSONRenderer renderer = new JSONRenderer(); context.setRenderer(renderer); final JSONObject ret = new JSONObject(); renderer.setJSONObject(ret); try { final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response); final JSONObject broadcast = requestJSONObject.getJSONObject("broadcast"); final JSONObject preference = preferenceQueryService.getPreference(); final String b3logKey = preference.getString(Option.ID_C_KEY_OF_SOLO); final String email = preference.getString(Option.ID_C_ADMIN_EMAIL); final String clientName = "B3log Solo"; final String clientVersion = SoloServletListener.VERSION; final String clientTitle = preference.getString(Option.ID_C_BLOG_TITLE); final String clientRuntimeEnv = Latkes.getRuntimeEnv().name(); final JSONObject broadcastRequest = new JSONObject(); broadcastRequest.put("b3logKey", b3logKey); broadcastRequest.put("email", email); broadcastRequest.put("broadcast", broadcast); broadcastRequest.put("clientRuntimeEnv", clientRuntimeEnv); broadcastRequest.put("clientTitle", clientTitle); broadcastRequest.put("clientVersion", clientVersion); broadcastRequest.put("clientName", clientName); broadcastRequest.put("clientHost", Latkes.getServePath()); final HTTPRequest httpRequest = new HTTPRequest(); httpRequest.setURL(ADD_BROADCAST_URL); httpRequest.setRequestMethod(HTTPRequestMethod.POST); httpRequest.setPayload(broadcastRequest.toString().getBytes("UTF-8")); @SuppressWarnings("unchecked") final Future<HTTPResponse> future = (Future<HTTPResponse>) urlFetchService.fetchAsync(httpRequest); final HTTPResponse result = future.get(); if (HttpServletResponse.SC_OK == result.getResponseCode()) { ret.put(Keys.STATUS_CODE, true); optionMgmtService.removeOption(Option.ID_C_BROADCAST_CHANCE_EXPIRATION_TIME); LOGGER.info("Submits broadcast successfully"); return; } ret.put(Keys.STATUS_CODE, false); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Submits broadcast failed", e); final JSONObject jsonObject = QueryResults.defaultResult(); renderer.setJSONObject(jsonObject); jsonObject.put(Keys.MSG, e.getMessage()); } } }
apache-2.0
calrissian/flowmix
src/main/java/org/calrissian/flowmix/api/filter/NoFilter.java
917
/* * Copyright (C) 2014 The Calrissian Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.calrissian.flowmix.api.filter; import org.calrissian.flowmix.api.Filter; import org.calrissian.mango.domain.event.Event; /** * A filter that accepts everything passed through it */ public class NoFilter implements Filter { @Override public boolean accept(Event event) { return true; } }
apache-2.0
Activiti/Activiti
activiti-core/activiti-engine/src/test/java/org/activiti/standalone/history/VariableUpdateDelegate.java
940
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.standalone.history; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.JavaDelegate; /** */ public class VariableUpdateDelegate implements JavaDelegate { public void execute(DelegateExecution execution) { execution.setVariable("zzz", 123456789L); } }
apache-2.0
tltv/gantt
gantt-addon/src/main/java/org/tltv/gantt/client/shared/SubStep.java
1043
/* * Copyright 2015 Tomi Virtanen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tltv.gantt.client.shared; public class SubStep extends AbstractStep { public SubStep() { } public SubStep(String caption) { super(caption); } public SubStep(String caption, CaptionMode captionMode) { super(caption, captionMode); } private Step owner; public Step getOwner() { return owner; } protected void setOwner(Step owner) { this.owner = owner; } }
apache-2.0
LaiHouWen/ProjectAll
android-huaxing-cust1.0/pickerview/src/main/java/com/huaxiafinance/lc/pickerview/TimePickerView.java
4979
package com.huaxiafinance.lc.pickerview; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.huaxiafinance.lc.pickerview.view.BasePickerView; import com.huaxiafinance.lc.pickerview.view.WheelTime; import java.text.ParseException; import java.util.Calendar; import java.util.Date; /** * 时间选择器 * Created by Sai on 15/11/22. */ public class TimePickerView extends BasePickerView implements View.OnClickListener { public enum Type { ALL, YEAR_MONTH_DAY, HOURS_MINS, MONTH_DAY_HOUR_MIN, YEAR_MONTH }// 四种选择模式,年月日时分,年月日,时分,月日时分 WheelTime wheelTime; private View btnSubmit, btnCancel; private TextView tvTitle; private static final String TAG_SUBMIT = "submit"; private static final String TAG_CANCEL = "cancel"; private OnTimeSelectListener timeSelectListener; public TimePickerView(Context context, Type type) { super(context); LayoutInflater.from(context).inflate(R.layout.pickerview_time, contentContainer); // -----确定和取消按钮 btnSubmit = findViewById(R.id.btnSubmit); btnSubmit.setTag(TAG_SUBMIT); btnCancel = findViewById(R.id.btnCancel); btnCancel.setTag(TAG_CANCEL); btnSubmit.setOnClickListener(this); btnCancel.setOnClickListener(this); //顶部标题 tvTitle = (TextView) findViewById(R.id.tvTitle); // ----时间转轮 final View timepickerview = findViewById(R.id.timepicker); wheelTime = new WheelTime(timepickerview, type); //默认选中当前时间 Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hours = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); wheelTime.setPicker(year, month, day, hours, minute); } /** * 设置可以选择的时间范围 * 要在setTime之前调用才有效果 * * @param startYear 开始年份 * @param endYear 结束年份 */ public void setRange(int startYear, int endYear) { wheelTime.setStartYear(startYear); wheelTime.setEndYear(endYear); } /** * 设置选中时间 * * @param date 时间 */ public void setTime(Date date) { Calendar calendar = Calendar.getInstance(); if (date == null) calendar.setTimeInMillis(System.currentTimeMillis()); else calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hours = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); wheelTime.setPicker(year, month, day, hours, minute); } // /** // * 指定选中的时间,显示选择器 // * // * @param date // */ // public void show(Date date) { // Calendar calendar = Calendar.getInstance(); // if (date == null) // calendar.setTimeInMillis(System.currentTimeMillis()); // else // calendar.setTime(date); // int year = calendar.get(Calendar.YEAR); // int month = calendar.get(Calendar.MONTH); // int day = calendar.get(Calendar.DAY_OF_MONTH); // int hours = calendar.get(Calendar.HOUR_OF_DAY); // int minute = calendar.get(Calendar.MINUTE); // wheelTime.setPicker(year, month, day, hours, minute); // show(); // } /** * 设置是否循环滚动 * * @param cyclic 是否循环 */ public void setCyclic(boolean cyclic) { wheelTime.setCyclic(cyclic); } @Override public void onClick(View v) { String tag = (String) v.getTag(); if (tag.equals(TAG_CANCEL)) { dismiss(); return; } else { if (timeSelectListener != null) { try { Date date = WheelTime.dateFormat.parse(wheelTime.getTime()); timeSelectListener.onTimeSelect(date); if (date.getTime() > new Date().getTime()) { return; } } catch (ParseException e) { e.printStackTrace(); } } dismiss(); return; } } public interface OnTimeSelectListener { void onTimeSelect(Date date); } public void setOnTimeSelectListener(OnTimeSelectListener timeSelectListener) { this.timeSelectListener = timeSelectListener; } public void setTitle(String title) { tvTitle.setText(title); } }
apache-2.0
gerdriesselmann/netty
testsuite/src/main/java/io/netty/testsuite/transport/socket/TrafficShapingHandlerTest.java
22509
/* * Copyright 2012 The Netty Project * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.testsuite.transport.socket; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.SocketChannel; import io.netty.handler.traffic.AbstractTrafficShapingHandler; import io.netty.handler.traffic.ChannelTrafficShapingHandler; import io.netty.handler.traffic.GlobalTrafficShapingHandler; import io.netty.handler.traffic.TrafficCounter; import io.netty.util.concurrent.DefaultEventExecutorGroup; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Promise; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.*; public class TrafficShapingHandlerTest extends AbstractSocketTest { private static final InternalLogger logger = InternalLoggerFactory.getInstance(TrafficShapingHandlerTest.class); private static final InternalLogger loggerServer = InternalLoggerFactory.getInstance("ServerTSH"); private static final InternalLogger loggerClient = InternalLoggerFactory.getInstance("ClientTSH"); static final int messageSize = 1024; static final int bandwidthFactor = 12; static final int minfactor = 3; static final int maxfactor = bandwidthFactor + bandwidthFactor / 2; static final long stepms = (1000 / bandwidthFactor - 10) / 10 * 10; static final long minimalms = Math.max(stepms / 2, 20) / 10 * 10; static final long check = 10; private static final Random random = new Random(); static final byte[] data = new byte[messageSize]; private static final String TRAFFIC = "traffic"; private static String currentTestName; private static int currentTestRun; private static EventExecutorGroup group; private static EventExecutorGroup groupForGlobal; private static final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); static { random.nextBytes(data); } @BeforeClass public static void createGroup() { logger.info("Bandwidth: " + minfactor + " <= " + bandwidthFactor + " <= " + maxfactor + " StepMs: " + stepms + " MinMs: " + minimalms + " CheckMs: " + check); group = new DefaultEventExecutorGroup(8); groupForGlobal = new DefaultEventExecutorGroup(8); } @AfterClass public static void destroyGroup() throws Exception { group.shutdownGracefully().sync(); groupForGlobal.shutdownGracefully().sync(); executor.shutdown(); } private static long[] computeWaitRead(int[] multipleMessage) { long[] minimalWaitBetween = new long[multipleMessage.length + 1]; minimalWaitBetween[0] = 0; for (int i = 0; i < multipleMessage.length; i++) { if (multipleMessage[i] > 1) { minimalWaitBetween[i + 1] = (multipleMessage[i] - 1) * stepms + minimalms; } else { minimalWaitBetween[i + 1] = 10; } } return minimalWaitBetween; } private static long[] computeWaitWrite(int[] multipleMessage) { long[] minimalWaitBetween = new long[multipleMessage.length + 1]; for (int i = 0; i < multipleMessage.length; i++) { if (multipleMessage[i] > 1) { minimalWaitBetween[i] = (multipleMessage[i] - 1) * stepms + minimalms; } else { minimalWaitBetween[i] = 10; } } return minimalWaitBetween; } private static long[] computeWaitAutoRead(int []autoRead) { long [] minimalWaitBetween = new long[autoRead.length + 1]; minimalWaitBetween[0] = 0; for (int i = 0; i < autoRead.length; i++) { if (autoRead[i] != 0) { if (autoRead[i] > 0) { minimalWaitBetween[i + 1] = -1; } else { minimalWaitBetween[i + 1] = check; } } else { minimalWaitBetween[i + 1] = 0; } } return minimalWaitBetween; } @Test(timeout = 10000) public void testNoTrafficShapping() throws Throwable { currentTestName = "TEST NO TRAFFIC"; currentTestRun = 0; run(); } public void testNoTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1 }; long[] minimalWaitBetween = null; testTrafficShapping0(sb, cb, false, false, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testWriteTrafficShapping() throws Throwable { currentTestName = "TEST WRITE"; currentTestRun = 0; run(); } public void testWriteTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitWrite(multipleMessage); testTrafficShapping0(sb, cb, false, false, true, false, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testReadTrafficShapping() throws Throwable { currentTestName = "TEST READ"; currentTestRun = 0; run(); } public void testReadTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitRead(multipleMessage); testTrafficShapping0(sb, cb, false, true, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testWrite1TrafficShapping() throws Throwable { currentTestName = "TEST WRITE"; currentTestRun = 0; run(); } public void testWrite1TrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 1, 1 }; long[] minimalWaitBetween = computeWaitWrite(multipleMessage); testTrafficShapping0(sb, cb, false, false, true, false, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testRead1TrafficShapping() throws Throwable { currentTestName = "TEST READ"; currentTestRun = 0; run(); } public void testRead1TrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 1, 1 }; long[] minimalWaitBetween = computeWaitRead(multipleMessage); testTrafficShapping0(sb, cb, false, true, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testWriteGlobalTrafficShapping() throws Throwable { currentTestName = "TEST GLOBAL WRITE"; currentTestRun = 0; run(); } public void testWriteGlobalTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitWrite(multipleMessage); testTrafficShapping0(sb, cb, false, false, true, true, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testReadGlobalTrafficShapping() throws Throwable { currentTestName = "TEST GLOBAL READ"; currentTestRun = 0; run(); } public void testReadGlobalTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = null; int[] multipleMessage = { 1, 2, 1, 1 }; long[] minimalWaitBetween = computeWaitRead(multipleMessage); testTrafficShapping0(sb, cb, false, true, false, true, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testAutoReadTrafficShapping() throws Throwable { currentTestName = "TEST AUTO READ"; currentTestRun = 0; run(); } public void testAutoReadTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = { 1, -1, -1, 1, -2, 0, 1, 0, -3, 0, 1, 2, 0 }; int[] multipleMessage = new int[autoRead.length]; Arrays.fill(multipleMessage, 1); long[] minimalWaitBetween = computeWaitAutoRead(autoRead); testTrafficShapping0(sb, cb, false, true, false, false, autoRead, minimalWaitBetween, multipleMessage); } @Test(timeout = 10000) public void testAutoReadGlobalTrafficShapping() throws Throwable { currentTestName = "TEST AUTO READ GLOBAL"; currentTestRun = 0; run(); } public void testAutoReadGlobalTrafficShapping(ServerBootstrap sb, Bootstrap cb) throws Throwable { int[] autoRead = { 1, -1, -1, 1, -2, 0, 1, 0, -3, 0, 1, 2, 0 }; int[] multipleMessage = new int[autoRead.length]; Arrays.fill(multipleMessage, 1); long[] minimalWaitBetween = computeWaitAutoRead(autoRead); testTrafficShapping0(sb, cb, false, true, false, true, autoRead, minimalWaitBetween, multipleMessage); } /** * * @param additionalExecutor * shall the pipeline add the handler using an additional executor * @param limitRead * True to set Read Limit on Server side * @param limitWrite * True to set Write Limit on Client side * @param globalLimit * True to change Channel to Global TrafficShapping * @param minimalWaitBetween * time in ms that should be waited before getting the final result (note: for READ the values are * right shifted once, the first value being 0) * @param multipleMessage * how many message to send at each step (for READ: the first should be 1, as the two last steps to * ensure correct testing) * @throws Throwable */ private static void testTrafficShapping0( ServerBootstrap sb, Bootstrap cb, final boolean additionalExecutor, final boolean limitRead, final boolean limitWrite, final boolean globalLimit, int[] autoRead, long[] minimalWaitBetween, int[] multipleMessage) throws Throwable { currentTestRun++; logger.info("TEST: " + currentTestName + " RUN: " + currentTestRun + " Exec: " + additionalExecutor + " Read: " + limitRead + " Write: " + limitWrite + " Global: " + globalLimit); final ServerHandler sh = new ServerHandler(autoRead, multipleMessage); Promise<Boolean> promise = group.next().newPromise(); final ClientHandler ch = new ClientHandler(promise, minimalWaitBetween, multipleMessage, autoRead); final AbstractTrafficShapingHandler handler; if (limitRead) { if (globalLimit) { handler = new GlobalTrafficShapingHandler(groupForGlobal, 0, bandwidthFactor * messageSize, check); } else { handler = new ChannelTrafficShapingHandler(0, bandwidthFactor * messageSize, check); } } else if (limitWrite) { if (globalLimit) { handler = new GlobalTrafficShapingHandler(groupForGlobal, bandwidthFactor * messageSize, 0, check); } else { handler = new ChannelTrafficShapingHandler(bandwidthFactor * messageSize, 0, check); } } else { handler = null; } sb.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel c) throws Exception { if (limitRead) { c.pipeline().addLast(TRAFFIC, handler); } c.pipeline().addLast(sh); } }); cb.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel c) throws Exception { if (limitWrite) { c.pipeline().addLast(TRAFFIC, handler); } c.pipeline().addLast(ch); } }); Channel sc = sb.bind().sync().channel(); Channel cc = cb.connect(sc.localAddress()).sync().channel(); int totalNb = 0; for (int i = 1; i < multipleMessage.length; i++) { totalNb += multipleMessage[i]; } Long start = TrafficCounter.milliSecondFromNano(); int nb = multipleMessage[0]; for (int i = 0; i < nb; i++) { cc.write(cc.alloc().buffer().writeBytes(data)); } cc.flush(); promise.await(); Long stop = TrafficCounter.milliSecondFromNano(); assertTrue("Error during execution of TrafficShapping: " + promise.cause(), promise.isSuccess()); float average = (totalNb * messageSize) / (float) (stop - start); logger.info("TEST: " + currentTestName + " RUN: " + currentTestRun + " Average of traffic: " + average + " compare to " + bandwidthFactor); sh.channel.close().sync(); ch.channel.close().sync(); sc.close().sync(); if (autoRead != null) { // for extra release call in AutoRead Thread.sleep(minimalms); } if (autoRead == null && minimalWaitBetween != null) { assertTrue("Overall Traffic not ok since > " + maxfactor + ": " + average, average <= maxfactor); if (additionalExecutor) { // Oio is not as good when using additionalExecutor assertTrue("Overall Traffic not ok since < 0.25: " + average, average >= 0.25); } else { assertTrue("Overall Traffic not ok since < " + minfactor + ": " + average, average >= minfactor); } } if (handler != null && globalLimit) { ((GlobalTrafficShapingHandler) handler).release(); } if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } private static class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> { volatile Channel channel; final AtomicReference<Throwable> exception = new AtomicReference<>(); volatile int step; // first message will always be validated private long currentLastTime = TrafficCounter.milliSecondFromNano(); private final long[] minimalWaitBetween; private final int[] multipleMessage; private final int[] autoRead; final Promise<Boolean> promise; ClientHandler(Promise<Boolean> promise, long[] minimalWaitBetween, int[] multipleMessage, int[] autoRead) { this.minimalWaitBetween = minimalWaitBetween; this.multipleMessage = Arrays.copyOf(multipleMessage, multipleMessage.length); this.promise = promise; this.autoRead = autoRead; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channel = ctx.channel(); } @Override public void messageReceived(ChannelHandlerContext ctx, ByteBuf in) throws Exception { long lastTimestamp = 0; loggerClient.debug("Step: " + step + " Read: " + in.readableBytes() / 8 + " blocks"); while (in.isReadable()) { lastTimestamp = in.readLong(); multipleMessage[step]--; } if (multipleMessage[step] > 0) { // still some message to get return; } long minimalWait = minimalWaitBetween != null? minimalWaitBetween[step] : 0; int ar = 0; if (autoRead != null) { if (step > 0 && autoRead[step - 1] != 0) { ar = autoRead[step - 1]; } } loggerClient.info("Step: " + step + " Interval: " + (lastTimestamp - currentLastTime) + " compareTo " + minimalWait + " (" + ar + ')'); assertTrue("The interval of time is incorrect:" + (lastTimestamp - currentLastTime) + " not> " + minimalWait, lastTimestamp - currentLastTime >= minimalWait); currentLastTime = lastTimestamp; step++; if (multipleMessage.length > step) { int nb = multipleMessage[step]; for (int i = 0; i < nb; i++) { channel.write(channel.alloc().buffer().writeBytes(data)); } channel.flush(); } else { promise.setSuccess(true); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (exception.compareAndSet(null, cause)) { cause.printStackTrace(); promise.setFailure(cause); ctx.close(); } } } private static class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> { private final int[] autoRead; private final int[] multipleMessage; volatile Channel channel; volatile int step; final AtomicReference<Throwable> exception = new AtomicReference<>(); ServerHandler(int[] autoRead, int[] multipleMessage) { this.autoRead = autoRead; this.multipleMessage = Arrays.copyOf(multipleMessage, multipleMessage.length); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channel = ctx.channel(); } @Override public void messageReceived(final ChannelHandlerContext ctx, ByteBuf in) throws Exception { byte[] actual = new byte[in.readableBytes()]; int nb = actual.length / messageSize; loggerServer.info("Step: " + step + " Read: " + nb + " blocks"); in.readBytes(actual); long timestamp = TrafficCounter.milliSecondFromNano(); int isAutoRead = 0; int laststep = step; for (int i = 0; i < nb; i++) { multipleMessage[step]--; if (multipleMessage[step] == 0) { // setAutoRead test if (autoRead != null) { isAutoRead = autoRead[step]; } step++; } } if (laststep != step) { // setAutoRead test if (autoRead != null && isAutoRead != 2) { if (isAutoRead != 0) { loggerServer.info("Step: " + step + " Set AutoRead: " + (isAutoRead > 0)); channel.config().setAutoRead(isAutoRead > 0); } else { loggerServer.info("Step: " + step + " AutoRead: NO"); } } } Thread.sleep(10); loggerServer.debug("Step: " + step + " Write: " + nb); for (int i = 0; i < nb; i++) { channel.write(Unpooled.copyLong(timestamp)); } channel.flush(); if (laststep != step) { // setAutoRead test if (isAutoRead != 0) { if (isAutoRead < 0) { final int exactStep = step; long wait = isAutoRead == -1? minimalms : stepms + minimalms; if (isAutoRead == -3) { wait = stepms * 3; } executor.schedule(() -> { loggerServer.info("Step: " + exactStep + " Reset AutoRead"); channel.config().setAutoRead(true); }, wait, TimeUnit.MILLISECONDS); } else { if (isAutoRead > 1) { loggerServer.debug("Step: " + step + " Will Set AutoRead: True"); final int exactStep = step; executor.schedule(() -> { loggerServer.info("Step: " + exactStep + " Set AutoRead: True"); channel.config().setAutoRead(true); }, stepms + minimalms, TimeUnit.MILLISECONDS); } } } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (exception.compareAndSet(null, cause)) { cause.printStackTrace(); ctx.close(); } } } }
apache-2.0
xjtu3c/GranuleJ
GOP/GranuleJIDE/src/AST/CONSTANT_Float_Info.java
1401
package AST; import java.util.HashSet; import java.util.LinkedHashSet; import java.io.File; import java.util.*; import beaver.*; import java.util.ArrayList; import java.util.zip.*; import java.io.*; import java.util.Stack; import java.util.regex.Pattern; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Element; import org.w3c.dom.Document; import java.util.HashMap; import java.util.Map.Entry; import javax.xml.transform.TransformerException; import javax.xml.parsers.ParserConfigurationException; import java.util.Collection; /** * @ast class * @declaredat :0 */ public class CONSTANT_Float_Info extends CONSTANT_Info { public float value; public CONSTANT_Float_Info(BytecodeParser parser) { super(parser); value = p.readFloat(); } public String toString() { return "FloatInfo: " + Float.toString(value); } public Expr expr() { return Literal.buildFloatLiteral(value); } }
apache-2.0
rdblue/parquet-mr
parquet-column/src/main/java/org/apache/parquet/io/MessageColumnIO.java
19368
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.parquet.io; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.parquet.column.ColumnWriteStore; import org.apache.parquet.column.ColumnWriter; import org.apache.parquet.column.impl.ColumnReadStoreImpl; import org.apache.parquet.column.page.PageReadStore; import org.apache.parquet.filter.UnboundRecordFilter; import org.apache.parquet.filter2.compat.FilterCompat; import org.apache.parquet.filter2.compat.FilterCompat.Filter; import org.apache.parquet.filter2.compat.FilterCompat.FilterPredicateCompat; import org.apache.parquet.filter2.compat.FilterCompat.NoOpFilter; import org.apache.parquet.filter2.compat.FilterCompat.UnboundRecordFilterCompat; import org.apache.parquet.filter2.compat.FilterCompat.Visitor; import org.apache.parquet.filter2.predicate.FilterPredicate; import org.apache.parquet.filter2.recordlevel.FilteringRecordMaterializer; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate; import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicateBuilder; import org.apache.parquet.io.api.Binary; import org.apache.parquet.io.api.RecordConsumer; import org.apache.parquet.io.api.RecordMaterializer; import org.apache.parquet.schema.MessageType; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.parquet.Preconditions.checkNotNull; /** * Message level of the IO structure * * * @author Julien Le Dem */ public class MessageColumnIO extends GroupColumnIO { private static final Logger LOG = LoggerFactory.getLogger(MessageColumnIO.class); private static final boolean DEBUG = LOG.isDebugEnabled(); private List<PrimitiveColumnIO> leaves; private final boolean validating; private final String createdBy; MessageColumnIO(MessageType messageType, boolean validating, String createdBy) { super(messageType, null, 0); this.validating = validating; this.createdBy = createdBy; } public List<String[]> getColumnNames() { return super.getColumnNames(); } public <T> RecordReader<T> getRecordReader(PageReadStore columns, RecordMaterializer<T> recordMaterializer) { return getRecordReader(columns, recordMaterializer, FilterCompat.NOOP); } /** * @deprecated use {@link #getRecordReader(PageReadStore, RecordMaterializer, Filter)} */ @Deprecated public <T> RecordReader<T> getRecordReader(PageReadStore columns, RecordMaterializer<T> recordMaterializer, UnboundRecordFilter filter) { return getRecordReader(columns, recordMaterializer, FilterCompat.get(filter)); } public <T> RecordReader<T> getRecordReader(final PageReadStore columns, final RecordMaterializer<T> recordMaterializer, final Filter filter) { checkNotNull(columns, "columns"); checkNotNull(recordMaterializer, "recordMaterializer"); checkNotNull(filter, "filter"); if (leaves.isEmpty()) { return new EmptyRecordReader<T>(recordMaterializer); } return filter.accept(new Visitor<RecordReader<T>>() { @Override public RecordReader<T> visit(FilterPredicateCompat filterPredicateCompat) { FilterPredicate predicate = filterPredicateCompat.getFilterPredicate(); IncrementallyUpdatedFilterPredicateBuilder builder = new IncrementallyUpdatedFilterPredicateBuilder(); IncrementallyUpdatedFilterPredicate streamingPredicate = builder.build(predicate); RecordMaterializer<T> filteringRecordMaterializer = new FilteringRecordMaterializer<T>( recordMaterializer, leaves, builder.getValueInspectorsByColumn(), streamingPredicate); return new RecordReaderImplementation<T>( MessageColumnIO.this, filteringRecordMaterializer, validating, new ColumnReadStoreImpl(columns, filteringRecordMaterializer.getRootConverter(), getType(), createdBy)); } @Override public RecordReader<T> visit(UnboundRecordFilterCompat unboundRecordFilterCompat) { return new FilteredRecordReader<T>( MessageColumnIO.this, recordMaterializer, validating, new ColumnReadStoreImpl(columns, recordMaterializer.getRootConverter(), getType(), createdBy), unboundRecordFilterCompat.getUnboundRecordFilter(), columns.getRowCount() ); } @Override public RecordReader<T> visit(NoOpFilter noOpFilter) { return new RecordReaderImplementation<T>( MessageColumnIO.this, recordMaterializer, validating, new ColumnReadStoreImpl(columns, recordMaterializer.getRootConverter(), getType(), createdBy)); } }); } /** * To improve null writing performance, we cache null values on group nodes. We flush nulls when a * non-null value hits the group node. * * Intuitively, when a group node hits a null value, all the leaves underneath it should be null. * A direct way of doing it is to write nulls for all the leaves underneath it when a group node * is null. This approach is not optimal, consider following case: * * - When the schema is really wide where for each group node, there are thousands of leaf * nodes underneath it. * - When the data being written is really sparse, group nodes could hit nulls frequently. * * With the direct approach, if a group node hit null values a thousand times, and there are a * thousand nodes underneath it. * For each null value, it iterates over a thousand leaf writers to write null values and it * will do it for a thousand null values. * * In the above case, each leaf writer maintains it's own buffer of values, calling thousands of * them in turn is very bad for memory locality. Instead each group node can remember the null values * encountered and flush only when a non-null value hits the group node. In this way, when we flush * null values, we only iterate through all the leaves 1 time and multiple cached null values are * flushed to each leaf in a tight loop. This implementation has following characteristics. * * 1. When a group node hits a null value, it adds the repetition level of the null value to * the groupNullCache. The definition level of the cached nulls should always be the same as * the definition level of the group node so there is no need to store it. * * 2. When a group node hits a non null value and it has null value cached, it should flush null * values and start from his children group nodes first. This make sure the order of null values * being flushed is correct. * */ private class MessageColumnIORecordConsumer extends RecordConsumer { private ColumnIO currentColumnIO; private int currentLevel = 0; private class FieldsMarker { private BitSet vistedIndexes = new BitSet(); @Override public String toString() { return "VistedIndex{" + "vistedIndexes=" + vistedIndexes + '}'; } public void reset(int fieldsCount) { this.vistedIndexes.clear(0, fieldsCount); } public void markWritten(int i) { vistedIndexes.set(i); } public boolean isWritten(int i) { return vistedIndexes.get(i); } } //track at each level of depth, which fields are written, so nulls can be inserted for the unwritten fields private final FieldsMarker[] fieldsWritten; private final int[] r; private final ColumnWriter[] columnWriter; /** * Maintain a map of groups and all the leaf nodes underneath it. It's used to optimize writing null for a group node. * Instead of using recursion calls, all the leaves can be called directly without traversing the sub tree of the group node */ private Map<GroupColumnIO, List<ColumnWriter>> groupToLeafWriter = new HashMap<GroupColumnIO, List<ColumnWriter>>(); /* * Cache nulls for each group node. It only stores the repetition level, since the definition level * should always be the definition level of the group node. */ private Map<GroupColumnIO, IntArrayList> groupNullCache = new HashMap<GroupColumnIO, IntArrayList>(); private final ColumnWriteStore columns; private boolean emptyField = true; private void buildGroupToLeafWriterMap(PrimitiveColumnIO primitive, ColumnWriter writer) { GroupColumnIO parent = primitive.getParent(); do { getLeafWriters(parent).add(writer); parent = parent.getParent(); } while (parent != null); } private List<ColumnWriter> getLeafWriters(GroupColumnIO group) { List<ColumnWriter> writers = groupToLeafWriter.get(group); if (writers == null) { writers = new ArrayList<ColumnWriter>(); groupToLeafWriter.put(group, writers); } return writers; } public MessageColumnIORecordConsumer(ColumnWriteStore columns) { this.columns = columns; int maxDepth = 0; this.columnWriter = new ColumnWriter[MessageColumnIO.this.getLeaves().size()]; for (PrimitiveColumnIO primitiveColumnIO : MessageColumnIO.this.getLeaves()) { ColumnWriter w = columns.getColumnWriter(primitiveColumnIO.getColumnDescriptor()); maxDepth = Math.max(maxDepth, primitiveColumnIO.getFieldPath().length); columnWriter[primitiveColumnIO.getId()] = w; buildGroupToLeafWriterMap(primitiveColumnIO, w); } fieldsWritten = new FieldsMarker[maxDepth]; for (int i = 0; i < maxDepth; i++) { fieldsWritten[i] = new FieldsMarker(); } r = new int[maxDepth]; } private void printState() { if (DEBUG) { log(currentLevel + ", " + fieldsWritten[currentLevel] + ": " + Arrays.toString(currentColumnIO.getFieldPath()) + " r:" + r[currentLevel]); if (r[currentLevel] > currentColumnIO.getRepetitionLevel()) { // sanity check throw new InvalidRecordException(r[currentLevel] + "(r) > " + currentColumnIO.getRepetitionLevel() + " ( schema r)"); } } } private void log(Object message, Object...parameters) { if (DEBUG) { String indent = ""; for (int i = 0; i < currentLevel; ++i) { indent += " "; } LOG.debug(indent + message, parameters); } } @Override public void startMessage() { if (DEBUG) log("< MESSAGE START >"); currentColumnIO = MessageColumnIO.this; r[0] = 0; int numberOfFieldsToVisit = ((GroupColumnIO) currentColumnIO).getChildrenCount(); fieldsWritten[0].reset(numberOfFieldsToVisit); if (DEBUG) printState(); } @Override public void endMessage() { writeNullForMissingFieldsAtCurrentLevel(); columns.endRecord(); if (DEBUG) log("< MESSAGE END >"); if (DEBUG) printState(); } @Override public void startField(String field, int index) { try { if (DEBUG) log("startField({}, {})", field, index); currentColumnIO = ((GroupColumnIO) currentColumnIO).getChild(index); emptyField = true; if (DEBUG) printState(); } catch (RuntimeException e) { throw new ParquetEncodingException("error starting field " + field + " at " + index, e); } } @Override public void endField(String field, int index) { if (DEBUG) log("endField({}, {})",field ,index); currentColumnIO = currentColumnIO.getParent(); if (emptyField) { throw new ParquetEncodingException("empty fields are illegal, the field should be ommited completely instead"); } fieldsWritten[currentLevel].markWritten(index); r[currentLevel] = currentLevel == 0 ? 0 : r[currentLevel - 1]; if (DEBUG) printState(); } private void writeNullForMissingFieldsAtCurrentLevel() { int currentFieldsCount = ((GroupColumnIO) currentColumnIO).getChildrenCount(); for (int i = 0; i < currentFieldsCount; i++) { if (!fieldsWritten[currentLevel].isWritten(i)) { try { ColumnIO undefinedField = ((GroupColumnIO) currentColumnIO).getChild(i); int d = currentColumnIO.getDefinitionLevel(); if (DEBUG) log(Arrays.toString(undefinedField.getFieldPath()) + ".writeNull(" + r[currentLevel] + "," + d + ")"); writeNull(undefinedField, r[currentLevel], d); } catch (RuntimeException e) { throw new ParquetEncodingException("error while writing nulls for fields of indexes " + i + " . current index: " + fieldsWritten[currentLevel], e); } } } } private void writeNull(ColumnIO undefinedField, int r, int d) { if (undefinedField.getType().isPrimitive()) { columnWriter[((PrimitiveColumnIO) undefinedField).getId()].writeNull(r, d); } else { GroupColumnIO groupColumnIO = (GroupColumnIO) undefinedField; // only cache the repetition level, the definition level should always be the definition level of the parent node cacheNullForGroup(groupColumnIO, r); } } private void cacheNullForGroup(GroupColumnIO group, int r) { IntArrayList nulls = groupNullCache.get(group); if (nulls == null) { nulls = new IntArrayList(); groupNullCache.put(group, nulls); } nulls.add(r); } private void writeNullToLeaves(GroupColumnIO group) { IntArrayList nullCache = groupNullCache.get(group); if (nullCache == null || nullCache.isEmpty()) return; int parentDefinitionLevel = group.getParent().getDefinitionLevel(); for (ColumnWriter leafWriter : groupToLeafWriter.get(group)) { for (IntIterator iter = nullCache.iterator(); iter.hasNext();) { int repetitionLevel = iter.nextInt(); leafWriter.writeNull(repetitionLevel, parentDefinitionLevel); } } nullCache.clear(); } private void setRepetitionLevel() { r[currentLevel] = currentColumnIO.getRepetitionLevel(); if (DEBUG) log("r: {}", r[currentLevel]); } @Override public void startGroup() { if (DEBUG) log("startGroup()"); GroupColumnIO group = (GroupColumnIO) currentColumnIO; // current group is not null, need to flush all the nulls that were cached before if (hasNullCache(group)) { flushCachedNulls(group); } ++currentLevel; r[currentLevel] = r[currentLevel - 1]; int fieldsCount = ((GroupColumnIO) currentColumnIO).getChildrenCount(); fieldsWritten[currentLevel].reset(fieldsCount); if (DEBUG) printState(); } private boolean hasNullCache(GroupColumnIO group) { IntArrayList nulls = groupNullCache.get(group); return nulls != null && !nulls.isEmpty(); } private void flushCachedNulls(GroupColumnIO group) { //flush children first for (int i = 0; i < group.getChildrenCount(); i++) { ColumnIO child = group.getChild(i); if (child instanceof GroupColumnIO) { flushCachedNulls((GroupColumnIO) child); } } //then flush itself writeNullToLeaves(group); } @Override public void endGroup() { if (DEBUG) log("endGroup()"); emptyField = false; writeNullForMissingFieldsAtCurrentLevel(); --currentLevel; setRepetitionLevel(); if (DEBUG) printState(); } private ColumnWriter getColumnWriter() { return columnWriter[((PrimitiveColumnIO) currentColumnIO).getId()]; } @Override public void addInteger(int value) { if (DEBUG) log("addInt({})", value); emptyField = false; getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel()); setRepetitionLevel(); if (DEBUG) printState(); } @Override public void addLong(long value) { if (DEBUG) log("addLong({})", value); emptyField = false; getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel()); setRepetitionLevel(); if (DEBUG) printState(); } @Override public void addBoolean(boolean value) { if (DEBUG) log("addBoolean({})", value); emptyField = false; getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel()); setRepetitionLevel(); if (DEBUG) printState(); } @Override public void addBinary(Binary value) { if (DEBUG) log("addBinary({} bytes)", value.length()); emptyField = false; getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel()); setRepetitionLevel(); if (DEBUG) printState(); } @Override public void addFloat(float value) { if (DEBUG) log("addFloat({})", value); emptyField = false; getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel()); setRepetitionLevel(); if (DEBUG) printState(); } @Override public void addDouble(double value) { if (DEBUG) log("addDouble({})", value); emptyField = false; getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel()); setRepetitionLevel(); if (DEBUG) printState(); } /** * Flush null for all groups */ @Override public void flush() { flushCachedNulls(MessageColumnIO.this); } } public RecordConsumer getRecordWriter(ColumnWriteStore columns) { RecordConsumer recordWriter = new MessageColumnIORecordConsumer(columns); if (DEBUG) recordWriter = new RecordConsumerLoggingWrapper(recordWriter); return validating ? new ValidatingRecordConsumer(recordWriter, getType()) : recordWriter; } void setLevels() { setLevels(0, 0, new String[0], new int[0], Arrays.<ColumnIO>asList(this), Arrays.<ColumnIO>asList(this)); } void setLeaves(List<PrimitiveColumnIO> leaves) { this.leaves = leaves; } public List<PrimitiveColumnIO> getLeaves() { return this.leaves; } @Override public MessageType getType() { return (MessageType) super.getType(); } }
apache-2.0
lianying/asdf
src/main/java/com/taobao/api/request/ProductsGetRequest.java
2739
package com.taobao.api.request; import com.taobao.api.internal.util.RequestCheckUtils; import java.util.Map; import com.taobao.api.TaobaoRequest; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.response.ProductsGetResponse; import com.taobao.api.ApiRuleException; /** * TOP API: taobao.products.get request * * @author auto create * @since 1.0, 2013-03-14 16:30:14 */ public class ProductsGetRequest implements TaobaoRequest<ProductsGetResponse> { private TaobaoHashMap udfParams; // add user-defined text parameters private Long timestamp; /** * 需返回的字段列表.可选值:Product数据结构中的所有字段;多个字段之间用","分隔 */ private String fields; /** * 用户昵称 */ private String nick; /** * 页码.传入值为1代表第一页,传入值为2代表第二页,依此类推.默认返回的数据是从第一页开始. */ private Long pageNo; /** * 每页条数.每页返回最多返回100条,默认值为40 */ private Long pageSize; public void setFields(String fields) { this.fields = fields; } public String getFields() { return this.fields; } public void setNick(String nick) { this.nick = nick; } public String getNick() { return this.nick; } public void setPageNo(Long pageNo) { this.pageNo = pageNo; } public Long getPageNo() { return this.pageNo; } public void setPageSize(Long pageSize) { this.pageSize = pageSize; } public Long getPageSize() { return this.pageSize; } private Map<String,String> headerMap=new TaobaoHashMap(); public Long getTimestamp() { return this.timestamp; } public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } public String getApiMethodName() { return "taobao.products.get"; } public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("fields", this.fields); txtParams.put("nick", this.nick); txtParams.put("page_no", this.pageNo); txtParams.put("page_size", this.pageSize); if(this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new TaobaoHashMap(); } this.udfParams.put(key, value); } public Class<ProductsGetResponse> getResponseClass() { return ProductsGetResponse.class; } public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(fields,"fields"); RequestCheckUtils.checkNotEmpty(nick,"nick"); } public Map<String,String> getHeaderMap() { return headerMap; } }
apache-2.0
tlarzabal/IHM
JavaFX/src/main/java/fr/polytech/ihm/model/produits/ListProduits.java
1187
package fr.polytech.ihm.model.produits; import fr.polytech.ihm.controller.produits.ListProduitsController; import fr.polytech.ihm.controller.produits.UnProduitController; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.ListCell; import java.io.IOException; /** * Created by thiba on 03/03/2017. */ public class ListProduits extends ListCell<Produit[]> { @Override protected void updateItem(Produit[] produits, boolean empty) { super.updateItem(produits, empty); if (produits != null) { // Load fxml file for this internship try { String fxmlFile = "/fxml/produits/paneListProduits.fxml"; FXMLLoader loader = new FXMLLoader(); Parent listElement = loader.load(getClass().getResourceAsStream(fxmlFile)); for(Produit produit : produits) ((ListProduitsController) loader.getController()).init(produit); // Display content of the fxml file this.setGraphic(listElement); } catch (IOException e) { e.printStackTrace(); } } } }
apache-2.0
ChangerYoung/alluxio
core/server/master/src/test/java/alluxio/master/file/meta/InodeTreeTest.java
29711
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.file.meta; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import alluxio.AlluxioURI; import alluxio.ConfigurationRule; import alluxio.Constants; import alluxio.PropertyKey; import alluxio.exception.BlockInfoException; import alluxio.exception.ExceptionMessage; import alluxio.exception.FileAlreadyExistsException; import alluxio.exception.FileDoesNotExistException; import alluxio.exception.InvalidPathException; import alluxio.master.MasterRegistry; import alluxio.master.block.BlockMaster; import alluxio.master.block.BlockMasterFactory; import alluxio.master.file.options.CreateDirectoryOptions; import alluxio.master.file.options.CreateFileOptions; import alluxio.master.file.options.CreatePathOptions; import alluxio.master.file.options.DeleteOptions; import alluxio.master.journal.JournalContext; import alluxio.master.journal.JournalSystem; import alluxio.master.journal.NoopJournalContext; import alluxio.master.journal.noop.NoopJournalSystem; import alluxio.security.authorization.Mode; import alluxio.underfs.UfsManager; import alluxio.util.CommonUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Unit tests for {@link InodeTree}. */ public final class InodeTreeTest { private static final String TEST_PATH = "test"; private static final AlluxioURI TEST_URI = new AlluxioURI("/test"); private static final AlluxioURI NESTED_URI = new AlluxioURI("/nested/test"); private static final AlluxioURI NESTED_FILE_URI = new AlluxioURI("/nested/test/file"); public static final String TEST_OWNER = "user1"; public static final String TEST_GROUP = "group1"; public static final Mode TEST_DIR_MODE = new Mode((short) 0755); public static final Mode TEST_FILE_MODE = new Mode((short) 0644); private static CreateFileOptions sFileOptions; private static CreateDirectoryOptions sDirectoryOptions; private static CreateFileOptions sNestedFileOptions; private static CreateDirectoryOptions sNestedDirectoryOptions; private InodeTree mTree; private MasterRegistry mRegistry; /** Rule to create a new temporary folder during each test. */ @Rule public TemporaryFolder mTestFolder = new TemporaryFolder(); /** The exception expected to be thrown. */ @Rule public ExpectedException mThrown = ExpectedException.none(); @Rule public ConfigurationRule mConfigurationRule = new ConfigurationRule(new ImmutableMap.Builder<PropertyKey, String>() .put(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED, "true") .put(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_SUPERGROUP, "test-supergroup") .build()); /** * Sets up all dependencies before a test runs. */ @Before public void before() throws Exception { mRegistry = new MasterRegistry(); JournalSystem journalSystem = new NoopJournalSystem(); BlockMaster blockMaster = new BlockMasterFactory().create(mRegistry, journalSystem); InodeDirectoryIdGenerator directoryIdGenerator = new InodeDirectoryIdGenerator(blockMaster); UfsManager ufsManager = Mockito.mock(UfsManager.class); MountTable mountTable = new MountTable(ufsManager); mTree = new InodeTree(blockMaster, directoryIdGenerator, mountTable); mRegistry.start(true); mTree.initializeRoot(TEST_OWNER, TEST_GROUP, TEST_DIR_MODE); } @After public void after() throws Exception { mRegistry.stop(); } /** * Sets up dependencies before a single test runs. */ @BeforeClass public static void beforeClass() throws Exception { sFileOptions = CreateFileOptions.defaults().setBlockSizeBytes(Constants.KB).setOwner(TEST_OWNER) .setGroup(TEST_GROUP).setMode(TEST_FILE_MODE); sDirectoryOptions = CreateDirectoryOptions.defaults().setOwner(TEST_OWNER).setGroup(TEST_GROUP) .setMode(TEST_DIR_MODE); sNestedFileOptions = CreateFileOptions.defaults().setBlockSizeBytes(Constants.KB) .setOwner(TEST_OWNER).setGroup(TEST_GROUP).setMode(TEST_FILE_MODE).setRecursive(true); sNestedDirectoryOptions = CreateDirectoryOptions.defaults().setOwner(TEST_OWNER) .setGroup(TEST_GROUP).setMode(TEST_DIR_MODE).setRecursive(true); } /** * Tests that initializing the root twice results in the same root. */ @Test public void initializeRootTwice() throws Exception { Inode<?> root = getInodeByPath(mTree, new AlluxioURI("/")); // initializeRoot call does nothing mTree.initializeRoot(TEST_OWNER, TEST_GROUP, TEST_DIR_MODE); assertEquals(TEST_OWNER, root.getOwner()); Inode<?> newRoot = getInodeByPath(mTree, new AlluxioURI("/")); assertEquals(root, newRoot); } /** * Tests the {@link InodeTree#createPath(LockedInodePath, CreatePathOptions, JournalContext)} * method for creating directories. */ @Test public void createDirectory() throws Exception { // create directory createPath(mTree, TEST_URI, sDirectoryOptions); assertTrue(mTree.inodePathExists(TEST_URI)); Inode<?> test = getInodeByPath(mTree, TEST_URI); assertEquals(TEST_PATH, test.getName()); assertTrue(test.isDirectory()); assertEquals("user1", test.getOwner()); assertEquals("group1", test.getGroup()); assertEquals(TEST_DIR_MODE.toShort(), test.getMode()); // create nested directory createPath(mTree, NESTED_URI, sNestedDirectoryOptions); assertTrue(mTree.inodePathExists(NESTED_URI)); Inode<?> nested = getInodeByPath(mTree, NESTED_URI); assertEquals(TEST_PATH, nested.getName()); assertEquals(2, nested.getParentId()); assertTrue(test.isDirectory()); assertEquals("user1", test.getOwner()); assertEquals("group1", test.getGroup()); assertEquals(TEST_DIR_MODE.toShort(), test.getMode()); } /** * Tests that an exception is thrown when trying to create an already existing directory with the * {@code allowExists} flag set to {@code false}. */ @Test public void createExistingDirectory() throws Exception { // create directory createPath(mTree, TEST_URI, sDirectoryOptions); // create again with allowExists true createPath(mTree, TEST_URI, CreateDirectoryOptions.defaults().setAllowExists(true)); // create again with allowExists false mThrown.expect(FileAlreadyExistsException.class); mThrown.expectMessage(ExceptionMessage.FILE_ALREADY_EXISTS.getMessage(TEST_URI)); createPath(mTree, TEST_URI, CreateDirectoryOptions.defaults().setAllowExists(false)); } /** * Tests that creating a file under a pinned directory works. */ @Test public void createFileUnderPinnedDirectory() throws Exception { // create nested directory createPath(mTree, NESTED_URI, sNestedDirectoryOptions); // pin nested folder try ( LockedInodePath inodePath = mTree.lockFullInodePath(NESTED_URI, InodeTree.LockMode.WRITE)) { mTree.setPinned(inodePath, true); } // create nested file under pinned folder createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); // the nested file is pinned assertEquals(1, mTree.getPinIdSet().size()); } /** * Tests the {@link InodeTree#createPath(LockedInodePath, CreatePathOptions, JournalContext)} * method for creating a file. */ @Test public void createFile() throws Exception { // created nested file createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); Inode<?> nestedFile = getInodeByPath(mTree, NESTED_FILE_URI); assertEquals("file", nestedFile.getName()); assertEquals(2, nestedFile.getParentId()); assertTrue(nestedFile.isFile()); assertEquals("user1", nestedFile.getOwner()); assertEquals("group1", nestedFile.getGroup()); assertEquals(TEST_FILE_MODE.toShort(), nestedFile.getMode()); } /** * Tests the {@link InodeTree#createPath(LockedInodePath, CreatePathOptions, JournalContext)} * method. */ @Test public void createPathTest() throws Exception { // save the last mod time of the root long lastModTime = mTree.getRoot().getLastModificationTimeMs(); // sleep to ensure a different last modification time CommonUtils.sleepMs(10); // Need to use updated options to set the correct last mod time. CreateDirectoryOptions dirOptions = CreateDirectoryOptions.defaults().setOwner(TEST_OWNER) .setGroup(TEST_GROUP).setMode(TEST_DIR_MODE).setRecursive(true); // create nested directory InodeTree.CreatePathResult createResult = createPath(mTree, NESTED_URI, dirOptions); List<Inode<?>> modified = createResult.getModified(); List<Inode<?>> created = createResult.getCreated(); // 1 modified directory assertEquals(1, modified.size()); assertEquals("", modified.get(0).getName()); assertNotEquals(lastModTime, modified.get(0).getLastModificationTimeMs()); // 2 created directories assertEquals(2, created.size()); assertEquals("nested", created.get(0).getName()); assertEquals("test", created.get(1).getName()); // save the last mod time of 'test' lastModTime = created.get(1).getLastModificationTimeMs(); // sleep to ensure a different last modification time CommonUtils.sleepMs(10); // creating the directory path again results in no new inodes. try { createPath(mTree, NESTED_URI, dirOptions); assertTrue("createPath should throw FileAlreadyExistsException", false); } catch (FileAlreadyExistsException e) { assertEquals(e.getMessage(), ExceptionMessage.FILE_ALREADY_EXISTS.getMessage(NESTED_URI)); } // create a file CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(Constants.KB).setRecursive(true); createResult = createPath(mTree, NESTED_FILE_URI, options); modified = createResult.getModified(); created = createResult.getCreated(); // test directory was modified assertEquals(1, modified.size()); assertEquals("test", modified.get(0).getName()); assertNotEquals(lastModTime, modified.get(0).getLastModificationTimeMs()); // file was created assertEquals(1, created.size()); assertEquals("file", created.get(0).getName()); } /** * Tests that an exception is thrown when trying to create the root path twice. */ @Test public void createRootPath() throws Exception { mThrown.expect(FileAlreadyExistsException.class); mThrown.expectMessage("/"); createPath(mTree, new AlluxioURI("/"), sFileOptions); } /** * Tests that an exception is thrown when trying to create a file with invalid block size. */ @Test public void createFileWithInvalidBlockSize() throws Exception { mThrown.expect(BlockInfoException.class); mThrown.expectMessage("Invalid block size 0"); CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(0); createPath(mTree, TEST_URI, options); } /** * Tests that an exception is thrown when trying to create a file with a negative block size. */ @Test public void createFileWithNegativeBlockSize() throws Exception { mThrown.expect(BlockInfoException.class); mThrown.expectMessage("Invalid block size -1"); CreateFileOptions options = CreateFileOptions.defaults().setBlockSizeBytes(-1); createPath(mTree, TEST_URI, options); } /** * Tests that an exception is thrown when trying to create a file under a non-existing directory. */ @Test public void createFileUnderNonexistingDir() throws Exception { mThrown.expect(FileDoesNotExistException.class); mThrown.expectMessage("File /nested/test creation failed. Component 1(nested) does not exist"); createPath(mTree, NESTED_URI, sFileOptions); } /** * Tests that an exception is thrown when trying to create a file twice. */ @Test public void createFileTwice() throws Exception { mThrown.expect(FileAlreadyExistsException.class); mThrown.expectMessage("/nested/test"); createPath(mTree, NESTED_URI, sNestedFileOptions); createPath(mTree, NESTED_URI, sNestedFileOptions); } /** * Tests that an exception is thrown when trying to create a file under a file path. */ @Test public void createFileUnderFile() throws Exception { mThrown.expect(InvalidPathException.class); mThrown.expectMessage("Traversal failed. Component 2(test) is a file"); createPath(mTree, NESTED_URI, sNestedFileOptions); createPath(mTree, new AlluxioURI("/nested/test/test"), sNestedFileOptions); } /** * Tests {@link InodeTree#inodeIdExists(long)}. */ @Test public void inodeIdExists() throws Exception { assertTrue(mTree.inodeIdExists(0)); assertFalse(mTree.inodeIdExists(1)); createPath(mTree, TEST_URI, sFileOptions); Inode<?> inode = getInodeByPath(mTree, TEST_URI); assertTrue(mTree.inodeIdExists(inode.getId())); deleteInodeByPath(mTree, TEST_URI); assertFalse(mTree.inodeIdExists(inode.getId())); } /** * Tests {@link InodeTree#inodePathExists(AlluxioURI)}. */ @Test public void inodePathExists() throws Exception { assertFalse(mTree.inodePathExists(TEST_URI)); createPath(mTree, TEST_URI, sFileOptions); assertTrue(mTree.inodePathExists(TEST_URI)); deleteInodeByPath(mTree, TEST_URI); assertFalse(mTree.inodePathExists(TEST_URI)); } /** * Tests that an exception is thrown when trying to get an Inode by a non-existing path. */ @Test public void getInodeByNonexistingPath() throws Exception { mThrown.expect(FileDoesNotExistException.class); mThrown.expectMessage("Path /test does not exist"); assertFalse(mTree.inodePathExists(TEST_URI)); getInodeByPath(mTree, TEST_URI); } /** * Tests that an exception is thrown when trying to get an Inode by a non-existing, nested path. */ @Test public void getInodeByNonexistingNestedPath() throws Exception { mThrown.expect(FileDoesNotExistException.class); mThrown.expectMessage("Path /nested/test/file does not exist"); createPath(mTree, NESTED_URI, sNestedDirectoryOptions); assertFalse(mTree.inodePathExists(NESTED_FILE_URI)); getInodeByPath(mTree, NESTED_FILE_URI); } /** * Tests that an exception is thrown when trying to get an Inode with an invalid id. */ @Test public void getInodeByInvalidId() throws Exception { mThrown.expect(FileDoesNotExistException.class); mThrown.expectMessage(ExceptionMessage.INODE_DOES_NOT_EXIST.getMessage(1)); assertFalse(mTree.inodeIdExists(1)); try (LockedInodePath inodePath = mTree.lockFullInodePath(1, InodeTree.LockMode.READ)) { // inode exists } } /** * Tests the {@link InodeTree#isRootId(long)} method. */ @Test public void isRootId() { assertTrue(mTree.isRootId(0)); assertFalse(mTree.isRootId(1)); } /** * Tests the {@link InodeTree#getPath(Inode)} method. */ @Test public void getPath() throws Exception { try (LockedInodePath inodePath = mTree.lockFullInodePath(0, InodeTree.LockMode.READ)) { Inode<?> root = inodePath.getInode(); // test root path assertEquals(new AlluxioURI("/"), mTree.getPath(root)); } // test one level createPath(mTree, TEST_URI, sDirectoryOptions); try (LockedInodePath inodePath = mTree.lockFullInodePath(TEST_URI, InodeTree.LockMode.READ)) { assertEquals(new AlluxioURI("/test"), mTree.getPath(inodePath.getInode())); } // test nesting createPath(mTree, NESTED_URI, sNestedDirectoryOptions); try (LockedInodePath inodePath = mTree.lockFullInodePath(NESTED_URI, InodeTree.LockMode.READ)) { assertEquals(new AlluxioURI("/nested/test"), mTree.getPath(inodePath.getInode())); } } /** * Tests the {@link InodeTree#lockDescendants(LockedInodePath, InodeTree.LockMode)} method. */ @Test public void getInodeChildrenRecursive() throws Exception { createPath(mTree, TEST_URI, sDirectoryOptions); createPath(mTree, NESTED_URI, sNestedDirectoryOptions); // add nested file createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); // all inodes under root try (LockedInodePath inodePath = mTree.lockFullInodePath(0, InodeTree.LockMode.READ); InodeLockList lockList = mTree.lockDescendants(inodePath, InodeTree.LockMode.READ)) { List<Inode<?>> inodes = lockList.getInodes(); // /test, /nested, /nested/test, /nested/test/file assertEquals(4, inodes.size()); } } /** * Tests deleting a nested inode. */ @Test public void deleteInode() throws Exception { createPath(mTree, NESTED_URI, sNestedDirectoryOptions); // all inodes under root try (LockedInodePath inodePath = mTree.lockFullInodePath(0, InodeTree.LockMode.WRITE)) { try (InodeLockList lockList = mTree.lockDescendants(inodePath, InodeTree.LockMode.WRITE)) { List<Inode<?>> inodes = lockList.getInodes(); // /nested, /nested/test assertEquals(2, inodes.size()); } // delete the nested inode deleteInodeByPath(mTree, NESTED_URI); try (InodeLockList lockList = mTree.lockDescendants(inodePath, InodeTree.LockMode.WRITE)) { List<Inode<?>> inodes = lockList.getInodes(); // only /nested left assertEquals(1, inodes.size()); } } } /** * Tests the {@link InodeTree#setPinned(LockedInodePath, boolean)} method. */ @Test public void setPinned() throws Exception { createPath(mTree, NESTED_URI, sNestedDirectoryOptions); createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); // no inodes pinned assertEquals(0, mTree.getPinIdSet().size()); // pin nested folder try ( LockedInodePath inodePath = mTree.lockFullInodePath(NESTED_URI, InodeTree.LockMode.WRITE)) { mTree.setPinned(inodePath, true); } // nested file pinned assertEquals(1, mTree.getPinIdSet().size()); // unpin nested folder try ( LockedInodePath inodePath = mTree.lockFullInodePath(NESTED_URI, InodeTree.LockMode.WRITE)) { mTree.setPinned(inodePath, false); } assertEquals(0, mTree.getPinIdSet().size()); } /** * Tests that streaming to a journal checkpoint works. */ @Test public void streamToJournalCheckpoint() throws Exception { InodeDirectory root = mTree.getRoot(); // test root verifyJournal(mTree, Lists.<Inode<?>>newArrayList(root)); // test nested URI createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); InodeDirectory nested = (InodeDirectory) root.getChild("nested"); InodeDirectory test = (InodeDirectory) nested.getChild("test"); Inode<?> file = test.getChild("file"); verifyJournal(mTree, Arrays.asList(root, nested, test, file)); // add a sibling of test and verify journaling is in correct order (breadth first) createPath(mTree, new AlluxioURI("/nested/test1/file1"), sNestedFileOptions); InodeDirectory test1 = (InodeDirectory) nested.getChild("test1"); Inode<?> file1 = test1.getChild("file1"); verifyJournal(mTree, Arrays.asList(root, nested, test, test1, file, file1)); } /** * Tests the {@link InodeTree#addInodeFileFromJournal} and * {@link InodeTree#addInodeDirectoryFromJournal} methods. */ @Test public void addInodeFromJournal() throws Exception { createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); createPath(mTree, new AlluxioURI("/nested/test1/file1"), sNestedFileOptions); InodeDirectory root = mTree.getRoot(); InodeDirectory nested = (InodeDirectory) root.getChild("nested"); InodeDirectory test = (InodeDirectory) nested.getChild("test"); Inode<?> file = test.getChild("file"); InodeDirectory test1 = (InodeDirectory) nested.getChild("test1"); Inode<?> file1 = test1.getChild("file1"); // reset the tree mTree.addInodeDirectoryFromJournal(root.toJournalEntry().getInodeDirectory()); // re-init the root since the tree was reset above mTree.getRoot(); try (LockedInodePath inodePath = mTree.lockFullInodePath(new AlluxioURI("/"), InodeTree.LockMode.READ)) { try (InodeLockList lockList = mTree.lockDescendants(inodePath, InodeTree.LockMode.READ)) { assertEquals(0, lockList.getInodes().size()); } mTree.addInodeDirectoryFromJournal(nested.toJournalEntry().getInodeDirectory()); verifyChildrenNames(mTree, inodePath, Sets.newHashSet("nested")); mTree.addInodeDirectoryFromJournal(test.toJournalEntry().getInodeDirectory()); verifyChildrenNames(mTree, inodePath, Sets.newHashSet("nested", "test")); mTree.addInodeDirectoryFromJournal(test1.toJournalEntry().getInodeDirectory()); verifyChildrenNames(mTree, inodePath, Sets.newHashSet("nested", "test", "test1")); mTree.addInodeFileFromJournal(file.toJournalEntry().getInodeFile()); verifyChildrenNames(mTree, inodePath, Sets.newHashSet("nested", "test", "test1", "file")); mTree.addInodeFileFromJournal(file1.toJournalEntry().getInodeFile()); verifyChildrenNames(mTree, inodePath, Sets.newHashSet("nested", "test", "test1", "file", "file1")); } } @Test public void getInodePathById() throws Exception { try (LockedInodePath rootPath = mTree.lockFullInodePath(0, InodeTree.LockMode.READ)) { assertEquals(0, rootPath.getInode().getId()); } InodeTree.CreatePathResult createResult = createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); for (Inode<?> inode : createResult.getCreated()) { long id = inode.getId(); try (LockedInodePath inodePath = mTree.lockFullInodePath(id, InodeTree.LockMode.READ)) { assertEquals(id, inodePath.getInode().getId()); } } } @Test public void getInodePathByPath() throws Exception { try (LockedInodePath rootPath = mTree.lockFullInodePath(new AlluxioURI("/"), InodeTree.LockMode.READ)) { assertTrue(mTree.isRootId(rootPath.getInode().getId())); } // Create a nested file. createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); AlluxioURI uri = new AlluxioURI("/nested"); try (LockedInodePath inodePath = mTree.lockFullInodePath(uri, InodeTree.LockMode.READ)) { assertEquals(uri.getName(), inodePath.getInode().getName()); } uri = NESTED_URI; try (LockedInodePath inodePath = mTree.lockFullInodePath(uri, InodeTree.LockMode.READ)) { assertEquals(uri.getName(), inodePath.getInode().getName()); } uri = NESTED_FILE_URI; try (LockedInodePath inodePath = mTree.lockFullInodePath(uri, InodeTree.LockMode.READ)) { assertEquals(uri.getName(), inodePath.getInode().getName()); } } @Test public void tempInodePathWithNoDescendant() throws Exception { InodeTree.CreatePathResult createResult = createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); for (Inode<?> inode : createResult.getCreated()) { long id = inode.getId(); try (LockedInodePath inodePath = mTree.lockFullInodePath(id, InodeTree.LockMode.READ)) { TempInodePathForDescendant tempInodePath = new TempInodePathForDescendant(inodePath); assertEquals(inodePath.getInode(), tempInodePath.getInode()); assertEquals(inodePath.getUri(), tempInodePath.getUri()); assertEquals(inodePath.getParentInodeDirectory(), tempInodePath.getParentInodeDirectory()); assertEquals(inodePath.getInodeList(), tempInodePath.getInodeList()); assertEquals(inodePath.fullPathExists(), tempInodePath.fullPathExists()); } } } @Test public void tempInodePathWithDirectDescendant() throws Exception { InodeTree.CreatePathResult createResult = createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); Inode<?> parentInode = createResult.getCreated().get(0); assertTrue(parentInode.isDirectory()); Inode<?> childInode = createResult.getCreated().get(1); assertTrue(childInode.isDirectory()); long parentId = parentInode.getId(); long childId = childInode.getId(); AlluxioURI childUri; List<Inode<?>> childInodeList; try (LockedInodePath lockedChildPath = mTree.lockFullInodePath(childId, InodeTree.LockMode.READ)) { childUri = lockedChildPath.getUri(); childInodeList = lockedChildPath.getInodeList(); } try (LockedInodePath locked = mTree.lockFullInodePath(parentId, InodeTree.LockMode.READ)) { TempInodePathForDescendant tempInodePath = new TempInodePathForDescendant(locked); tempInodePath.setDescendant(childInode, childUri); assertEquals(childInode, tempInodePath.getInode()); assertEquals(childUri, tempInodePath.getUri()); assertEquals(true, tempInodePath.fullPathExists()); // Get inode list of the direct ancestor is support. assertEquals(childInodeList, tempInodePath.getInodeList()); // Get parent inode directory of the direct ancestor is support. assertEquals(parentInode, tempInodePath.getParentInodeDirectory()); } } @Test public void tempInodePathWithIndirectDescendant() throws Exception { InodeTree.CreatePathResult createResult = createPath(mTree, NESTED_FILE_URI, sNestedFileOptions); Inode<?> dirInode = createResult.getCreated().get(0); assertTrue(dirInode.isDirectory()); int size = createResult.getCreated().size(); assertTrue(size > 2); Inode<?> fileInode = createResult.getCreated().get(size - 1); assertTrue(fileInode.isFile()); long dirId = dirInode.getId(); long fileId = fileInode.getId(); AlluxioURI fileUri; List<Inode<?>> fileInodeList; try ( LockedInodePath lockedFilePath = mTree.lockFullInodePath(fileId, InodeTree.LockMode.READ)) { fileUri = lockedFilePath.getUri(); fileInodeList = lockedFilePath.getInodeList(); } try (LockedInodePath locked = mTree.lockFullInodePath(dirId, InodeTree.LockMode.READ)) { TempInodePathForDescendant tempInodePath = new TempInodePathForDescendant(locked); tempInodePath.setDescendant(fileInode, fileUri); assertEquals(fileInode, tempInodePath.getInode()); assertEquals(fileUri, tempInodePath.getUri()); assertEquals(true, tempInodePath.fullPathExists()); try { // Get inode list of the indirect ancestor is not support. assertEquals(fileInodeList, tempInodePath.getInodeList()); Assert.fail(); } catch (UnsupportedOperationException e) { // expected } try { // Get parent inode directory of the indirect ancestor is not support. tempInodePath.getParentInodeDirectory(); Assert.fail(); } catch (UnsupportedOperationException e) { // expected } } } // Helper to create a path. InodeTree.CreatePathResult createPath(InodeTree root, AlluxioURI path, CreatePathOptions<?> options) throws FileAlreadyExistsException, BlockInfoException, InvalidPathException, IOException, FileDoesNotExistException { try (LockedInodePath inodePath = root.lockInodePath(path, InodeTree.LockMode.WRITE)) { return root.createPath(inodePath, options, new NoopJournalContext()); } } // Helper to get an inode by path. The inode is unlocked before returning. private static Inode<?> getInodeByPath(InodeTree root, AlluxioURI path) throws Exception { try (LockedInodePath inodePath = root.lockFullInodePath(path, InodeTree.LockMode.READ)) { return inodePath.getInode(); } } // Helper to delete an inode by path. private static void deleteInodeByPath(InodeTree root, AlluxioURI path) throws Exception { try (LockedInodePath inodePath = root.lockFullInodePath(path, InodeTree.LockMode.WRITE)) { root.deleteInode(inodePath, System.currentTimeMillis(), DeleteOptions.defaults(), NoopJournalContext.INSTANCE); } } // helper for verifying that correct objects were journaled to the output stream private static void verifyJournal(InodeTree root, List<Inode<?>> journaled) throws Exception { Iterator<alluxio.proto.journal.Journal.JournalEntry> it = root.getJournalEntryIterator(); for (Inode<?> node : journaled) { assertTrue(it.hasNext()); assertEquals(node.toJournalEntry(), it.next()); } assertTrue(!it.hasNext()); } // verify that the tree has the given children private static void verifyChildrenNames(InodeTree tree, LockedInodePath inodePath, Set<String> childNames) throws Exception { try (InodeLockList lockList = tree.lockDescendants(inodePath, InodeTree.LockMode.READ)) { List<Inode<?>> children = lockList.getInodes(); assertEquals(childNames.size(), children.size()); for (Inode<?> child : children) { assertTrue(childNames.contains(child.getName())); } } } }
apache-2.0
DavidLDawes/zxing
android/app/src/main/java/com/coact/kochzap/book/SearchBookContentsResult.java
1667
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.coact.kochzap.book; /** * The underlying data for a SBC result. * * @author dswitkin@google.com (Daniel Switkin) */ final class SearchBookContentsResult { private static String query = null; private final String pageId; private final String pageNumber; private final String snippet; private final boolean validSnippet; SearchBookContentsResult(String pageId, String pageNumber, String snippet, boolean validSnippet) { this.pageId = pageId; this.pageNumber = pageNumber; this.snippet = snippet; this.validSnippet = validSnippet; } public static void setQuery(String query) { SearchBookContentsResult.query = query; } public String getPageId() { return pageId; } public String getPageNumber() { return pageNumber; } public String getSnippet() { return snippet; } public boolean getValidSnippet() { return validSnippet; } public static String getQuery() { return query; } }
apache-2.0
bascoder/formvalid
src/main/java/nl/bascoder/formvalid/package-info.java
150
/** * @author Bas van Marwijk * @since 24-10-14 * @version 1.0 - creation * * Root package of formvalid webapp */ package nl.bascoder.formvalid;
apache-2.0
golfstream83/BookShop
src/main/java/ru/tulin/service/BookService.java
368
package ru.tulin.service; import ru.tulin.model.Book; import java.util.List; /** * @author Viktor Tulin * @version 1 * @since 04.01.2017 */ public interface BookService { public void addBook(Book book); public void updateBook(Book book); public void removeBook(int id); public Book getBookById(int id); public List<Book> listBooks(); }
apache-2.0
spinnaker/halyard
halyard-deploy/src/main/java/com/netflix/spinnaker/halyard/deploy/spinnaker/v1/profile/SecurityConfig.java
1508
/* * Copyright 2017 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile; import com.netflix.spinnaker.halyard.config.model.v1.security.OAuth2; import com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.ServiceSettings; import lombok.Data; @Data public class SecurityConfig { BasicSecurity basic = new BasicSecurity(); User user = new User(); OAuth2 oauth2; SecurityConfig(ServiceSettings settings) { if (settings.getBasicAuthEnabled() == null || settings.getBasicAuthEnabled()) { String username = settings.getUsername(); String password = settings.getPassword(); assert (username != null && password != null); basic.setEnabled(true); user.setName(username); user.setPassword(password); } } @Data public static class BasicSecurity { boolean enabled = false; } @Data public static class User { String name; String password; } }
apache-2.0
liuyf8688/demos
cache-demos/ehcache2-demos/src/test/java/com/liuyf/demos/cache/ehcache2/test/VerifyEhcacheIsDeepCopy.java
1209
package com.liuyf.demos.cache.ehcache2.test; import org.junit.Assert; import org.junit.Test; import com.liuyf.demos.cache.ehcache2.pojo.Person; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; public class VerifyEhcacheIsDeepCopy { private static final String PERSON = "PERSON_"; @Test public void test() { final CacheManager cacheManager = new CacheManager(); try { final Ehcache cache = cacheManager.getEhcache("copyCache"); System.out.println(cache); final Person person = new Person(); person.setId(100L); person.setName("TonyLiu"); person.setAge(16); // String key = PERSON + person.getId(); String snapshot = person.toString(); System.out.println(" === before putting cache, " + snapshot); final Element element = new Element(key, person); cache.put(element); person.setName("LiuYanfeng"); person.setAge(19); Element e = cache.get(key); Person p = (Person)e.getObjectValue(); String actual = p.toString(); System.out.println(" === get from cache, " + actual); Assert.assertEquals(snapshot, actual); } finally { cacheManager.shutdown(); } } }
apache-2.0
Activiti/Activiti
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/tenant/TenancyTest.java
57014
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.test.api.tenant; import java.util.ArrayList; import java.util.List; import org.activiti.engine.ActivitiException; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.impl.history.HistoryLevel; import org.activiti.engine.impl.test.PluggableActivitiTestCase; import org.activiti.engine.repository.Deployment; import org.activiti.engine.repository.Model; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.runtime.Job; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * A test case for the various implications of the tenancy support (tenant id column to entities + query support) */ public class TenancyTest extends PluggableActivitiTestCase { private static final String TEST_TENANT_ID = "myTenantId"; private List<String> autoCleanedUpDeploymentIds = new ArrayList<String>(); @Override protected void setUp() throws Exception { super.setUp(); this.autoCleanedUpDeploymentIds.clear(); } @Override protected void tearDown() throws Exception { super.tearDown(); if (!autoCleanedUpDeploymentIds.isEmpty()) { for (String deploymentId : autoCleanedUpDeploymentIds) { repositoryService.deleteDeployment(deploymentId, true); } } } /** * Deploys the one task process with the test tenant id. * @return The process definition id of the deployed process definition. */ private String deployTestProcessWithTestTenant() { return deployTestProcessWithTestTenant(TEST_TENANT_ID); } private String deployTestProcessWithTestTenant(String tenantId) { String id = repositoryService.createDeployment().addBpmnModel("testProcess.bpmn20.xml", createOneTaskTestProcess()).tenantId(tenantId).deploy().getId(); autoCleanedUpDeploymentIds.add(id); return repositoryService.createProcessDefinitionQuery().deploymentId(id).singleResult().getId(); } private String deployTestProcessWithTwoTasksWithTestTenant() { String id = repositoryService.createDeployment().addBpmnModel("testProcess.bpmn20.xml", createTwoTasksTestProcess()).tenantId(TEST_TENANT_ID).deploy().getId(); autoCleanedUpDeploymentIds.add(id); return repositoryService.createProcessDefinitionQuery().deploymentId(id).singleResult().getId(); } private String deployTestProcessWithTwoTasksNoTenant() { String id = repositoryService.createDeployment().addBpmnModel("testProcess.bpmn20.xml", createTwoTasksTestProcess()).deploy().getId(); autoCleanedUpDeploymentIds.add(id); return repositoryService.createProcessDefinitionQuery().deploymentId(id).singleResult().getId(); } public void testDeploymentTenancy() { deployTestProcessWithTestTenant(); assertThat(repositoryService.createDeploymentQuery().singleResult().getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(repositoryService.createDeploymentQuery().deploymentTenantId(TEST_TENANT_ID).list()).hasSize(1); assertThat(repositoryService.createDeploymentQuery().deploymentId(autoCleanedUpDeploymentIds.get(0)).deploymentTenantId(TEST_TENANT_ID).list()).hasSize(1); assertThat(repositoryService.createDeploymentQuery().deploymentTenantIdLike("my%").list()).hasSize(1); assertThat(repositoryService.createDeploymentQuery().deploymentTenantIdLike("%TenantId").list()).hasSize(1); assertThat(repositoryService.createDeploymentQuery().deploymentTenantIdLike("m%Ten%").list()).hasSize(1); assertThat(repositoryService.createDeploymentQuery().deploymentTenantIdLike("noexisting%").list()).hasSize(0); assertThat(repositoryService.createDeploymentQuery().deploymentWithoutTenantId().list()).hasSize(0); } public void testProcessDefinitionTenancy() { // Deploy a process with tenant and verify String processDefinitionIdWithTenant = deployTestProcessWithTestTenant(); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionIdWithTenant).singleResult().getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(TEST_TENANT_ID).list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("m%").list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("somethingElse%").list()).hasSize(0); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionWithoutTenantId().list()).hasSize(0); // Deploy another process, without tenant String processDefinitionIdWithoutTenant = deployOneTaskTestProcess(); assertThat(repositoryService.createProcessDefinitionQuery().list()).hasSize(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(TEST_TENANT_ID).list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("m%").list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("somethingElse%").list()).hasSize(0); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionWithoutTenantId().list()).hasSize(1); // Deploy another process with the same tenant String processDefinitionIdWithTenant2 = deployTestProcessWithTestTenant(); assertThat(repositoryService.createProcessDefinitionQuery().list()).hasSize(3); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(TEST_TENANT_ID).list()).hasSize(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("m%").list()).hasSize(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantIdLike("somethingElse%").list()).hasSize(0); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionWithoutTenantId().list()).hasSize(1); // Extra check: we deployed the one task process twice, but once with // tenant and once without. The latest query should show this. assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(TEST_TENANT_ID).latestVersion() .singleResult().getId()).isEqualTo(processDefinitionIdWithTenant2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId("Not a tenant").latestVersion().count()).isEqualTo(0); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionWithoutTenantId().latestVersion().singleResult().getId()).isEqualTo(processDefinitionIdWithoutTenant); } public void testProcessInstanceTenancy() { // Start a number of process instances with tenant String processDefinitionId = deployTestProcessWithTestTenant(); int nrOfProcessInstancesWithTenant = 6; for (int i = 0; i < nrOfProcessInstancesWithTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionId); } // Start a number of process instance without tenantit String processDefinitionIdNoTenant = deployOneTaskTestProcess(); int nrOfProcessInstancesNoTenant = 8; for (int i = 0; i < nrOfProcessInstancesNoTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdNoTenant); } // Check the query results assertThat(runtimeService.createProcessInstanceQuery().processDefinitionId(processDefinitionId).list().get(0).getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(runtimeService.createProcessInstanceQuery().list().size()).isEqualTo(nrOfProcessInstancesNoTenant + nrOfProcessInstancesWithTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().list().size()).isEqualTo(nrOfProcessInstancesNoTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).list().size()).isEqualTo(nrOfProcessInstancesWithTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantIdLike("%enan%").list().size()).isEqualTo(nrOfProcessInstancesWithTenant); } public void testExecutionTenancy() { // Start a number of process instances with tenant String processDefinitionId = deployTestProcessWithTwoTasksWithTestTenant(); int nrOfProcessInstancesWithTenant = 4; for (int i = 0; i < nrOfProcessInstancesWithTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionId); } // Start a number of process instance without tenantid String processDefinitionIdNoTenant = deployTwoTasksTestProcess(); int nrOfProcessInstancesNoTenant = 2; for (int i = 0; i < nrOfProcessInstancesNoTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdNoTenant); } // Check the query results: // note: 3 executions per process instance due to parallelism! assertThat(runtimeService.createExecutionQuery().processDefinitionId(processDefinitionId).list().get(0).getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(runtimeService.createExecutionQuery().processDefinitionId(processDefinitionIdNoTenant).list().get(0).getTenantId()).isEqualTo(""); assertThat(runtimeService.createExecutionQuery().list().size()).isEqualTo(3 * (nrOfProcessInstancesNoTenant + nrOfProcessInstancesWithTenant)); assertThat(runtimeService.createExecutionQuery().executionWithoutTenantId().list().size()).isEqualTo(3 * nrOfProcessInstancesNoTenant); assertThat(runtimeService.createExecutionQuery().executionTenantId(TEST_TENANT_ID).list().size()).isEqualTo(3 * nrOfProcessInstancesWithTenant); assertThat(runtimeService.createExecutionQuery().executionTenantIdLike("%en%").list().size()).isEqualTo(3 * nrOfProcessInstancesWithTenant); // Check the process instance query results, just to be sure assertThat(runtimeService.createProcessInstanceQuery().processDefinitionId(processDefinitionId).list().get(0).getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(runtimeService.createProcessInstanceQuery().list().size()).isEqualTo(nrOfProcessInstancesNoTenant + nrOfProcessInstancesWithTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().list().size()).isEqualTo(nrOfProcessInstancesNoTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).list().size()).isEqualTo(nrOfProcessInstancesWithTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantIdLike("%en%").list().size()).isEqualTo(nrOfProcessInstancesWithTenant); } public void testTaskTenancy() { // Generate 10 tasks with tenant String processDefinitionIdWithTenant = deployTestProcessWithTwoTasksWithTestTenant(); int nrOfProcessInstancesWithTenant = 5; for (int i = 0; i < nrOfProcessInstancesWithTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdWithTenant); } // Generate 4 tasks without tenant String processDefinitionIdNoTenant = deployTwoTasksTestProcess(); int nrOfProcessInstancesNoTenant = 2; for (int i = 0; i < nrOfProcessInstancesNoTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdNoTenant); } // Check the query results assertThat(taskService.createTaskQuery().processDefinitionId(processDefinitionIdWithTenant).list().get(0).getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(taskService.createTaskQuery().processDefinitionId(processDefinitionIdNoTenant).list().get(0).getTenantId()).isEqualTo(""); assertThat(taskService.createTaskQuery().list().size()).isEqualTo(14); assertThat(taskService.createTaskQuery().taskTenantId(TEST_TENANT_ID).list().size()).isEqualTo(10); assertThat(taskService.createTaskQuery().taskTenantId("Another").list().size()).isEqualTo(0); assertThat(taskService.createTaskQuery().taskTenantIdLike("my%").list().size()).isEqualTo(10); assertThat(taskService.createTaskQuery().taskWithoutTenantId().list().size()).isEqualTo(4); } public void testJobTenancy() { // Deploy process with a timer and an async step AND with a tenant String deploymentId = repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testJobTenancy.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy() .getId(); // verify job (timer start) Job job = managementService.createTimerJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(TEST_TENANT_ID); managementService.moveTimerToExecutableJob(job.getId()); managementService.executeJob(job.getId()); // Verify Job tenancy (process intermediary timer) job = managementService.createTimerJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(TEST_TENANT_ID); // Start process, and verify async job has correct tenant id managementService.moveTimerToExecutableJob(job.getId()); managementService.executeJob(job.getId()); job = managementService.createJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(TEST_TENANT_ID); // Finish process managementService.executeJob(job.getId()); // Do the same, but now without a tenant String deploymentId2 = repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testJobTenancy.bpmn20.xml").deploy().getId(); job = managementService.createTimerJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(""); managementService.moveTimerToExecutableJob(job.getId()); managementService.executeJob(job.getId()); job = managementService.createTimerJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(""); managementService.moveTimerToExecutableJob(job.getId()); managementService.executeJob(job.getId()); job = managementService.createJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(""); // clean up repositoryService.deleteDeployment(deploymentId, true); repositoryService.deleteDeployment(deploymentId2, true); } public void testModelTenancy() { // Create a few models with tenant int nrOfModelsWithTenant = 3; for (int i = 0; i < nrOfModelsWithTenant; i++) { Model model = repositoryService.newModel(); model.setName(i + ""); model.setTenantId(TEST_TENANT_ID); repositoryService.saveModel(model); } // Create a few models without tenant int nrOfModelsWithoutTenant = 5; for (int i = 0; i < nrOfModelsWithoutTenant; i++) { Model model = repositoryService.newModel(); model.setName(i + ""); repositoryService.saveModel(model); } // Check query assertThat(repositoryService.createModelQuery().list().size()).isEqualTo(nrOfModelsWithoutTenant + nrOfModelsWithTenant); assertThat(repositoryService.createModelQuery().modelWithoutTenantId().list().size()).isEqualTo(nrOfModelsWithoutTenant); assertThat(repositoryService.createModelQuery().modelTenantId(TEST_TENANT_ID).list().size()).isEqualTo(nrOfModelsWithTenant); assertThat(repositoryService.createModelQuery().modelTenantIdLike("my%").list().size()).isEqualTo(nrOfModelsWithTenant); assertThat(repositoryService.createModelQuery().modelTenantId("a%").list().size()).isEqualTo(0); // Clean up for (Model model : repositoryService.createModelQuery().list()) { repositoryService.deleteModel(model.getId()); } } public void testChangeDeploymentTenantId() { // Generate 8 tasks with tenant String processDefinitionIdWithTenant = deployTestProcessWithTwoTasksWithTestTenant(); int nrOfProcessInstancesWithTenant = 4; for (int i = 0; i < nrOfProcessInstancesWithTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdWithTenant); } // Generate 10 tasks without tenant String processDefinitionIdNoTenant = deployTwoTasksTestProcess(); int nrOfProcessInstancesNoTenant = 5; for (int i = 0; i < nrOfProcessInstancesNoTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdNoTenant); } // Migrate deployment with tenant to another tenant String newTenantId = "NEW TENANT ID"; String deploymentId = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionIdWithTenant).singleResult().getDeploymentId(); repositoryService.changeDeploymentTenantId(deploymentId, newTenantId); // Verify tenant id Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); assertThat(deployment.getTenantId()).isEqualTo(newTenantId); // Verify deployment assertThat(repositoryService.createDeploymentQuery().list()).hasSize(2); assertThat(repositoryService.createDeploymentQuery().deploymentTenantId(TEST_TENANT_ID).list()).hasSize(0); assertThat(repositoryService.createDeploymentQuery().deploymentTenantId(newTenantId).list()).hasSize(1); assertThat(repositoryService.createDeploymentQuery().deploymentWithoutTenantId().list()).hasSize(1); // Verify process definition assertThat(repositoryService.createProcessDefinitionQuery().list()).hasSize(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(TEST_TENANT_ID).list()).hasSize(0); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(newTenantId).list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(newTenantId).list()).hasSize(1); // Verify process instances assertThat(runtimeService.createProcessInstanceQuery().list()).hasSize(nrOfProcessInstancesNoTenant + nrOfProcessInstancesWithTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).list()).hasSize(0); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(newTenantId).list()).hasSize(nrOfProcessInstancesWithTenant); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().list()).hasSize(nrOfProcessInstancesNoTenant); // Verify executions assertThat(runtimeService.createExecutionQuery().list()).hasSize(3 * (nrOfProcessInstancesNoTenant + nrOfProcessInstancesWithTenant)); assertThat(runtimeService.createExecutionQuery().executionWithoutTenantId().list()).hasSize(3 * nrOfProcessInstancesNoTenant); assertThat(runtimeService.createExecutionQuery().executionTenantId(TEST_TENANT_ID).list()).hasSize(0); assertThat(runtimeService.createExecutionQuery().executionTenantId(newTenantId).list()).hasSize(3 * nrOfProcessInstancesWithTenant); assertThat(runtimeService.createExecutionQuery().executionTenantIdLike("NEW%").list()).hasSize(3 * nrOfProcessInstancesWithTenant); // Verify tasks assertThat(taskService.createTaskQuery().list()).hasSize(2 * (nrOfProcessInstancesNoTenant + nrOfProcessInstancesWithTenant)); assertThat(taskService.createTaskQuery().taskTenantId(TEST_TENANT_ID).list()).hasSize(0); assertThat(taskService.createTaskQuery().taskTenantId(newTenantId).list()).hasSize(2 * nrOfProcessInstancesWithTenant); assertThat(taskService.createTaskQuery().taskWithoutTenantId().list()).hasSize(2 * nrOfProcessInstancesNoTenant); // Remove the tenant id and verify results // should clash: there is already a process definition with the same key assertThatExceptionOfType(Exception.class) .isThrownBy(() -> repositoryService.changeDeploymentTenantId(deploymentId, "")); } public void testChangeDeploymentIdWithClash() { String processDefinitionIdWithTenant = deployTestProcessWithTestTenant("tenantA"); deployOneTaskTestProcess(); // Changing the one with tenant now back to one without should clash, // cause there already exists one assertThatExceptionOfType(Exception.class) .isThrownBy(() -> repositoryService.changeDeploymentTenantId(processDefinitionIdWithTenant, "")); // Deploying another version should just up the version String processDefinitionIdNoTenant2 = deployOneTaskTestProcess(); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionIdNoTenant2).singleResult().getVersion()).isEqualTo(2); } public void testJobTenancyAfterTenantChange() { // Deploy process with a timer and an async step AND with a tenant String deploymentId = repositoryService.createDeployment() .addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testJobTenancy.bpmn20.xml").tenantId(TEST_TENANT_ID) .deploy() .getId(); String newTenant = "newTenant"; repositoryService.changeDeploymentTenantId(deploymentId, newTenant); // verify job (timer start) Job job = managementService.createTimerJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(newTenant); managementService.moveTimerToExecutableJob(job.getId()); managementService.executeJob(job.getId()); // Verify Job tenancy (process intermediary timer) job = managementService.createTimerJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(newTenant); // Start process, and verify async job has correct tenant id managementService.moveTimerToExecutableJob(job.getId()); managementService.executeJob(job.getId()); job = managementService.createJobQuery().singleResult(); assertThat(job.getTenantId()).isEqualTo(newTenant); // Finish process managementService.executeJob(job.getId()); // clean up repositoryService.deleteDeployment(deploymentId, true); } public void testHistoryTenancy() { if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) { // Generate 3 tasks with tenant String processDefinitionIdWithTenant = deployTestProcessWithTestTenant(); int nrOfProcessInstancesWithTenant = 3; for (int i = 0; i < nrOfProcessInstancesWithTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdWithTenant); } // Generate 2 tasks without tenant String processDefinitionIdNoTenant = deployOneTaskTestProcess(); int nrOfProcessInstancesNoTenant = 2; for (int i = 0; i < nrOfProcessInstancesNoTenant; i++) { runtimeService.startProcessInstanceById(processDefinitionIdNoTenant); } // Complete all tasks for (Task task : taskService.createTaskQuery().list()) { taskService.complete(task.getId()); } // Verify process instances assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionId(processDefinitionIdWithTenant).list().get(0).getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionId(processDefinitionIdNoTenant).list().get(0).getTenantId()).isEqualTo(""); assertThat(historyService.createHistoricProcessInstanceQuery().list()).hasSize(nrOfProcessInstancesWithTenant + nrOfProcessInstancesNoTenant); assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).list()).hasSize(nrOfProcessInstancesWithTenant); assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceTenantIdLike("%e%").list()).hasSize(nrOfProcessInstancesWithTenant); assertThat(historyService.createHistoricProcessInstanceQuery().processInstanceWithoutTenantId().list()).hasSize(nrOfProcessInstancesNoTenant); // verify tasks assertThat(historyService.createHistoricTaskInstanceQuery().processDefinitionId(processDefinitionIdWithTenant).list().get(0).getTenantId()).isEqualTo(TEST_TENANT_ID); assertThat(historyService.createHistoricTaskInstanceQuery().processDefinitionId(processDefinitionIdNoTenant).list().get(0).getTenantId()).isEqualTo(""); assertThat(historyService.createHistoricTaskInstanceQuery().list()).hasSize(nrOfProcessInstancesWithTenant + nrOfProcessInstancesNoTenant); assertThat(historyService.createHistoricTaskInstanceQuery().taskTenantId(TEST_TENANT_ID).list()).hasSize(nrOfProcessInstancesWithTenant); assertThat(historyService.createHistoricTaskInstanceQuery().taskTenantIdLike("my%").list()).hasSize(nrOfProcessInstancesWithTenant); assertThat(historyService.createHistoricTaskInstanceQuery().taskWithoutTenantId().list()).hasSize(nrOfProcessInstancesNoTenant); // verify activities List<HistoricActivityInstance> activityInstances = historyService.createHistoricActivityInstanceQuery().processDefinitionId(processDefinitionIdWithTenant).list(); for (HistoricActivityInstance historicActivityInstance : activityInstances) { assertThat(historicActivityInstance.getTenantId()).isEqualTo(TEST_TENANT_ID); } assertThat(historyService.createHistoricActivityInstanceQuery().processDefinitionId(processDefinitionIdNoTenant).list().get(0).getTenantId()).isEqualTo(""); assertThat(historyService.createHistoricActivityInstanceQuery().list()).hasSize(3 * (nrOfProcessInstancesWithTenant + nrOfProcessInstancesNoTenant)); assertThat(historyService.createHistoricActivityInstanceQuery().activityTenantId(TEST_TENANT_ID).list()).hasSize(3 * nrOfProcessInstancesWithTenant); assertThat(historyService.createHistoricActivityInstanceQuery().activityTenantIdLike("my%").list()).hasSize(3 * nrOfProcessInstancesWithTenant); assertThat(historyService.createHistoricActivityInstanceQuery().activityWithoutTenantId().list()).hasSize(3 * nrOfProcessInstancesNoTenant); } } public void testProcessDefinitionKeyClashBetweenTenants() { String tentanA = "tenantA"; String tenantB = "tenantB"; // Deploy the same process (same process definition key) for two different tenants. String procDefIdA = deployTestProcessWithTestTenant(tentanA); String procDefIdB = deployTestProcessWithTestTenant(tenantB); // verify query assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdA).singleResult().getKey()).isEqualTo("oneTaskProcess"); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdA).singleResult().getVersion()).isEqualTo(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdB).singleResult().getKey()).isEqualTo("oneTaskProcess"); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdB).singleResult().getVersion()).isEqualTo(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").list()).hasSize(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(tentanA).list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(tenantB).list()).hasSize(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionWithoutTenantId().list()).hasSize(0); // Deploy second version procDefIdA = deployTestProcessWithTestTenant(tentanA); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdA).singleResult().getKey()).isEqualTo("oneTaskProcess"); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdA).singleResult().getVersion()).isEqualTo(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(tentanA).latestVersion().singleResult().getVersion()).isEqualTo(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdB).singleResult().getKey()).isEqualTo("oneTaskProcess"); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefIdB).singleResult().getVersion()).isEqualTo(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").list().size()).isEqualTo(3); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(tentanA).list().size()).isEqualTo(2); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(tenantB).list().size()).isEqualTo(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionTenantId(tentanA).latestVersion().list().size()).isEqualTo(1); assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionKey("oneTaskProcess").processDefinitionWithoutTenantId().list().size()).isEqualTo(0); // Now, start process instances by process definition key (no tenant) // shouldn't happen, there is no process definition with that // key that has no tenant, it has to give an exception as such! assertThatExceptionOfType(Exception.class) .isThrownBy(() -> runtimeService.startProcessInstanceByKey("oneTaskProcess")); ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId("oneTaskProcess", tentanA); assertThat(processInstance.getProcessDefinitionId()).isEqualTo(procDefIdA); processInstance = runtimeService.startProcessInstanceByKeyAndTenantId("oneTaskProcess", tenantB); assertThat(processInstance.getProcessDefinitionId()).isEqualTo(procDefIdB); } public void testSuspendProcessDefinitionTenancy() { // Deploy one process definition for tenant A, and two process // definitions versions for tenant B String tentanA = "tenantA"; String tenantB = "tenantB"; String procDefIdA = deployTestProcessWithTestTenant(tentanA); String procDefIdB = deployTestProcessWithTestTenant(tenantB); String procDefIdB2 = deployTestProcessWithTestTenant(tenantB); // Suspend process definition B repositoryService.suspendProcessDefinitionByKey("oneTaskProcess", tenantB); // Shouldn't be able to start proc defs for tentant B try { runtimeService.startProcessInstanceById(procDefIdB); } catch (ActivitiException e) { } try { runtimeService.startProcessInstanceById(procDefIdB2); } catch (ActivitiException e) { } ProcessInstance processInstance = runtimeService.startProcessInstanceById(procDefIdA); assertThat(processInstance).isNotNull(); // Activate process again repositoryService.activateProcessDefinitionByKey("oneTaskProcess", tenantB); processInstance = runtimeService.startProcessInstanceById(procDefIdB); assertThat(processInstance).isNotNull(); processInstance = runtimeService.startProcessInstanceById(procDefIdB2); assertThat(processInstance).isNotNull(); processInstance = runtimeService.startProcessInstanceById(procDefIdA); assertThat(processInstance).isNotNull(); // Suspending with NO tenant id should give an error, cause they both // have tenants try { repositoryService.suspendProcessDefinitionByKey("oneTaskProcess"); } catch (ActivitiException e) { } } public void testSignalFromProcessTenancy() { // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Start 3 proc instances for the one with a tenant and 2 for the one // without tenant runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); // verify assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(3); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(2); // Now, start 1 process instance that fires a signal event (not in tenant context), it should only continue those without tenant runtimeService.startProcessInstanceByKey("testMtSignalFiring"); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(0); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(2); // Start a process instance that is running in tenant context runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalFiring", TEST_TENANT_ID); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(3); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(2); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } public void testSignalThroughApiTenancy() { // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Start 4 proc instances for the one with a tenant and 5 for the one without tenant runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); // Verify assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(5); // Signal through API (with tenant) runtimeService.signalEventReceivedWithTenantId("The Signal", TEST_TENANT_ID); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(0); // Signal through API (without tenant) runtimeService.signalEventReceived("The Signal"); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(5); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } public void testSignalThroughApiTenancyReversed() { // cause reversing the // order of calling DID leave to an error! // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Start 4 proc instances for the one with a tenant and 5 for the one without tenant runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); // Verify assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(5); // Signal through API (without tenant) runtimeService.signalEventReceived("The Signal"); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(0); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(5); // Signal through API (with tenant) runtimeService.signalEventReceivedWithTenantId("The Signal", TEST_TENANT_ID); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(5); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } public void testSignalAsyncThroughApiTenancy() { // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMultiTenancySignals.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Start 4 proc instances for the one with a tenant and 5 for the one // without tenant runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKeyAndTenantId("testMtSignalCatch", TEST_TENANT_ID); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); runtimeService.startProcessInstanceByKey("testMtSignalCatch"); // Verify assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(5); // Signal through API (with tenant) runtimeService.signalEventReceivedAsyncWithTenantId("The Signal", TEST_TENANT_ID); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(0); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(0); for (Job job : managementService.createJobQuery().list()) { managementService.executeJob(job.getId()); } assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(0); // Signal through API (without tenant) runtimeService.signalEventReceivedAsync("The Signal"); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(0); for (Job job : managementService.createJobQuery().list()) { managementService.executeJob(job.getId()); } assertThat(taskService.createTaskQuery().taskName("Task after signal").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(4); assertThat(taskService.createTaskQuery().taskName("Task after signal").taskWithoutTenantId().count()).isEqualTo(5); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } public void testStartProcessInstanceBySignalTenancy() { // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testStartProcessInstanceBySignalTenancy.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testStartProcessInstanceBySignalTenancy.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Signaling without tenant runtimeService.signalEventReceived("The Signal"); assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(3); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().count()).isEqualTo(3); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).count()).isEqualTo(0); // Signalling with tenant runtimeService.signalEventReceivedWithTenantId("The Signal", TEST_TENANT_ID); assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(6); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().count()).isEqualTo(3); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).count()).isEqualTo(3); // Start a process instance with a boundary catch (with and without tenant) runtimeService.startProcessInstanceByKey("processWithSignalCatch"); runtimeService.startProcessInstanceByKeyAndTenantId("processWithSignalCatch", TEST_TENANT_ID); runtimeService.signalEventReceived("The Signal"); assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(11); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().count()).isEqualTo(7); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).count()).isEqualTo(4); runtimeService.signalEventReceivedWithTenantId("The Signal", TEST_TENANT_ID); assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(14); assertThat(runtimeService.createProcessInstanceQuery().processInstanceWithoutTenantId().count()).isEqualTo(7); assertThat(runtimeService.createProcessInstanceQuery().processInstanceTenantId(TEST_TENANT_ID).count()).isEqualTo(7); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } public void testStartProcessInstanceByMessageTenancy() { // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMessageTenancy.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMessageTenancy.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Verify query assertThat(repositoryService.createProcessDefinitionQuery().messageEventSubscriptionName("My message").count()).isEqualTo(2); assertThat(repositoryService.createProcessDefinitionQuery().messageEventSubscriptionName("My message").processDefinitionWithoutTenantId().count()).isEqualTo(1); assertThat(repositoryService.createProcessDefinitionQuery().messageEventSubscriptionName("My message").processDefinitionTenantId(TEST_TENANT_ID).count()).isEqualTo(1); // Start a process instance by message without tenant runtimeService.startProcessInstanceByMessage("My message"); runtimeService.startProcessInstanceByMessage("My message"); assertThat(taskService.createTaskQuery().taskName("My task").count()).isEqualTo(2); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(2); assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(0); // Start a process instance by message with tenant runtimeService.startProcessInstanceByMessageAndTenantId("My message", TEST_TENANT_ID); runtimeService.startProcessInstanceByMessageAndTenantId("My message", TEST_TENANT_ID); runtimeService.startProcessInstanceByMessageAndTenantId("My message", TEST_TENANT_ID); assertThat(taskService.createTaskQuery().taskName("My task").count()).isEqualTo(5); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(2); assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(3); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } public void testStartProcessInstanceByMessageTenancyReversed() { // same as // above, but now reversed // Deploy process both with and without tenant repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMessageTenancy.bpmn20.xml").deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testMessageTenancy.bpmn20.xml").tenantId(TEST_TENANT_ID).deploy(); // Start a process instance by message with tenant runtimeService.startProcessInstanceByMessageAndTenantId("My message", TEST_TENANT_ID); runtimeService.startProcessInstanceByMessageAndTenantId("My message", TEST_TENANT_ID); runtimeService.startProcessInstanceByMessageAndTenantId("My message", TEST_TENANT_ID); assertThat(taskService.createTaskQuery().taskName("My task").count()).isEqualTo(3); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(0); assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(3); // Start a process instance by message without tenant runtimeService.startProcessInstanceByMessage("My message"); runtimeService.startProcessInstanceByMessage("My message"); assertThat(taskService.createTaskQuery().taskName("My task").count()).isEqualTo(5); assertThat(taskService.createTaskQuery().taskName("My task").taskWithoutTenantId().count()).isEqualTo(2); assertThat(taskService.createTaskQuery().taskName("My task").taskTenantId(TEST_TENANT_ID).count()).isEqualTo(3); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } // Bug from http://forums.activiti.org/content/callactiviti-tenant-id public void testCallActivityWithTenant() { if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { String tenantId = "apache"; // deploying both processes. Process 1 will call Process 2 repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testCallActivityWithTenant-process01.bpmn20.xml").tenantId(tenantId).deploy(); repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/api/tenant/TenancyTest.testCallActivityWithTenant-process02.bpmn20.xml").tenantId(tenantId).deploy(); // Starting Process 1. Process 1 will be executed successfully but // when the call to process 2 is made internally it will throw the // exception ProcessInstance processInstance = runtimeService.startProcessInstanceByKeyAndTenantId("process1", null, singletonMap("sendFor", "test"), tenantId); assertThat(processInstance).isNotNull(); assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("process2").processInstanceTenantId(tenantId).count()).isEqualTo(1); assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("process2").count()).isEqualTo(1); // following line if executed will give activiti object not found // exception as the process1 is linked to a tenant id. assertThatExceptionOfType(Exception.class) .isThrownBy(() -> runtimeService.startProcessInstanceByKey("process1")); // Cleanup for (Deployment deployment : repositoryService.createDeploymentQuery().list()) { repositoryService.deleteDeployment(deployment.getId(), true); } } } /* * See https://activiti.atlassian.net/browse/ACT-4034 */ public void testGetLatestProcessDefinitionVersionForSameProcessDefinitionKey() { String tenant1 = "tenant1"; String tenant2 = "tenant2"; // Tenant 1 ==> version 4 for (int i = 0; i < 4; i++) { deployTestProcessWithTestTenant(tenant1); } // Tenant 2 ==> version 2 for (int i = 0; i < 2; i++) { deployTestProcessWithTestTenant(tenant2); } // No tenant ==> version 3 for (int i = 0; i < 3; i++) { deployTestProcessWithTwoTasksNoTenant(); } ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery() .processDefinitionTenantId(tenant1) .latestVersion() .singleResult(); assertThat(processDefinition.getVersion()).isEqualTo(4); processDefinition = repositoryService.createProcessDefinitionQuery() .processDefinitionTenantId(tenant2) .latestVersion() .singleResult(); assertThat(processDefinition.getVersion()).isEqualTo(2); processDefinition = repositoryService.createProcessDefinitionQuery() .processDefinitionWithoutTenantId() .latestVersion() .singleResult(); assertThat(processDefinition.getVersion()).isEqualTo(3); List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().latestVersion().list(); assertThat(processDefinitions.size()).isEqualTo(3); // Verify they have different tenant ids int tenant1Count = 0, tenant2Count = 0, noTenantCount = 0; for (ProcessDefinition p : processDefinitions) { if (p.getTenantId() == null || p.getTenantId().equals(ProcessEngineConfiguration.NO_TENANT_ID)) { noTenantCount++; } else if (p.getTenantId().equals(tenant1)) { tenant1Count++; } else if (p.getTenantId().equals(tenant2)) { tenant2Count++; } } assertThat(tenant1Count).isEqualTo(1); assertThat(tenant2Count).isEqualTo(1); assertThat(noTenantCount).isEqualTo(1); } }
apache-2.0
gxa/atlas
gxa/src/main/java/uk/ac/ebi/atlas/home/LatestExperimentsDao.java
1893
package uk.ac.ebi.atlas.home; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import uk.ac.ebi.atlas.model.experiment.ExperimentType; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Component public class LatestExperimentsDao { static final int LIMIT = 8; private static final String SELECT_PUBLIC_ACCESSIONS = "SELECT accession FROM experiment WHERE private=FALSE "; private static final String IN_DESCENDING_ORDER_BY_DATE = " ORDER BY last_update DESC LIMIT " + LIMIT; private static final String EXPERIMENT_COUNT = "SELECT COUNT(*) FROM experiment WHERE private=FALSE "; private final JdbcTemplate jdbcTemplate; public LatestExperimentsDao(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } private String buildExperimentTypeConditions(Set<ExperimentType> experimentTypes) { if (experimentTypes.isEmpty()) { return ""; } return String.format( "AND (%s)", experimentTypes.stream() .map(experimentType -> String.format("type='%s'", experimentType.name())) .collect(Collectors.joining(" OR "))); } public List<String> fetchLatestExperimentAccessions(Set<ExperimentType> experimentTypes) { return jdbcTemplate.queryForList( SELECT_PUBLIC_ACCESSIONS + buildExperimentTypeConditions(experimentTypes) + IN_DESCENDING_ORDER_BY_DATE, String.class); } public long fetchPublicExperimentsCount(Set<ExperimentType> experimentTypes) { return jdbcTemplate.queryForObject( EXPERIMENT_COUNT + buildExperimentTypeConditions(experimentTypes), Long.class); } }
apache-2.0
dsysme/briefcase
src/org/opendatakit/briefcase/model/DocumentDescription.java
1827
/* * Copyright (C) 2011 University of Washington. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.opendatakit.briefcase.model; import org.bushe.swing.event.annotation.AnnotationProcessor; public class DocumentDescription { final String fetchDocFailed; final String fetchDocFailedNoDetail; final String documentDescriptionType; final TerminationFuture terminationFuture; volatile boolean cancelled = false; public DocumentDescription(String fetchDocFailed, String fetchDocFailedNoDetail, String documentDescriptionType, TerminationFuture terminationFuture) { AnnotationProcessor.process(this);// if not using AOP this.fetchDocFailed = fetchDocFailed; this.fetchDocFailedNoDetail = fetchDocFailedNoDetail; this.documentDescriptionType = documentDescriptionType; this.terminationFuture = terminationFuture; } public boolean isCancelled() { return terminationFuture.isCancelled(); } public String getFetchDocFailed() { return fetchDocFailed; } public String getFetchDocFailedNoDetail() { return fetchDocFailedNoDetail; } public String getDocumentDescriptionType() { return documentDescriptionType; } }
apache-2.0
cocoatomo/asakusafw
yaess-project/asakusa-yaess-core/src/main/java/com/asakusafw/yaess/basic/BlobUtil.java
2084
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.yaess.basic; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import com.asakusafw.yaess.core.Blob; import com.asakusafw.yaess.core.ExecutionContext; import com.asakusafw.yaess.core.ExecutionScript; /** * Utilities for {@link Blob}. * @since 0.8.0 */ public final class BlobUtil { private BlobUtil() { return; } /** * Builds {@link ExecutionContext#getExtensions() extensions} for the script. * @param context the current context * @param script the target script * @return the extended arguments */ public static Map<String, Blob> getExtensions(ExecutionContext context, ExecutionScript script) { Map<String, Blob> results = new LinkedHashMap<>(); Map<String, Blob> extensions = context.getExtensions(); Set<String> supported = script.getSupportedExtensions(); for (Map.Entry<String, Blob> entry : extensions.entrySet()) { if (supported.contains(entry.getKey())) { results.put(entry.getKey(), entry.getValue()); } } return results; } /** * Returns the file suffix for the extension. * @param extension the extension name * @param blob the target BLOB * @return the target file name suffix */ public static String getSuffix(String extension, Blob blob) { return String.format(".%s.%s", extension, blob.getFileExtension()); } }
apache-2.0
murgo/MultiplayerLatencyTester
PingServer/src/fi/iki/murgo/pingserver/UdpPinger.java
2023
package fi.iki.murgo.pingserver; import java.io.IOException; import java.net.*; public class UdpPinger implements Runnable { private static final int PORT = 56666; private DatagramSocket mSocket; private final Object mSocketLock = new Object(); private volatile boolean mRunning = false; private DatagramPacket mReceivePacket; public boolean open() { mReceivePacket = new DatagramPacket(new byte[9], 9); try { mRunning = true; mSocket = new DatagramSocket(PORT); Thread t = new Thread(this); t.start(); } catch (SocketException e) { e.printStackTrace(); return false; } return true; } public void close() { mRunning = false; if (mSocket != null) { mSocket.close(); } } public void sendUdp(byte[] data, SocketAddress address) throws IOException { System.out.println("UDP - Sending to " + address); DatagramPacket packet = new DatagramPacket(data, data.length, address); synchronized (mSocketLock) { mSocket.send(packet); } } @Override public void run() { while (mRunning) { try { mSocket.receive(mReceivePacket); } catch (SocketException e) { System.out.println("UDP - Socket closed"); return; } catch (IOException e) { e.printStackTrace(); return; } byte[] buf = mReceivePacket.getData(); if (buf[0] == 'P') { System.out.println("UDP - Ping received from " + mReceivePacket.getSocketAddress()); // we were pinged, respond buf[0] = 'R'; try { sendUdp(buf, mReceivePacket.getSocketAddress()); } catch (IOException e) { e.printStackTrace(); } } } } }
apache-2.0
Haixing-Hu/commons
src/main/java/com/github/haixing_hu/collection/ArrayLinkedList.java
27096
/* * Copyright (c) 2014 Haixing Hu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.github.haixing_hu.collection; import java.io.Serializable; import java.util.AbstractSequentialList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import javax.annotation.Nullable; import com.github.haixing_hu.lang.Cloneable; import com.github.haixing_hu.util.expand.ExpansionPolicy; import static com.github.haixing_hu.lang.Argument.*; /** * An implementation of {@link List} which use an internal array buffer to store * the nodes and use the array current to simulate the link between nodes. * <p> * This implementation will has the benefits of {@link LinkedList} and avoid the * frequent memory allocations. * </p> * <p> * This implementation uses an array to store nodes of the list. Each node * contains the position of the previous node and the position of the next node. The * position of -1 denotes a nil node. All nodes in the array consist two list: the * allocated list and the free list. The allocated list is a * bidirectional-linked cycle list containing all allocated nodes (i.e., the nodes * used to store the elements), and the free list is a single direction linked * list containing all free nodes. The implementation also contains the position of * the head nodes of the allocated list and the free list. * </p> * * @author Haixing Hu */ public class ArrayLinkedList<E> extends AbstractSequentialList<E> implements Deque<E>, Cloneable<ArrayLinkedList<E>>, Serializable { private static final long serialVersionUID = 7384854819145629005L; /** * The class of nodes of the {@link ArrayLinkedList}. * * @author Haixing Hu */ protected static class Node implements Serializable { private static final long serialVersionUID = 5992909288570428948L; Object element = null; int previous = -1; int next = -1; } /** * The class of iterators of {@link ArrayLinkedList}. * * @author Haixing Hu */ protected class ListIter implements ListIterator<E> { protected int expectedModCount; protected int lastReturned; protected int index; protected int pos; protected ListIter(final int index) { this.expectedModCount = modCount; this.lastReturned = -1; this.index = requireIndexInCloseRange(index, 0, size); this.pos = getNodeAtIndex(index); } @Override public boolean hasNext() { return index < size; } @SuppressWarnings("unchecked") @Override public E next() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (index >= size) { throw new NoSuchElementException(); } final Node node = nodes[pos]; lastReturned = pos; pos = node.next; ++index; return (E) node.element; } @Override public boolean hasPrevious() { return (index > 0); } @SuppressWarnings("unchecked") @Override public E previous() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (index <= 0) { throw new NoSuchElementException(); } pos = nodes[pos].previous; --index; final Node node = nodes[pos]; lastReturned = pos; return (E) node.element; } @Override public int nextIndex() { return index; } @Override public int previousIndex() { return index - 1; } @Override public void remove() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (lastReturned < 0) { throw new IllegalStateException(); } final int lastNext = removeNode(lastReturned); ++expectedModCount; if (size == 0) { // deal with removing the last node pos = -1; index = 0; } else if (pos == lastReturned) { // the last call is previous() pos = lastNext; } else { // the last call is next() --index; } lastReturned = -1; } @Override public void set(final E e) { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } if (lastReturned < 0) { throw new IllegalStateException(); } nodes[lastReturned].element = e; } @Override public void add(final E e) { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } // add the new element if (size == capacity) { ensureCapacity(size + 1); } if (index < size) { assert ((size > 0) && (pos >= 0)); insertNodeBefore(pos, e); } else { // index == size // note that size may be zero, so we need to update the pos int tail = getTail(); tail = insertNodeAfter(tail, e); pos = nodes[tail].next; } ++index; ++expectedModCount; lastReturned = -1; } } /** * Adapter to provide descending iterators via {@link ListIter#previous()}. * * @author Haixing Hu */ protected class DescendingIter implements Iterator<E> { final ListIter iter = new ListIter(size); @Override public boolean hasNext() { return iter.hasPrevious(); } @Override public E next() { return iter.previous(); } @Override public void remove() { iter.remove(); } } protected ExpansionPolicy expansionPolicy; protected Node[] nodes; protected int capacity; protected int size; protected int head; protected int freeListHead; public ArrayLinkedList() { this(ExpansionPolicy.getInitialCapacity(), ExpansionPolicy.getDefault()); } public ArrayLinkedList(final int initialCapacity) { this(initialCapacity, ExpansionPolicy.getDefault()); } public ArrayLinkedList(final ExpansionPolicy expansionPolicy) { this(ExpansionPolicy.getInitialCapacity(), expansionPolicy); } public ArrayLinkedList(final int initialCapacity, final ExpansionPolicy expansionPolicy) { requireGreater("initialCapacity", initialCapacity, "zero", 0); this.capacity = initialCapacity; this.expansionPolicy = requireNonNull("expansionPolicy", expansionPolicy); this.nodes = new Node[capacity]; this.size = 0; this.head = - 1; // initialize the nodes array in order to avoid frequent memory allocation // makes all free nodes become a singly linked list for (int i = 0; i < this.capacity; ++i) { this.nodes[i] = new Node(); this.nodes[i].next = i + 1; } this.freeListHead = 0; this.nodes[this.capacity - 1].next = -1; } public ArrayLinkedList(final Collection<E> col) { this((col.isEmpty() ? ExpansionPolicy.getInitialCapacity() : col.size()), ExpansionPolicy.getDefault()); this.addAll(col); } public ArrayLinkedList(final Collection<E> col, final ExpansionPolicy expansionPolicy) { this((col.isEmpty() ? ExpansionPolicy.getInitialCapacity() : col.size()), expansionPolicy); this.addAll(col); } @Override public int size() { return size; } /** * Gets the current capacity of the internal node array. * * @return the current capacity of the internal node array. */ public int capacity() { return capacity; } /** * Gets the expansion policy of this list. * * @return the expansion policy of this list. */ public ExpansionPolicy getExpansionPolicy() { return expansionPolicy; } @Override public boolean isEmpty() { return (size == 0); } @Override public boolean contains(@Nullable final Object obj) { final int index = findNodeForward(head, head, obj); return (index >= 0); } @Override public Iterator<E> iterator() { return new ListIter(0); } @Override public boolean add(@Nullable final E e) { addLast(e); return true; } @Override public boolean remove(@Nullable final Object obj) { return removeFirstOccurrence(obj); } @Override public boolean containsAll(final Collection<?> col) { for (final Object obj : col) { final int pos = findNodeForward(head, head, obj); if (pos < 0) { return false; } } return true; } @Override public boolean addAll(final Collection<? extends E> col) { final int n = col.size(); if (n == 0) { return false; } final int newSize = size + n; if (newSize > capacity) { ensureCapacity(newSize); } int tail = getTail(); for (final E e : col) { tail = insertNodeAfter(tail, e); } return true; } @Override public boolean addAll(final int index, final Collection<? extends E> col) { if ((index < 0) || (index > size)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } final int n = col.size(); if (n == 0) { return false; } final int newSize = size + n; if (newSize > capacity) { ensureCapacity(newSize); } if (index < size) { assert (size > 0); final int pos = getNodeAtIndex(index); assert (pos >= 0); for (final E e : col) { insertNodeBefore(pos, e); } } else { // index == size, insert at the tail int tail = getTail(); for (final E e : col) { tail = insertNodeAfter(tail, e); } } return true; } @Override public boolean removeAll(final Collection<?> col) { if ((size == 0) || (col.size() == 0)) { return false; } boolean modified = false; int index = 0; int pos = head; while (index < size) { final Node node = nodes[pos]; if (col.contains(node.element)) { pos = removeNode(pos); modified = true; } else { pos = node.next; ++index; } } return modified; } @Override public boolean retainAll(final Collection<?> col) { if (size == 0) { return false; } if (col.size() == 0) { clear(); return true; } boolean modified = false; int index = 0; int pos = head; while (index < size) { final Node node = nodes[pos]; if (! col.contains(node.element)) { pos = removeNode(pos); modified = true; } else { pos = node.next; ++index; } } return modified; } @Override public void clear() { while (size > 0) { removeNode(head); } } @SuppressWarnings("unchecked") @Override public E get(final int index) { if ((index < 0) || (index >= size)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } final int pos = getNodeAtIndex(index); return (E) nodes[pos].element; } @Override public E set(final int index, @Nullable final E element) { if ((index < 0) || (index >= size)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } final int pos = getNodeAtIndex(index); @SuppressWarnings("unchecked") final E old = (E) nodes[pos].element; nodes[pos].element = element; return old; } @Override public void add(final int index, @Nullable final E element) { if ((index < 0) || (index > size)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } if (size == capacity) { ensureCapacity(size + 1); } if (index < size) { final int pos = getNodeAtIndex(index); insertNodeBefore(pos, element); } else { // index == size final int tail = getTail(); insertNodeAfter(tail, element); } } @Override public E remove(final int index) { if ((index < 0) || (index >= size)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } final int pos = getNodeAtIndex(index); @SuppressWarnings("unchecked") final E old = (E) nodes[pos].element; removeNode(pos); return old; } @Override public int indexOf(@Nullable final Object obj) { if (size == 0) { return -1; } int index = 0; int pos = head; if (obj == null) { do { final Node node = nodes[pos]; if (node.element == null) { return index; } pos = node.next; ++index; } while (pos != head); } else { // obj != null do { final Node node = nodes[pos]; if (obj.equals(node.element)) { return index; } pos = node.next; ++index; } while (pos != head); } return -1; } @Override public int lastIndexOf(final Object obj) { if (size == 0) { return -1; } final int tail = nodes[head].previous; int index = size - 1; int pos = tail; if (obj == null) { do { final Node node = nodes[pos]; if (node.element == null) { return index; } pos = node.previous; --index; } while (pos != tail); } else { // obj != null do { final Node node = nodes[pos]; if (obj.equals(node.element)) { return index; } pos = node.previous; --index; } while (pos != tail); } return -1; } @Override public ListIterator<E> listIterator() { return new ListIter(0); } @Override public ListIterator<E> listIterator(final int index) { return new ListIter(index); } @Override public void addFirst(@Nullable final E e) { if (size == capacity) { ensureCapacity(size + 1); } insertNodeBefore(head, e); } @Override public void addLast(@Nullable final E e) { if (size == capacity) { ensureCapacity(size + 1); } final int tail = getTail(); insertNodeAfter(tail, e); } @Override public boolean offerFirst(@Nullable final E e) { addFirst(e); return true; } @Override public boolean offerLast(@Nullable final E e) { addLast(e); return true; } @Override public E removeFirst() { if (size == 0) { throw new NoSuchElementException(); } @SuppressWarnings("unchecked") final E result = (E) nodes[head].element; removeNode(head); return result; } @Override public E removeLast() { if (size == 0) { throw new NoSuchElementException(); } final int tail = nodes[head].previous; @SuppressWarnings("unchecked") final E result = (E) nodes[tail].element; removeNode(tail); return result; } @Override public E pollFirst() { if (size == 0) { return null; } @SuppressWarnings("unchecked") final E result = (E) nodes[head].element; removeNode(head); return result; } @Override public E pollLast() { if (size == 0) { return null; } final int tail = nodes[head].previous; @SuppressWarnings("unchecked") final E result = (E) nodes[tail].element; removeNode(tail); return result; } @SuppressWarnings("unchecked") @Override public E getFirst() { if (size == 0) { throw new NoSuchElementException(); } return (E) nodes[head].element; } @SuppressWarnings("unchecked") @Override public E getLast() { if (size == 0) { throw new NoSuchElementException(); } final int tail = nodes[head].previous; return (E) nodes[tail].element; } @SuppressWarnings("unchecked") @Override public E peekFirst() { if (size == 0) { return null; } else { return (E) nodes[head].element; } } @SuppressWarnings("unchecked") @Override public E peekLast() { if (size == 0) { return null; } else { final int tail = nodes[head].previous; return (E) nodes[tail].element; } } @Override public boolean removeFirstOccurrence(@Nullable final Object obj) { final int pos = findNodeForward(head, head, obj); if (pos < 0) { return false; } else { removeNode(pos); return true; } } @Override public boolean removeLastOccurrence(@Nullable final Object obj) { final int tail = getTail(); final int pos = findNodeBackward(tail, tail, obj); if (pos < 0) { return false; } else { removeNode(pos); return true; } } @Override public boolean offer(@Nullable final E e) { return offerLast(e); } @Override public E remove() { return removeFirst(); } @Override public E poll() { return pollFirst(); } @Override public E element() { return getFirst(); } @Override public E peek() { return peekFirst(); } @Override public void push(@Nullable final E e) { addFirst(e); } @Override public E pop() { return removeFirst(); } @Override public Iterator<E> descendingIterator() { return new DescendingIter(); } /** * Returns a shallow copy of this {@link ArrayLinkedList}. (The elements * themselves are not cloned.) * * @return a shallow copy of this {@link ArrayLinkedList} instance. */ @Override public ArrayLinkedList<E> clone() { return new ArrayLinkedList<E>(this, this.expansionPolicy); } /** * Ensures the capacity of the node array to be able to hold the nodes of the * specified count. * * @param count * the number of nodes need to be hold by the node array. It MUST be * greater than the current capacity. */ protected final void ensureCapacity(final int count) { assert (capacity < count); nodes = expansionPolicy.expand(nodes, capacity, count, Node.class); assert (count <= nodes.length); for (int i = capacity; i < nodes.length; ++i) { nodes[i] = new Node(); // may throw OutOfMemoryError nodes[i].next = i + 1; } // add the new nodes list to the free list nodes[nodes.length - 1].next = freeListHead; freeListHead = capacity; capacity = nodes.length; } /** * Gets the position of the tail (last node) of the list. * * @return the position of the tail of the list, or -1 if the list is empty. */ protected final int getTail() { return (head < 0 ? -1 : nodes[head].previous); } /** * Removes a node from the list. * * @param pos * the position of the node to be removed. * @return the position of the node next to the node just removed. If the node * just removed is the last node, returns -1. */ protected final int removeNode(final int pos) { assert ((size > 0) && (pos >= 0) && (pos < capacity)); final Node node = nodes[pos]; int result = -1; if (node.next != pos) { // this is NOT the sole node result = node.next; nodes[node.next].previous = node.previous; nodes[node.previous].next = node.next; if (head == pos) { head = node.next; } } else { // node.next == pos // this is the sole node assert (head == pos); head = -1; } // dereference the element so that it could be garbage collected node.element = null; // add the node to the free list node.next = freeListHead; freeListHead = pos; // update the state --size; ++modCount; return result; } /** * Inserts an element before the specified node of the non-empty list. * <p> * The node array MUST have enough free space before calling this function. * </p> * * @param pos * the position of the node before which to insert the new element. * If the list is empty before calling this function, this argument * must be -1. * @param e * the element to be inserted. * @return the position of the new node inserted by this function. */ protected final int insertNodeBefore(final int pos, final E e) { assert ((size < capacity) && (freeListHead >= 0)); // get a free node final int newPos = freeListHead; final Node newNode = nodes[newPos]; freeListHead = newNode.next; // set the element of the new node newNode.element = e; // insert the new node if (pos >= 0) { // the list is non-empty before calling this function final Node nextNode = nodes[pos]; final Node prevNode = nodes[nextNode.previous]; newNode.next = pos; newNode.previous = nextNode.previous; nextNode.previous = newPos; prevNode.next = newPos; // update the head of allocated list if necessary if (head == pos) { head = newPos; } } else { // pos < 0 // the list is empty before calling this function // construct a sole node cycle list newNode.next = newPos; newNode.previous = newPos; assert (head < 0); head = newPos; } // update the state ++size; ++modCount; return newPos; } /** * Inserts an element after the specified node of the non-empty list. * <p> * The node array MUST have enough free space before calling this function. * </p> * * @param pos * the position of the node after which to insert the new element. If * the list is empty before calling this function, this argument must * be -1. * @param e * the element to be inserted. * @return the position of the new node inserted by this function. */ protected final int insertNodeAfter(final int pos, final E e) { assert ((size < capacity) && (freeListHead >= 0)); // get a free node final int newPos = freeListHead; final Node newNode = nodes[newPos]; freeListHead = newNode.next; // set the element of the new node newNode.element = e; // insert the new node if (pos >= 0) { // the list is non-empty before calling this function final Node prevNode = nodes[pos]; final Node nextNode = nodes[prevNode.next]; newNode.previous = pos; newNode.next = prevNode.next; prevNode.next = newPos; nextNode.previous = newPos; // don't need to update the head of allocated list } else { // pos < 0 // the list is empty before calling this function // construct a sole node cycle list newNode.next = newPos; newNode.previous = newPos; assert (head < 0); head = newPos; } // update the state ++size; ++modCount; return newPos; } /** * Gets the node at the specified index of the list. * <p> * The allowed index ranges from 0 to the size of the list. If the index is the * size of the list, gets the node next to the last node of the list, which is * also the head node of the list, since the list is a bidirectional cycle. * </p> * @param index * the index of the node to be get. It must be in the range of * {@code [0, size]}. * @return the position of the node at the specified index in the list. */ protected final int getNodeAtIndex(final int index) { assert ((index >= 0) && (index <= size)); if (size == 0) { return -1; } if (index <= (size / 2)) { int pos = head; for (int i = 0; i < index; ++i) { pos = nodes[pos].next; } return pos; } else { int pos = head; for (int i = size; i > index; --i) { pos = nodes[pos].previous; } return pos; } } /** * Finds the first occurrence of the specified element in the allocated list * in the forward direction. * * @param startPos * the position of the node where the search starts. If the list is * empty before calling this function, this argument must be -1, and * this function will returns -1. * @param stopPos * the position of the node next to the node where the search ends. * If it is the same as {@code startPos}, the whole list will be * searched, since the list is a cycle. If the list is empty before * calling this function, this argument must be -1, and this function * will returns -1. * @param obj * the object to be found, which could be null. * @return the position of the node where the specified element first * occurred, or -1 if no such node. */ protected final int findNodeForward(final int startPos, final int stopPos, @Nullable final Object obj) { if (startPos < 0) { return -1; } int pos = startPos; if (obj == null) { do { final Node node = nodes[pos]; if (node.element == null) { return pos; } pos = node.next; } while (pos != stopPos); } else { // obj != null do { final Node node = nodes[pos]; if (obj.equals(node.element)) { return pos; } pos = node.next; } while (pos != stopPos); } return -1; } /** * Finds the first occurrence of the specified element in the allocated list * in the backward direction. * * @param startPos * the position of the node where the search starts. If the list is * empty before calling this function, this argument must be -1, and * this function will returns -1. * @param stopPos * the position of the node previous to the node where the search * ends. If it is the same as {@code startPos}, the whole list * will be searched, since the list is a cycle. If the list is empty * before calling this function, this argument must be -1, and this * function will returns -1. * @param obj * the object to be found, which could be null. * @return the position of the node where the specified element first * occurred, or -1 if no such node. */ protected final int findNodeBackward(final int startPos, final int stopPos, @Nullable final Object obj) { if (startPos < 0) { return -1; } int pos = startPos; if (obj == null) { do { final Node node = nodes[pos]; if (node.element == null) { return pos; } pos = node.previous; } while (pos != stopPos); } else { // obj != null do { final Node node = nodes[pos]; if (obj.equals(node.element)) { return pos; } pos = node.previous; } while (pos != stopPos); } return -1; } }
apache-2.0
sunvar/pwd-gnt-app
src/main/java/com/mma/trion/marketlink/application/config/SecurityConfiguration.java
6515
package com.mma.trion.marketlink.application.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties; import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.WebUtils; @Configuration @EnableOAuth2Client public class SecurityConfiguration extends WebSecurityConfigurerAdapter { //getAccessTokenRequest and add username and password here into this @Autowired OAuth2ClientContext oauth2ClientContext; @Value("${security.oauth2.client.clientId}") private String clientId; @Value("${security.oauth2.client.clientSecret}") private String clientSecret; @Value("${security.oauth2.client.accessTokenUri}") private String accessTokenUri; /* Match everything without a suffix (so not a static resource) */ /*@RequestMapping(value = "/{path:[^\\.]*}") public String redirect() { *//** Forward to home page so that route is preserved. **//* return "forward:/"; }*/ @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/**") .authorizeRequests() .antMatchers("/", "/login**", "/webjars/**").permitAll() .anyRequest().authenticated() .and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")) .and().logout().logoutSuccessUrl("/").permitAll() .and().csrf().csrfTokenRepository(csrfTokenRepository()) .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class) //.and().csrf().disable() .addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class); ; } private Filter ssoFilter() { CustomOAuth2ClientAuthenticationProcessingFilter customOAuth2ClientAuthenticationProcessingFilter = new CustomOAuth2ClientAuthenticationProcessingFilter("/login"); this.setAuthenticationConfiguration(null); //OAuth2ClientAuthenticationProcessingFilter oAuth2ClientAuthenticationProcessingFilter = new OAuth2ClientAuthenticationProcessingFilter("/login/wso2"); OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(oauth2ProtectedResourceDetails(), oauth2ClientContext); customOAuth2ClientAuthenticationProcessingFilter.setRestTemplate(oAuth2RestTemplate); customOAuth2ClientAuthenticationProcessingFilter.setTokenServices(new UserInfoTokenServices(resourceServerProperties().getUserInfoUri(), oauth2ProtectedResourceDetails().getClientId())); return customOAuth2ClientAuthenticationProcessingFilter; } @Bean @ConfigurationProperties("security.oauth2.client") public OAuth2ProtectedResourceDetails oauth2ProtectedResourceDetails() { OAuth2ProtectedResourceDetails details = new ResourceOwnerPasswordResourceDetails(); return details; } @Bean @ConfigurationProperties("security.oauth2.resource") ResourceServerProperties resourceServerProperties() { return new ResourceServerProperties(); } @Bean public FilterRegistrationBean oauth2ClientFilterRegistration( CustomOAuth2ClientAuthenticationProcessingFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(filter); registration.setOrder(-100); return registration; } private Filter csrfHeaderFilter() { return new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie("XSRF-TOKEN", token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }; } private CsrfTokenRepository csrfTokenRepository() { HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); repository.setHeaderName("X-XSRF-TOKEN"); return repository; } }
apache-2.0
jimmyLian001/SpringLearn
src/main/java/com/jimmy/common/impl/KLineCombineChartImpl.java
8641
package com.jimmy.common.impl; import org.jfree.chart.ChartFrame; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.*; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.CandlestickRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.data.time.Day; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.ohlc.OHLCSeries; import org.jfree.data.time.ohlc.OHLCSeriesCollection; import java.awt.*; import java.text.SimpleDateFormat; public class KLineCombineChartImpl { public static void main(String[] args) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// double highValue = Double.MIN_VALUE;// double minValue = Double.MAX_VALUE;// double high2Value = Double.MIN_VALUE;// double min2Value = Double.MAX_VALUE;// OHLCSeries series = new OHLCSeries("");// series.add(new Day(28, 9, 2007), 9.2, 9.58, 9.16, 9.34); series.add(new Day(27, 9, 2007), 8.9, 9.06, 8.83, 8.96); series.add(new Day(26, 9, 2007), 9.0, 9.1, 8.82, 9.04); series.add(new Day(25, 9, 2007), 9.25, 9.33, 8.88, 9.00); series.add(new Day(24, 9, 2007), 9.05, 9.50, 8.91, 9.25); series.add(new Day(21, 9, 2007), 8.68, 9.05, 8.40, 9.00); series.add(new Day(20, 9, 2007), 8.68, 8.95, 8.50, 8.69); series.add(new Day(19, 9, 2007), 8.80, 8.94, 8.50, 8.66); series.add(new Day(18, 9, 2007), 8.88, 9.17, 8.69, 8.80); series.add(new Day(17, 9, 2007), 8.26, 8.98, 8.15, 8.89); series.add(new Day(14, 9, 2007), 8.44, 8.45, 8.13, 8.33); series.add(new Day(13, 9, 2007), 8.13, 8.46, 7.97, 8.42); series.add(new Day(12, 9, 2007), 8.2, 8.4, 7.81, 8.13); series.add(new Day(11, 9, 2007), 9.0, 9.0, 8.1, 8.24); series.add(new Day(10, 9, 2007), 8.6, 9.03, 8.40, 8.95); series.add(new Day(7, 9, 2007), 8.89, 9.04, 8.70, 8.73); series.add(new Day(6, 9, 2007), 8.4, 9.08, 8.33, 8.88); series.add(new Day(5, 9, 2007), 8.2, 8.74, 8.17, 8.36); series.add(new Day(4, 9, 2007), 7.7, 8.46, 7.67, 8.27); series.add(new Day(3, 9, 2007), 7.5, 7.8, 7.48, 7.69); series.add(new Day(31, 8, 2007), 7.4, 7.6, 7.28, 7.43); series.add(new Day(30, 8, 2007), 7.42, 7.56, 7.31, 7.40); series.add(new Day(29, 8, 2007), 7.42, 7.66, 7.22, 7.33); series.add(new Day(28, 8, 2007), 7.31, 7.70, 7.15, 7.56); series.add(new Day(27, 8, 2007), 7.05, 7.46, 7.02, 7.41); series.add(new Day(24, 8, 2007), 7.05, 7.09, 6.90, 6.99); series.add(new Day(23, 8, 2007), 7.12, 7.16, 7.00, 7.03); series.add(new Day(22, 8, 2007), 6.96, 7.15, 6.93, 7.11); series.add(new Day(21, 8, 2007), 7.10, 7.15, 7.02, 7.07); series.add(new Day(20, 8, 2007), 7.02, 7.19, 6.94, 7.14); final OHLCSeriesCollection seriesCollection = new OHLCSeriesCollection();// seriesCollection.addSeries(series); TimeSeries series2=new TimeSeries("");// series2.add(new Day(28, 9, 2007), 260659400/100); series2.add(new Day(27, 9, 2007), 119701900/100); series2.add(new Day(26, 9, 2007), 109719000/100); series2.add(new Day(25, 9, 2007), 178492400/100); series2.add(new Day(24, 9, 2007), 269978500/100); series2.add(new Day(21, 9, 2007), 361042300/100); series2.add(new Day(20, 9, 2007), 173912600/100); series2.add(new Day(19, 9, 2007), 154622600/100); series2.add(new Day(18, 9, 2007), 200661600/100); series2.add(new Day(17, 9, 2007), 312799600/100); series2.add(new Day(14, 9, 2007), 141652900/100); series2.add(new Day(13, 9, 2007), 221260400/100); series2.add(new Day(12, 9, 2007), 274795400/100); series2.add(new Day(11, 9, 2007), 289287300/100); series2.add(new Day(10, 9, 2007), 289063600/100); series2.add(new Day(7, 9, 2007), 351575300/100); series2.add(new Day(6, 9, 2007), 451357300/100); series2.add(new Day(5, 9, 2007), 442421200/100); series2.add(new Day(4, 9, 2007), 671942600/100); series2.add(new Day(3, 9, 2007), 349647800/100); series2.add(new Day(31, 8, 2007), 225339300/100); series2.add(new Day(30, 8, 2007), 160048200/100); series2.add(new Day(29, 8, 2007), 247341700/100); series2.add(new Day(28, 8, 2007), 394975400/100); series2.add(new Day(27, 8, 2007), 475797500/100); series2.add(new Day(24, 8, 2007), 297679500/100); series2.add(new Day(23, 8, 2007), 191760600/100); series2.add(new Day(22, 8, 2007), 232570200/100); series2.add(new Day(21, 8, 2007), 215693200/100); series2.add(new Day(20, 8, 2007), 200287500/100); TimeSeriesCollection timeSeriesCollection=new TimeSeriesCollection();// timeSeriesCollection.addSeries(series2); // int seriesCount = seriesCollection.getSeriesCount();// for (int i = 0; i < seriesCount; i++) { int itemCount = seriesCollection.getItemCount(i);// for (int j = 0; j < itemCount; j++) { if (highValue < seriesCollection.getHighValue(i, j)) {// highValue = seriesCollection.getHighValue(i, j); } if (minValue > seriesCollection.getLowValue(i, j)) {// minValue = seriesCollection.getLowValue(i, j); } } } // int seriesCount2 = timeSeriesCollection.getSeriesCount();// for (int i = 0; i < seriesCount2; i++) { int itemCount = timeSeriesCollection.getItemCount(i);// for (int j = 0; j < itemCount; j++) { if (high2Value < timeSeriesCollection.getYValue(i, j)) {// high2Value = timeSeriesCollection.getYValue(i, j); } if (min2Value > timeSeriesCollection.getYValue(i, j)) {// min2Value = timeSeriesCollection.getYValue(i, j); } } } final CandlestickRenderer candlestickRender = new CandlestickRenderer();// candlestickRender.setUseOutlinePaint(true); // candlestickRender.setAutoWidthMethod(CandlestickRenderer.WIDTHMETHOD_AVERAGE);// candlestickRender.setAutoWidthGap(0.001);// candlestickRender.setUpPaint(Color.RED);// candlestickRender.setDownPaint(Color.GREEN);// DateAxis x1Axis = new DateAxis();// x1Axis.setAutoRange(false);// try { x1Axis.setRange(dateFormat.parse("2007-08-20"), dateFormat.parse("2007-09-29"));// } catch (Exception e) { e.printStackTrace(); } x1Axis.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());// x1Axis.setAutoTickUnitSelection(false);// x1Axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);// x1Axis.setStandardTickUnits(DateAxis.createStandardDateTickUnits());// x1Axis.setTickUnit(new DateTickUnit(DateTickUnit.DAY, 7));// x1Axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM-dd"));// NumberAxis y1Axis = new NumberAxis();// y1Axis.setAutoRange(false);// y1Axis.setRange(minValue * 0.9, highValue * 1.1);// y1Axis.setTickUnit(new NumberTickUnit((highValue * 1.1 - minValue * 0.9) / 10));// XYPlot plot1 = new XYPlot(seriesCollection, x1Axis, y1Axis, candlestickRender);// XYBarRenderer xyBarRender = new XYBarRenderer() { private static final long serialVersionUID = 1L;// public Paint getItemPaint(int i, int j) {// if (seriesCollection.getCloseValue(i, j) > seriesCollection.getOpenValue(i, j)) {// return candlestickRender.getUpPaint(); } else { return candlestickRender.getDownPaint(); } } }; xyBarRender.setMargin(0.1);// NumberAxis y2Axis = new NumberAxis();// y2Axis.setAutoRange(false); y2Axis.setRange(min2Value * 0.9, high2Value * 1.1); y2Axis.setTickUnit(new NumberTickUnit((high2Value * 1.1 - min2Value * 0.9) / 4)); XYPlot plot2 = new XYPlot(timeSeriesCollection, null, y2Axis, xyBarRender);// CombinedDomainXYPlot combineddomainxyplot = new CombinedDomainXYPlot(x1Axis);// combineddomainxyplot.add(plot1, 2);// combineddomainxyplot.add(plot2, 1);// combineddomainxyplot.setGap(10);// JFreeChart chart = new JFreeChart("汇率K线图", JFreeChart.DEFAULT_TITLE_FONT, combineddomainxyplot, false); ChartFrame frame = new ChartFrame("K线展示", chart); frame.pack(); frame.setVisible(true); } }
apache-2.0
ringlelai/HSDcDesignPattern-Java
design-pattern-intf/src/main/java/com/hsdc/dp/intf/dto/builder/Leave.java
1036
package com.hsdc.dp.intf.dto.builder; import java.io.Serializable; import java.util.Date; public class Leave implements Serializable { /** * */ private static final long serialVersionUID = -380920585101902853L; private String leaveID; private String applier; private String leaveType; private int leaveDay; private Date leaveBeginDate; public String getLeaveID() { return leaveID; } public void setLeaveID(String leaveID) { this.leaveID = leaveID; } public String getApplier() { return applier; } public void setApplier(String applier) { this.applier = applier; } public String getLeaveType() { return leaveType; } public void setLeaveType(String leaveType) { this.leaveType = leaveType; } public int getLeaveDay() { return leaveDay; } public void setLeaveDay(int leaveDay) { this.leaveDay = leaveDay; } public Date getLeaveBeginDate() { return leaveBeginDate; } public void setLeaveBeginDate(Date leaveBeginDate) { this.leaveBeginDate = leaveBeginDate; } }
apache-2.0
finiteV/quickget
src/quickget/DownThread.java
2263
package quickget; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; /** * 多线程下载工具类,多线程写入单个文件 * @author book *@tempSize表示已经下载的部分,@start表示输入流开始位置 */ class DownThread extends Thread{ final int BUFF_LEN =1024; private InputStream fin; private RandomAccessFile fout; private long start; private long end; long tempSize; long totalRead=0;//这个线程的实际读取的大小 DownThread(long tempSize,long start,long end,InputStream fin,RandomAccessFile fout){ super(); this.fin = fin; this.fout = fout; this.start = start; this.end = end; this.tempSize=tempSize; } public void run(){ try{ //判断是否还需要下载 if(0<(end-start)){//问题在这里 //输入流跳过部分,设置分段请求可略 //fin.skip(start+tempSize); fout.seek(tempSize); //long buffTimes = (end-start)/BUFF_LEN; //写入数据 byte[] buf = new byte[BUFF_LEN] ; int hasRead=0; long length = end -start;//剩余写入长度 /********Test*************/ //System.out.println("这个部分应该写入"+length); /******************/ //实际写入的总是大于应该写入的,totalread表示实际读入,length表示应该写入 while(((hasRead=fin.read(buf))!=-1) && (totalRead<length)){ fout.write(buf,0,hasRead); totalRead+=hasRead; //buf = new byte[BUFF_LEN] ; //空出线程资源,限制下载速度,一般要禁止 //try{ //Thread.sleep((int)(Math.random()*50)); //} //catch(InterruptedException e){ //System.out.println("线程异常终止"); //} } //实际写入内容大小 //System.out.println("线程实际写入"+totalRead); } else { totalRead=tempSize; //System.out.println("这个线程已经写入"+totalRead); } }catch(IOException e){ e.printStackTrace(); } finally{ try{ //关闭输入输出流 fin.close(); fout.close(); }catch(IOException e){ System.out.println("cannot download the file!"); e.printStackTrace(); } } } //long displayNumber(){ //System.out.println("这个线程已经写入"+finished); //return finished; //} }
apache-2.0
GeowindOfAgriculture/MutualAgriculture
com/usc/util/SQlUtil.java
3143
package com.usc.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.usc.bean.Order; /** * 数据库的工具类 主要是数据库的增改操作 单例实现 * * @author lilin * @time 2016年1月11日 下午5:12:10 * @email gaosi0812@gmail.com * @blog gaosililin.iteye.com * @school USC */ public class SQlUtil { private static SQlUtil sqlUtil = null; private SQlUtil() { } /** * 获取数据库的工具类 * * @return */ public static SQlUtil getSQLUtil() { if (sqlUtil == null) { sqlUtil = new SQlUtil(); } return sqlUtil; } /** * 执行sql 修改表的属性 * * @param sql * 需要执行的sql * @param connection * 数据库链接对象 Connection * @return 是否修改成功 */ public boolean update(String sql, Connection connection) { boolean succeed = false; // sql不为空且不为“” if (sql != null && !("".equals(sql))) { try { // 链接 Statement statement = connection.createStatement(); // 执行sql修改表的字段 int update = statement.executeUpdate(sql); // 根据受影响的行数是否大于0 判断是否修改成功 if (update > 0) { succeed = true; } else { succeed = false; } } catch (SQLException e) { succeed = false; e.printStackTrace(); } } else { succeed = false; } return succeed; } /** * 执行SQL获取订单 * * @param sql * 需要执行的sql * @param connection * 数据库链接对象 Connection * @return 返回订单的队列 */ public ArrayList<Order> getOrders(String sql, Connection connection) { ArrayList<Order> orders = new ArrayList<Order>(); try { // 链接数据库 Statement statement = connection.createStatement(); // 向数据库中查询 获取结果集 ResultSet resultSet = statement.executeQuery(sql); // 订单实体 Order order = null; // 循环读取结果集 while (resultSet.next()) { order = new Order(); // 获取ID并封装 order.setId(resultSet.getInt(Constant.ID_ORDER)); // 获取数量并封装 order.setNum(resultSet.getInt(Constant.NUM_ORDER)); // 获取结果并封装 order.setCommission(resultSet.getDouble(Constant.COMMISSION_ORDER)); // 获取开始时间并封装 order.setStartTime(resultSet.getDate(Constant.STARTTME_ORDER)); // 获取结束时间并封装 order.setEndTime(resultSet.getDate(Constant.ENDTIME_ORDER)); // 获取农田id并封装 order.setFarmlandId(resultSet.getInt(Constant.FARMLANDID_ORDER)); // 获取农村经济人id并封装 order.setAgentId(resultSet.getInt(Constant.AGENTID_ORDER)); // 获取农机主id并封装 order.setMachineOwnerId(resultSet.getInt(Constant.MACHINEOWNERID_ORDER)); //获取状态并封装 order.setState(resultSet.getString(Constant.STATE_ORDER)); // 将数据对象保存进队列当总 orders.add(order); } } catch (SQLException e) { e.printStackTrace(); } return orders; } }
apache-2.0
BeyondSkyCoder/BeyondCoder
leetcode/java/AlgoBinarysearchSort/AlgoBasicSortingComparison.java
13104
package AlgoBinarysearchSort; /* SORT is well studied, classic algorithms trade off is memory vs speed Other factors are stable, adaptive, worse case O(?) O(NlogN) is practically used MergeSort and QuickSort are efficient and good for general cases O(n^2) other sorts like selection/insertion/bubblesort are only used for special case like small or almost sorted array. */ import java.util.Random; public class AlgoBasicSortingComparison { // Selection Sort, O(n^2) // ======================== // start from offset 0, then 1, record it as smallest // compare with the rest of array, if there is smaller, swap // // in-place algorithm, not stable // requires at most n-1 swaps, good for expensive data moving system public void SelectionSort() { int smallest; for (int out = 0; out < data.length - 1; out++) { // find the index of smallest value smallest = out; for (int inner = out + 1; inner < data.length; inner++) { if (data[inner] < data[smallest]) smallest = inner; } swap(out, smallest); } } // Insertion Sort, O(n^2) // ======================== // outer loop starts from 1, inner loop start from 0 to outer loop // in-place algorithm, stable public void InsertionSort() { int cur; for (int out = 1; out < data.length; out++) { // save data to be inserted cur = data[out]; for (int inner = 0; inner < out; inner++) { if (cur <= data[inner]) { // shift right one space to empty a spot System.arraycopy(data, inner, data, inner + 1, out - inner); data[inner] = cur; // after one insert, break, no need to check others in this inner loop // this is because outer loop start from 1 and it ensures all previous elements // are already sorted in previous inner loop runs break; } } } } public void InsertionSort_passinData(int[] da1, int start, int end) { int insert; // Note, outer loop starts from 1, inner loop start from 0 to outer loop for (int next = start + 1; next < end; next++) { insert = da1[next]; for (int i = start; i < next; i++) { if (data[i] > insert) { // shift right to empty a spot System.arraycopy(data, i, data, i + 1, next - i); data[i] = insert; // after one insert, break, no need to check others in this inner loop // this is because outer loop start from 1 and it ensures all previous elements // are already sorted in previous inner loop runs break; } } } } // Bubble Sort, O(n^2) // ======================== // scan through the whole list repeatedly. compare neighbor and swap // stop when no swap was done in previous scan // most simple one. used rarely public void bubblesort() { int j; boolean swapflag = true; while (swapflag) { swapflag = false; for (j = 0; j < data.length - 1; j++) { if (data[j] < data[j + 1]) { swap(j, j + 1); swapflag = true; } } } } // // Merge Sort, O(nlog(n)), very important concept. // ======================== // merge step does the heavylifting. // PROS: the best, average and worse-case running times are all __O(nlog(n))__ // CONS: requires O(n) additional memory. For a large dataset, they need to be split into multiple smaller files to fit memory // public void MergeSort() { MergeSortRecursive(data, 0, data.length - 1); } public void MergeSortRecursive(int[] dat, int low, int high) { if ((high - low) < 2) { // can call other type of Sort algorithm like if ((high - low) < 10), insertionSort(); return; } int middle = (low + high) / 2; MergeSortRecursive(dat, low, middle); MergeSortRecursive(dat, middle + 1, high); util_mergeArray(dat, low, middle, middle + 1, high); } // merge two sorted list. This alone is a typical interview coding question private void util_mergeArray(int[] dat, int left, int middle1, int middle2, int right) { int lIndex = left; int rIndex = middle2; int c = left; int[] combined = new int[dat.length]; // new array to save combining results // A. merge two subarrays while there are elements in both while (lIndex <= middle1 && rIndex <= right) { if (dat[lIndex] <= dat[rIndex]) { combined[c++] = dat[lIndex++]; } else { combined[c++] = dat[rIndex++]; } } // B. copy rest of whichever array remains if (lIndex == middle2) { // left array is empty while (rIndex <= right) { combined[c++] = dat[rIndex++]; } } else { while (lIndex <= middle1) { combined[c++] = dat[lIndex++]; } } // C. copy back, only touch those elements sorted in this round of merge for (int i = left; i <= right; i++) { // this assumes middle2 = middle1+1. otherwise, need to handle that dat[i] = combined[i]; } } public String util_subarray(int low, int high) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < low; i++) { sb.append(" "); } for (int i = low; i <= high; i++) { sb.append(" "); sb.append(data[i]); } return sb.toString(); } public String toString() { return util_subarray(0, data.length - 1); } // Quicksort, most powerful // ======================== // PROS: best and average case are O(nlog(n)) // CONS: worse case is O(n^2) // divide-and-conquer, efficiency depends on the pivot value // Simple solution requires extra memory while optimized solution doesn't public int[] quicksortI_Simple(int[] dat) { if (dat.length < 2) { return dat; } int pivotIndex = dat.length / 2; int pivotValue = dat[pivotIndex]; int leftCount = 0; // A. count how many are less than the pivot for (int i = 0; i < dat.length; i++) { if (dat[i] < pivotValue) { ++leftCount; } } // B. Allocate the arrays and create the subsets int[] left = new int[leftCount]; int[] right = new int[dat.length - leftCount]; int l = 0, r = 0; for (int i = 0; i < dat.length; i++) { if (i == pivotIndex) continue; int val = dat[i]; if (val < pivotValue) { left[l++] = val; } else { right[r++] = val; } } // C. Sort the subsets left = quicksortI_Simple(left); right = quicksortI_Simple(right); // D. combine the sorted arrays and the pivot back into the original array System.arraycopy(left, 0, dat, 0, left.length); dat[left.length] = pivotValue; System.arraycopy(right, 0, dat, left.length + 1, right.length); return dat; } // // QuicksortII without extra memory // public void quicksortOptimized(int[] dat) { quicksortII_NoExtraMemory(dat, 0, data.length - 1); } public void quicksortII_NoExtraMemory(int[] dat, int left, int right) { int pivotValue = dat[(left + right) / 2]; int i = left; int j = right; // create subsets, in-place swap while (i <= j) { // find the leftmost value greater or equal to pivot while (dat[i] < pivotValue) i++; // find the rightmost value less or equal to pivot while (dat[j] > pivotValue) j--; // value equals to the pivot may end up in either partition. But Sort is still correct // if the values are in the wrong order, swap them if (i <= j) { swaparrayindex(dat, i, j); i++; j--; } } // apply the algorithm to the partitions we made, if any quicksortII_NoExtraMemory(dat, left, i); quicksortII_NoExtraMemory(dat, j, right); } // // Shell Sort, O(NLogN) // ======================== public void ShellSort(Comparable[] a) { int N = a.length; // 3x+1 increment sequence: 1, 4, 13, 40, 121, 364, 1093, ... int h = 1; while (h < N / 3) { h = 3 * h + 1; } while (h >= 1) { // h-Sort the array for (int i = h; i < N; i++) { for (int j = i; j >= h && sortUtilLess(a[j], a[j - h]); j -= h) { exch(a, j, j - h); } } assert isHsorted(a, h); h /= 3; } assert isSorted(a); } // is v < w ? private boolean sortUtilLess(Comparable v, Comparable w) { return (v.compareTo(w) < 0); } /* debugging routine */ private boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) if (sortUtilLess(a[i], a[i - 1])) return false; return true; } // is the array h-sorted? private boolean isHsorted(Comparable[] a, int h) { for (int i = h; i < a.length; i++) if (sortUtilLess(a[i], a[i - h])) return false; return true; } // Heap Sort, O(NLogN) // ======================== public void sort(Comparable[] pq) { int N = pq.length; for (int k = N / 2; k >= 1; k--) { sink(pq, k, N); } while (N > 1) { exch(pq, 1, N--); sink(pq, 1, N); } } /* Helper functions to restore the heap invariant */ private void sink(Comparable[] pq, int k, int N) { while (2 * k <= N) { int j = 2 * k; if (j < N && heapSortUtilless(pq, j, j + 1)) { j++; } if (!heapSortUtilless(pq, k, j)) { break; } exch(pq, k, j); k = j; } } /* * Indices are "off-by-one" to support 1-based indexing. */ private boolean heapSortUtilless(Comparable[] pq, int i, int j) { return pq[i - 1].compareTo(pq[j - 1]) < 0; } // Other utilities // exchange a[i] and a[j] public void exch(Object[] a, int i, int j) { Object swap = a[i]; a[i] = a[j]; a[j] = swap; } public void swap(int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } public void swaparrayindex(int[] indata, int i, int j) { int temp = indata[i]; indata[i] = indata[j]; indata[j] = temp; } private static final Random gen = new Random(); private int[] data; public AlgoBasicSortingComparison(int size) { data = new int[size]; for (int k = 0; k < size; k++) { data[k] = gen.nextInt(50); } } public static void main(String[] args) { // selectionsort ss = new SelectionSort(); int i; final Random gen = new Random(); int[] listtosort = new int[30]; for (i = 0; i < 30; i++) { listtosort[i] = gen.nextInt(90); } for (int it : listtosort) { System.out.printf("%d ", it); } System.out.printf("before Sort\n"); // TODO listtosort = selectionsort (listtosort); for (int it : listtosort) { System.out.printf("%d ", it); } System.out.printf("after Sort\n"); } public String util_remainingElements(int low, int high) { StringBuilder temp = new StringBuilder(); for (int i = 0; i < low; i++) temp.append(" "); for (int i = low; i <= high; i++) temp.append(data[i] + " "); temp.append("\n"); return temp.toString(); } public String toString_touse() { return util_remainingElements(0, data.length - 1); } }
apache-2.0
fangyucun/android-library
base-utils/src/main/java/com/hellofyc/base/security/Base64Utils.java
1887
package com.hellofyc.base.security; import android.support.annotation.NonNull; import android.util.Base64; import com.hellofyc.base.utils.FLog; import java.io.UnsupportedEncodingException; /** * Created on 2015/9/7. * * @author Yucun Fang */ public class Base64Utils { private static final boolean DEBUG = false; public static byte[] encode(@NonNull String data) { return encode(data.getBytes()); } public static byte[] encode(@NonNull byte[] data) { try { return Base64.encode(data, Base64.DEFAULT); } catch (Exception e) { if (DEBUG) FLog.e(e); } return null; } public static String encodeToString(@NonNull String data) { return encodeToString(data.getBytes()); } public static String encodeToString(@NonNull byte[] data) { try { return Base64.encodeToString(data, Base64.DEFAULT); } catch (Exception e) { if (DEBUG) FLog.e(e); } return ""; } public static byte[] decode(@NonNull String data) { try { return decode(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return decode(data.getBytes()); } } public static byte[] decode(@NonNull byte[] data) { return Base64.decode(data, Base64.DEFAULT); } public static String decodeToString(@NonNull String data) { try { return decodeToString(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return decodeToString(data.getBytes()); } } public static String decodeToString(@NonNull byte[] data) { try { return new String(Base64.decode(data, Base64.DEFAULT), "US-ASCII"); } catch (Exception e) { if(DEBUG) FLog.e(e); } return ""; } }
apache-2.0
cogfor/mcf-cogfor
framework/pull-agent/src/test/java/org/apache/manifoldcf/crawler/tests/ConnectionChangeTester.java
4071
/* $Id$ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.crawler.tests; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.crawler.system.ManifoldCF; import java.io.*; import java.util.*; /** This is a test whether we deal with changes to configuration properly */ public class ConnectionChangeTester { protected final ManifoldCFInstance instance; public ConnectionChangeTester(ManifoldCFInstance instance) { this.instance = instance; } public void executeTest() throws Exception { instance.start(); // Hey, we were able to install the file system connector etc. // Now, create a local test job and run it. IThreadContext tc = ThreadContextFactory.make(); // Create a basic file system connection, and save it. IRepositoryConnectionManager mgr = RepositoryConnectionManagerFactory.make(tc); IRepositoryConnection conn = mgr.create(); conn.setName("ConnectionChangeTest Connection"); conn.setDescription("ConnectionChangeTest Connection"); conn.setClassName("org.apache.manifoldcf.crawler.tests.ConnectionChangeRepositoryConnector"); conn.setMaxConnections(100); // Now, save mgr.save(conn); // Create a basic null output connection, and save it. IOutputConnectionManager outputMgr = OutputConnectionManagerFactory.make(tc); IOutputConnection outputConn = outputMgr.create(); outputConn.setName("Null Connection"); outputConn.setDescription("Null Connection"); outputConn.setClassName("org.apache.manifoldcf.agents.tests.TestingOutputConnector"); outputConn.setMaxConnections(100); // Now, save outputMgr.save(outputConn); // Create a job. IJobManager jobManager = JobManagerFactory.make(tc); IJobDescription job = jobManager.createJob(); job.setDescription("Test Job"); job.setConnectionName("ConnectionChangeTest Connection"); job.addPipelineStage(-1,true,"Null Connection",""); //job.setOutputConnectionName("Null Connection"); job.setType(job.TYPE_SPECIFIED); job.setStartMethod(job.START_DISABLE); job.setHopcountMode(job.HOPCOUNT_ACCURATE); // Save the job. jobManager.save(job); // Now, start the job, and wait until it is running. jobManager.manualStart(job.getID()); instance.waitJobRunningNative(jobManager,job.getID(),30000L); // Now, update the connection to allow the job to finish. conn = mgr.load("ConnectionChangeTest Connection"); ConfigParams cp = conn.getConfigParams(); cp.setParameter("proceed","true"); mgr.save(conn); // Wait for the job to become inactive. The time should not exceed 10 seconds for the actual crawl. instance.waitJobInactiveNative(jobManager,job.getID(),30000L); // The document will be skipped in the end. if (jobManager.getStatus(job.getID()).getDocumentsProcessed() != 10) throw new Exception("Expected 10 documents, saw "+jobManager.getStatus(job.getID()).getDocumentsProcessed()); // Now, delete the job. jobManager.deleteJob(job.getID()); instance.waitJobDeletedNative(jobManager,job.getID(),30000L); // Shut down instance2 instance.stop(); } }
apache-2.0
lessthanoptimal/BoofCV
main/boofcv-ip/src/benchmark/java/boofcv/alg/filter/convolve/BenchmarkConvolveImageStandard_SB.java
5348
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.filter.convolve; import boofcv.alg.filter.convolve.noborder.ConvolveImageStandard_SB; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.util.concurrent.TimeUnit; @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Warmup(iterations = 2) @Measurement(iterations = 5) @State(Scope.Benchmark) @Fork(value = 1) @SuppressWarnings({"UnusedDeclaration"}) public class BenchmarkConvolveImageStandard_SB extends CommonBenchmarkConvolve_SB { // @Param({"1", "10"}) @Param({"5"}) private int radius; @Setup public void setup() { setup(radius); } // @formatter:off @Benchmark public void horizontal_F32() {ConvolveImageStandard_SB.horizontal(kernelF32, input_F32, out_F32);} @Benchmark public void horizontal_U8_I8_DIV() {ConvolveImageStandard_SB.horizontal(kernelI32, input_U8, out_U8, 10);} @Benchmark public void horizontal_U8_I16() {ConvolveImageStandard_SB.horizontal(kernelI32, input_U8, out_S16);} @Benchmark public void horizontal_U8_I32() {ConvolveImageStandard_SB.horizontal(kernelI32, input_U8, out_S32);} @Benchmark public void horizontal_U16_I16() {ConvolveImageStandard_SB.horizontal(kernelI32, input_U16, out_S16);} @Benchmark public void horizontal_U16_I16_DIV() {ConvolveImageStandard_SB.horizontal(kernelI32, input_U16, out_S16, 10);} @Benchmark public void horizontal_S16_I16() {ConvolveImageStandard_SB.horizontal(kernelI32, input_S16, out_S16);} @Benchmark public void horizontal_S16_I16_DIV() {ConvolveImageStandard_SB.horizontal(kernelI32, input_S16, out_S16, 10);} @Benchmark public void horizontal_S32_I32() {ConvolveImageStandard_SB.horizontal(kernelI32, input_S32, out_S32);} @Benchmark public void horizontal_S32_I32_DIV() {ConvolveImageStandard_SB.horizontal(kernelI32, input_S32, out_S32, 10);} @Benchmark public void vertical_F32() {ConvolveImageStandard_SB.vertical(kernelF32, input_F32, out_F32);} @Benchmark public void vertical_U8_I8_DIV() {ConvolveImageStandard_SB.vertical(kernelI32, input_U8, out_U8, 10, work_I32);} @Benchmark public void vertical_U8_I16() {ConvolveImageStandard_SB.vertical(kernelI32, input_U8, out_S16);} @Benchmark public void vertical_U8_I32() {ConvolveImageStandard_SB.vertical(kernelI32, input_U8, out_S32);} @Benchmark public void vertical_U16_I16() {ConvolveImageStandard_SB.vertical(kernelI32, input_U16, out_S16);} @Benchmark public void vertical_U16_I32_DIV() {ConvolveImageStandard_SB.vertical(kernelI32, input_U16, out_S16, 10, work_I32);} @Benchmark public void vertical_S16_I16() {ConvolveImageStandard_SB.vertical(kernelI32, input_S16, out_S16);} @Benchmark public void vertical_S16_I16_DIV() {ConvolveImageStandard_SB.vertical(kernelI32, input_S16, out_S16, 10, work_I32);} @Benchmark public void vertical_S32_I16_DIV() {ConvolveImageStandard_SB.vertical(kernelI32, input_S32, out_S16, 10, work_I32);} @Benchmark public void vertical_S32_S32() {ConvolveImageStandard_SB.vertical(kernelI32, input_S32, out_S32);} @Benchmark public void vertical_S32_S32_DIV() {ConvolveImageStandard_SB.vertical(kernelI32, input_S32, out_S32, 10, work_I32);} @Benchmark public void convolve2D_F32() {ConvolveImageStandard_SB.convolve(kernel2D_F32, input_F32, out_F32);} @Benchmark public void convolve2D_U8_I16() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_U8, out_S16);} @Benchmark public void convolve2D_U8_I32() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_U8, out_S32);} @Benchmark public void convolve2D_U8_I8_DIV() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_U8, out_U8, 10, work_I32);} @Benchmark public void convolve2D_U16_I16() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_U16, out_S16);} @Benchmark public void convolve2D_U16_I16_DIV() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_U16, out_S16, 10, work_I32);} @Benchmark public void convolve2D_S16_I16() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_S16, out_S16);} @Benchmark public void convolve2D_S16_I16_DIV() {ConvolveImageStandard_SB.convolve(kernel2D_I32, input_S16, out_S16, 10, work_I32);} // @formatter:on public static void main( String[] args ) throws RunnerException { Options opt = new OptionsBuilder() .include(BenchmarkConvolveImageStandard_SB.class.getSimpleName()) .exclude(BenchmarkConvolveImageStandard_SB_MT.class.getSimpleName()) .warmupTime(TimeValue.seconds(1)) .measurementTime(TimeValue.seconds(1)) .build(); new Runner(opt).run(); } }
apache-2.0
jmckaskill/subversion
subversion/bindings/javahl/src/org/apache/subversion/javahl/SVNClient.java
21182
/** * @copyright * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * @endcopyright */ package org.apache.subversion.javahl; import org.apache.subversion.javahl.callback.*; import org.apache.subversion.javahl.types.*; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.ByteArrayOutputStream; import java.util.Collection; import java.util.Set; import java.util.List; import java.util.Map; /** * This is the main client class. All Subversion client APIs are * implemented in this class. This class is not threadsafe; if you * need threadsafe access, use ClientSynchronized. */ public class SVNClient implements ISVNClient { /** * Load the required native library. */ static { NativeResources.loadNativeLibrary(); } /** * Standard empty contructor, builds just the native peer. */ public SVNClient() { cppAddr = ctNative(); // Ensure that Subversion's config file area and templates exist. try { setConfigDirectory(null); } catch (ClientException suppressed) { // Not an exception-worthy problem, continue on. } } private long getCppAddr() { return cppAddr; } /** * Build the native peer * @return the adress of the peer */ private native long ctNative(); /** * release the native peer (should not depend on finalize) */ public native void dispose(); /** * release the native peer (should use dispose instead) */ public native void finalize(); /** * slot for the adress of the native peer. The JNI code is the only user * of this member */ protected long cppAddr; private ClientContext clientContext = new ClientContext(); public Version getVersion() { return NativeResources.getVersion(); } public native String getAdminDirectoryName(); public native boolean isAdminDirectory(String name); /** * @deprecated */ public native String getLastPath(); public native void status(String path, Depth depth, boolean onServer, boolean getAll, boolean noIgnore, boolean ignoreExternals, Collection<String> changelists, StatusCallback callback) throws ClientException; public native void list(String url, Revision revision, Revision pegRevision, Depth depth, int direntFields, boolean fetchLocks, ListCallback callback) throws ClientException; public native void username(String username); public native void password(String password); public native void setPrompt(UserPasswordCallback prompt); public native void logMessages(String path, Revision pegRevision, List<RevisionRange> revisionRanges, boolean stopOnCopy, boolean discoverPath, boolean includeMergedRevisions, Set<String> revProps, long limit, LogMessageCallback callback) throws ClientException; public native long checkout(String moduleName, String destPath, Revision revision, Revision pegRevision, Depth depth, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException; public void notification2(ClientNotifyCallback notify) { clientContext.notify = notify; } public void setConflictResolver(ConflictResolverCallback listener) { clientContext.resolver = listener; } public void setProgressCallback(ProgressCallback listener) { clientContext.listener = listener; } public native void remove(Set<String> paths, boolean force, boolean keepLocal, Map<String, String> revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException; public native void revert(String path, Depth depth, Collection<String> changelists) throws ClientException; public native void add(String path, Depth depth, boolean force, boolean noIgnores, boolean addParents) throws ClientException; public native long[] update(Set<String> paths, Revision revision, Depth depth, boolean depthIsSticky, boolean makeParents, boolean ignoreExternals, boolean allowUnverObstructions) throws ClientException; public native void commit(Set<String> paths, Depth depth, boolean noUnlock, boolean keepChangelist, Collection<String> changelists, Map<String, String> revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException; public native void copy(List<CopySource> sources, String destPath, boolean copyAsChild, boolean makeParents, boolean ignoreExternals, Map<String, String> revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException; public native void move(Set<String> srcPaths, String destPath, boolean force, boolean moveAsChild, boolean makeParents, Map<String, String> revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException; public native void mkdir(Set<String> paths, boolean makeParents, Map<String, String> revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException; public native void cleanup(String path) throws ClientException; public native void resolve(String path, Depth depth, ConflictResult.Choice conflictResult) throws SubversionException; public native long doExport(String srcPath, String destPath, Revision revision, Revision pegRevision, boolean force, boolean ignoreExternals, Depth depth, String nativeEOL) throws ClientException; public native long doSwitch(String path, String url, Revision revision, Revision pegRevision, Depth depth, boolean depthIsSticky, boolean ignoreExternals, boolean allowUnverObstructions, boolean ignoreAncestry) throws ClientException; public native void doImport(String path, String url, Depth depth, boolean noIgnore, boolean ignoreUnknownNodeTypes, Map<String, String> revpropTable, CommitMessageCallback handler, CommitCallback callback) throws ClientException; public native Set<String> suggestMergeSources(String path, Revision pegRevision) throws SubversionException; public native void merge(String path1, Revision revision1, String path2, Revision revision2, String localPath, boolean force, Depth depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException; public native void merge(String path, Revision pegRevision, List<RevisionRange> revisions, String localPath, boolean force, Depth depth, boolean ignoreAncestry, boolean dryRun, boolean recordOnly) throws ClientException; public native void mergeReintegrate(String path, Revision pegRevision, String localPath, boolean dryRun) throws ClientException; public native Mergeinfo getMergeinfo(String path, Revision pegRevision) throws SubversionException; public native void getMergeinfoLog(Mergeinfo.LogKind kind, String pathOrUrl, Revision pegRevision, String mergeSourceUrl, Revision srcPegRevision, boolean discoverChangedPaths, Depth depth, Set<String> revProps, LogMessageCallback callback) throws ClientException; public void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, String outFileName, Depth depth, Collection<String> changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { try { OutputStream stream = new FileOutputStream(outFileName); diff(target1, revision1, target2, revision2, relativeToDir, stream, depth, changelists, ignoreAncestry, noDiffDeleted, force, copiesAsAdds, false, false); } catch (FileNotFoundException ex) { throw ClientException.fromException(ex); } } public native void diff(String target1, Revision revision1, String target2, Revision revision2, String relativeToDir, OutputStream stream, Depth depth, Collection<String> changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds, boolean ignoreProps, boolean propsOnly) throws ClientException; public void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, String outFileName, Depth depth, Collection<String> changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds) throws ClientException { try { OutputStream stream = new FileOutputStream(outFileName); diff(target, pegRevision, startRevision, endRevision, relativeToDir, stream, depth, changelists, ignoreAncestry, noDiffDeleted, force, copiesAsAdds, false, false); } catch (FileNotFoundException ex) { throw ClientException.fromException(ex); } } public native void diff(String target, Revision pegRevision, Revision startRevision, Revision endRevision, String relativeToDir, OutputStream stream, Depth depth, Collection<String> changelists, boolean ignoreAncestry, boolean noDiffDeleted, boolean force, boolean copiesAsAdds, boolean ignoreProps, boolean propsOnly) throws ClientException; public native void diffSummarize(String target1, Revision revision1, String target2, Revision revision2, Depth depth, Collection<String> changelists, boolean ignoreAncestry, DiffSummaryCallback receiver) throws ClientException; public native void diffSummarize(String target, Revision pegRevision, Revision startRevision, Revision endRevision, Depth depth, Collection<String> changelists, boolean ignoreAncestry, DiffSummaryCallback receiver) throws ClientException; public native void properties(String path, Revision revision, Revision pegRevision, Depth depth, Collection<String> changelists, ProplistCallback callback) throws ClientException; public native void propertySetLocal(Set<String> paths, String name, byte[] value, Depth depth, Collection<String> changelists, boolean force) throws ClientException; public native void propertySetRemote(String path, long baseRev, String name, byte[] value, CommitMessageCallback handler, boolean force, Map<String, String> revpropTable, CommitCallback callback) throws ClientException; public native byte[] revProperty(String path, String name, Revision rev) throws ClientException; public native Map<String, byte[]> revProperties(String path, Revision rev) throws ClientException; public native void setRevProperty(String path, String name, Revision rev, String value, String originalValue, boolean force) throws ClientException; public native byte[] propertyGet(String path, String name, Revision revision, Revision pegRevision) throws ClientException; public byte[] fileContent(String path, Revision revision, Revision pegRevision) throws ClientException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); streamFileContent(path, revision, pegRevision, stream); return stream.toByteArray(); } public native void streamFileContent(String path, Revision revision, Revision pegRevision, OutputStream stream) throws ClientException; public native void relocate(String from, String to, String path, boolean ignoreExternals) throws ClientException; public native void blame(String path, Revision pegRevision, Revision revisionStart, Revision revisionEnd, boolean ignoreMimeType, boolean includeMergedRevisions, BlameCallback callback) throws ClientException; public native void setConfigDirectory(String configDir) throws ClientException; public native String getConfigDirectory() throws ClientException; public native void cancelOperation() throws ClientException; public native void addToChangelist(Set<String> paths, String changelist, Depth depth, Collection<String> changelists) throws ClientException; public native void removeFromChangelists(Set<String> paths, Depth depth, Collection<String> changelists) throws ClientException; public native void getChangelists(String rootPath, Collection<String> changelists, Depth depth, ChangelistCallback callback) throws ClientException; public native String getVersionInfo(String path, String trailUrl, boolean lastChanged) throws ClientException; public native void upgrade(String path) throws ClientException; /** * Enable logging in the JNI-code * @param logLevel the level of information to log (See * ClientLogLevel) * @param logFilePath path of the log file */ public static native void enableLogging(ClientLogLevel logLevel, String logFilePath); /** * enum for the constants of the logging levels. */ public enum ClientLogLevel { /** Log nothing */ NoLog, /** Log fatal error */ ErrorLog, /** Log exceptions thrown */ ExceptionLog, /** Log the entry and exits of the JNI code */ EntryLog; } /** * Returns version information of subversion and the javahl binding * @return version information */ public static native String version(); /** * Returns the major version of the javahl binding. Same version of the * javahl support the same interfaces * @return major version number */ public static native int versionMajor(); /** * Returns the minor version of the javahl binding. Same version of the * javahl support the same interfaces * @return minor version number */ public static native int versionMinor(); /** * Returns the micro (patch) version of the javahl binding. Same version of * the javahl support the same interfaces * @return micro version number */ public static native int versionMicro(); public native void lock(Set<String> paths, String comment, boolean force) throws ClientException; public native void unlock(Set<String> paths, boolean force) throws ClientException; public native void info2(String pathOrUrl, Revision revision, Revision pegRevision, Depth depth, Collection<String> changelists, InfoCallback callback) throws ClientException; public native void patch(String patchPath, String targetPath, boolean dryRun, int stripCount, boolean reverse, boolean ignoreWhitespace, boolean removeTempfiles, PatchCallback callback) throws ClientException; /** * A private class to hold the contextual information required to * persist in this object, such as notification handlers. */ private class ClientContext implements ClientNotifyCallback, ProgressCallback, ConflictResolverCallback { public ClientNotifyCallback notify = null; public ProgressCallback listener = null; public ConflictResolverCallback resolver = null; public void onNotify(ClientNotifyInformation notifyInfo) { if (notify != null) notify.onNotify(notifyInfo); } public void onProgress(ProgressEvent event) { if (listener != null) listener.onProgress(event); } public ConflictResult resolve(ConflictDescriptor conflict) throws SubversionException { if (resolver != null) return resolver.resolve(conflict); else return new ConflictResult(ConflictResult.Choice.postpone, null); } } }
apache-2.0
xu0xyc/amusing-wheather
app/src/main/java/com/charlie/wheather/MainActivity.java
5920
package com.charlie.wheather; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import com.charlie.wheather.adapter.CityWeatherPagerAdapter; import com.charlie.wheather.common.Constants; import com.charlie.wheather.pojo.City; import com.charlie.wheather.pojo.WeatherEntity; import com.charlie.wheather.util.LogUtil; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements DrawerLayout.DrawerListener, AppBarLayout.OnOffsetChangedListener { private Toolbar toolbar; private DrawerLayout drawer_layout; private AppBarLayout appbar_layout; private TabLayout tab_layout; private ViewPager view_pager; private ActionBarDrawerToggle mToggle; private FragmentPagerAdapter mAdapter; private boolean isDrawerOpened; private int mAppBarVerticalOffset;//appbar滑动的距离 全展开为0,全折叠为getTotalScrollRange @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); appbar_layout = (AppBarLayout) findViewById(R.id.appbar_layout); toolbar = (Toolbar) findViewById(R.id.toolbar); drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout); tab_layout = (TabLayout) findViewById(R.id.tab_layout); view_pager = (ViewPager) findViewById(R.id.view_pager); List<WeatherEntity> weatherEntities = new ArrayList<>(); weatherEntities.add(new WeatherEntity("北京")); weatherEntities.add(new WeatherEntity("上海")); weatherEntities.add(new WeatherEntity("深圳")); weatherEntities.add(new WeatherEntity("广州")); weatherEntities.add(new WeatherEntity("郑州")); weatherEntities.add(new WeatherEntity("杭州")); weatherEntities.add(new WeatherEntity("乌鲁木齐")); weatherEntities.add(new WeatherEntity("吐鲁番")); mAdapter = new CityWeatherPagerAdapter(getSupportFragmentManager(), weatherEntities); view_pager.setAdapter(mAdapter); tab_layout.setupWithViewPager(view_pager); setSupportActionBar(toolbar); mToggle = new ActionBarDrawerToggle(this, drawer_layout, R.string.open_drawer, R.string.close_drawer); drawer_layout.addDrawerListener(mToggle); drawer_layout.addDrawerListener(this); appbar_layout.addOnOffsetChangedListener(this); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mToggle.syncState(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.item_setting: // Toast.makeText(MainActivity.this, "click settings!", Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(), SettingsActivity.class)); overridePendingTransition(R.anim.act_in_from_right, R.anim.act_out_from_right); return true; } return mToggle.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mToggle.onConfigurationChanged(newConfig); } @Override protected void onDestroy() { drawer_layout.removeDrawerListener(mToggle); drawer_layout.removeDrawerListener(this); appbar_layout.removeOnOffsetChangedListener(this); super.onDestroy(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { } @Override public void onDrawerOpened(View drawerView) { isDrawerOpened = true; toolbar.setTitle(R.string.drawer_title); } @Override public void onDrawerClosed(View drawerView) { isDrawerOpened = false; toolbar.setTitle(R.string.app_name); } @Override public void onDrawerStateChanged(int newState) { appbar_layout.setExpanded(false, true); } @Override public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { LogUtil.d(Constants.LOG_TAG, "verticalOffset of appbar :"+verticalOffset); mAppBarVerticalOffset = -verticalOffset; } @Override public boolean dispatchTouchEvent(MotionEvent ev) { LogUtil.d(Constants.LOG_TAG, "Touch event action of MainActivity :"+ev.getAction()); if(!isDrawerOpened && MotionEvent.ACTION_UP == ev.getAction()){ int totalScrollRange = appbar_layout.getTotalScrollRange(); boolean needExpanded = mAppBarVerticalOffset>totalScrollRange/2 ? false : true; appbar_layout.setExpanded(needExpanded, true); } return super.dispatchTouchEvent(ev); } /** * 根据添加的城市,关闭drawer * @param city */ public void closeDrawer(City city) { drawer_layout.closeDrawer(GravityCompat.START); } }
apache-2.0
sanidhya09/androidprojectbase
baselibrary/src/main/java/xicom/com/baselibrary/retrofit2/RetroFitSingleton.java
7876
package xicom.com.baselibrary.retrofit2; import android.content.Context; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by sanidhya on 20/7/16. */ public enum RetroFitSingleton { INSTANCE; private Retrofit retrofit; private RetrofitConfigModel retrofitConfigModel; public static final String TAG = RetroFitSingleton.class.getName(); /** * Description : Mandatory Configuration Settings for Retrofit to work * * @param retrofitConfigModel : set important configuration here like base url, timeouts, etc * <p> * Sample implementation : * <p> * Headers.Builder builder = new Headers.Builder(); * builder.add("OS", "ANDROID"); * <p> * RetrofitConfigModel retrofitConfigModel = new RetrofitConfigModel.Builder() * .setBaseUrl("https://pubs.usgs.gov/") * .setConnectOutTime(60) * .setReadOutTime(45) * .setLoggingEnabled(true) * .setHeaders(builder) * .build(); */ public void setRetrofitConfig(RetrofitConfigModel retrofitConfigModel) { this.retrofitConfigModel = retrofitConfigModel; } public Retrofit getRetrofit() { return (retrofit == null) ? setRetrofit() : retrofit; } public Retrofit setRetrofit() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.NONE); if (retrofitConfigModel.loggingEnabled) interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); Interceptor interceptorHeader = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request.Builder requestBuilder = original.newBuilder() .headers(retrofitConfigModel.headers.build()) .method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }; OkHttpClient client = new OkHttpClient.Builder() .readTimeout(retrofitConfigModel.readOutTime, TimeUnit.SECONDS) .connectTimeout(retrofitConfigModel.connectOutTime, TimeUnit.SECONDS) .addInterceptor(interceptor) .addInterceptor(interceptorHeader) .build(); retrofit = new Retrofit.Builder() .baseUrl(retrofitConfigModel.baseUrl) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit; } /** * Description : Downloads the large file to External Storage * * @param url : Full url of file to download * @param fileName : Full url of file to download * @param fileExtension : File Extension to be saved. Eg : PDF, JPG, etc */ public void downloadLargeFile(final String url, final String fileName, final String fileExtension, final Context context) { final FileDownloadService downloadService = getRetrofit().create(FileDownloadService.class); new AsyncTask<Void, Long, Void>() { @Override protected Void doInBackground(Void... voids) { Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlAsync(url); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { if (response.isSuccessful()) { Log.d(TAG, "server contacted and has file"); boolean writtenToDisk = writeResponseBodyToDisk(response.body(), fileName, fileExtension); Log.d(TAG, "file download was a success? " + writtenToDisk); } else { Log.d(TAG, "server contact failed"); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.d(TAG, "Failed :: " + t.getLocalizedMessage()); } }); return null; } }.execute(); } private boolean writeResponseBodyToDisk(ResponseBody body, String fileName, String fileExtension) { try { // todo change the file location/name according to your needs File file = new File(Environment.getExternalStorageDirectory() + File.separator + fileName + "." + fileExtension); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] fileReader = new byte[4096]; long fileSize = body.contentLength(); long fileSizeDownloaded = 0; inputStream = body.byteStream(); outputStream = new FileOutputStream(file); while (true) { int read = inputStream.read(fileReader); if (read == -1) { break; } outputStream.write(fileReader, 0, read); fileSizeDownloaded += read; Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize); } outputStream.flush(); return true; } catch (IOException e) { return false; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return false; } } public Map<String, RequestBody> uploadImagesRequestGenerator(ArrayList<File> filesArray, String fileExtension, String keyParam) { Map<String, RequestBody> files = new HashMap<>(); for (int i = 0; i < filesArray.size(); i++) { String key = keyParam + "[" + String.valueOf(i) + "]"; files.put("" + key + "\"; filename=\"" + key + "." + fileExtension, getRequestFile(filesArray.get(i))); } return files; } public RequestBody getRequestFile(File file) { if (file != null) { return RequestBody.create(MediaType.parse("image/jpg"), file); } else { return null; } } public RequestBody getRequestString(String text) { if (text == null) { text = ""; } return RequestBody.create( MediaType.parse("text/plain"), text); } }
apache-2.0
aparod/jonix
jonix-onix3/src/main/java/com/tectonica/jonix/onix3/CollectionSequenceType.java
1799
/* * Copyright (C) 2012 Zach Melamed * * Latest version available online at https://github.com/zach-m/jonix * Contact me at zach@tectonica.co.il * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tectonica.jonix.onix3; import java.io.Serializable; import com.tectonica.jonix.JPU; import com.tectonica.jonix.OnixElement; import com.tectonica.jonix.codelist.CollectionSequenceTypes; import com.tectonica.jonix.codelist.RecordSourceTypes; /* * NOTE: THIS IS AN AUTO-GENERATED FILE, DON'T EDIT MANUALLY */ @SuppressWarnings("serial") public class CollectionSequenceType implements OnixElement, Serializable { public static final String refname = "CollectionSequenceType"; public static final String shortname = "x479"; /** * (type: dt.DateOrDateTime) */ public String datestamp; public RecordSourceTypes sourcetype; public String sourcename; public CollectionSequenceTypes value; public CollectionSequenceType() {} public CollectionSequenceType(org.w3c.dom.Element element) { datestamp = JPU.getAttribute(element, "datestamp"); sourcetype = RecordSourceTypes.byValue(JPU.getAttribute(element, "sourcetype")); sourcename = JPU.getAttribute(element, "sourcename"); value = CollectionSequenceTypes.byValue(JPU.getContentAsString(element)); } }
apache-2.0
microcks/microcks
webapp/src/main/java/io/github/microcks/util/ParameterConstraintUtil.java
2354
/* * Licensed to Laurent Broudoux (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.microcks.util; import io.github.microcks.domain.ParameterConstraint; import io.github.microcks.domain.ParameterLocation; import javax.servlet.http.HttpServletRequest; import java.util.regex.Pattern; /** * Utility class for holding various case around ParameterConstraints. * @author laurent */ public class ParameterConstraintUtil { /** * Validate that a parameter constraint it respected or violated. Return a message if violated. * @param request HttpServlet request holding parameters to validate * @param constraint Constraint to apply to one request parameter. * @return A string representing constraint violation if any. null otherwise. */ public static String validateConstraint(HttpServletRequest request, ParameterConstraint constraint) { String value = null; if (ParameterLocation.header == constraint.getIn()) { value = request.getHeader(constraint.getName()); } else if (ParameterLocation.query == constraint.getIn()) { value = request.getParameter(constraint.getName()); } if (value != null) { if (constraint.getMustMatchRegexp() != null) { if (!Pattern.matches(constraint.getMustMatchRegexp(), value)) { return "Parameter " + constraint.getName() + " should match " + constraint.getMustMatchRegexp(); } } } else { if (constraint.isRequired()) { return "Parameter " + constraint.getName() + " is required"; } } return null; } }
apache-2.0
fbotelho-university-code/poseidon
src/main/java/bonafide/datastore/KeyValueColumnDatastoreProxyTest.java
11832
/** * */ package bonafide.datastore; import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; /** * @author fabiim * */ public class KeyValueColumnDatastoreProxyTest { //TODO - laun smart, and maybe do it in verbose mode.... //XXX maybe set up tables for each method dynamically. public static KeyValueColumnDatastoreProxy ds; private byte[] key_1 = "1".getBytes(); private Map<String,byte[]> value_1 = Maps.newHashMap(ImmutableMap.of("1", "1".getBytes(), "2", "2".getBytes())); private byte[] key_2 = "2".getBytes(); private Map<String,byte[]> value_2 = Maps.newHashMap(ImmutableMap.of("4", "4".getBytes(), "3", "3".getBytes())); private byte[] key_3 = "3".getBytes(); private Map<String,byte[]> value_3 = Maps.newHashMap(ImmutableMap.of("5", "5".getBytes(), "6", "6".getBytes())); @BeforeClass public static void startup(){ ds = new ColumnProxy(0); System.out.println("here"); } @Before public void initTest(){ ds.clear(); } @Test public void testSetColumn(){ String tableName = "setColumn"; assertFalse(ds.setColumn(tableName, key_2, "whatever", new byte[1])); //table does not exits. ds.createTable(tableName); assertFalse(ds.setColumn(tableName, key_2, "whatever", new byte[1])); //key does not exist ds.put(tableName, key_1, value_1); assertFalse(ds.setColumn(tableName, key_2, "whatever", new byte[1])); //key (column) does not exist String k_to_change = value_1.keySet().iterator().next(); assertTrue(ds.setColumn(tableName, key_1, k_to_change, "weChangedThisValue".getBytes())); Map<String,byte[]> val = ds.getValue(tableName, key_1); assertTrue(Arrays.equals(val.get(k_to_change), "weChangedThisValue".getBytes())); } @Test public void testGetColumn(){ String tableName = "getColumn"; ds.createTable(tableName); Map<String,byte[]>map = Maps.newHashMap(ImmutableMap.of("1" ,"1".getBytes())); ds.put(tableName, key_1, map); assertTrue(Arrays.equals(ds.getColumn(tableName, key_1, "1" ),"1".getBytes())); ds.setColumn(tableName, key_1, "1","2".getBytes()); assertTrue(Arrays.equals(ds.getColumn(tableName, key_1, "1"),"2".getBytes())); } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#put(java.lang.String, byte[], byte[])}. */ @Test public void testPut() { String tableName = "put"; ds.createTable(tableName); Map<String,byte[]> val = ds.put(tableName,key_1, value_1); assertNull(val); // previous value was null. val = ds.put(tableName,key_1, value_2); //replace value, and get previous value. assertNotNull(val); //previous value is not null (should be value_1) assertMapAreEqual(val,value_1); assertMapAreEqual(ds.getValue(tableName, key_1), value_2); } private boolean areByteArrayValueMapEqual(Map<?, byte[]> a, Map<?, byte[]> b) { if (a.size() == b.size() ){ for (Entry<?, byte[]> en : a.entrySet()){ if (b.containsKey(en.getKey()) && Arrays.equals(en.getValue(), b.get(en.getKey()))){ continue; } return false; } return true; } return false; } private void assertMapAreEqual(final Map<?,byte[]> a , final Map<?,byte[]> b){ assertTrue(areByteArrayValueMapEqual(a,b)); } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#insert(java.lang.String, byte[], byte[])}. */ @Test public void testInsert() { String tableName = "insert"; assertFalse(ds.insert("nonExistent", key_1, value_1)); // can not insert in nonExistent table. ds.createTable(tableName); boolean inserted = ds.insert(tableName,key_1, value_1); assertTrue(inserted); assertMapAreEqual(ds.getValue(tableName, key_1), value_1); inserted = ds.insert(tableName,key_1, value_2); assertTrue(inserted); assertMapAreEqual(ds.getValue(tableName, key_1), value_2); //value has been replaced. } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#get(java.lang.String, byte[])}. */ @Test public void testGet() { String tableName = "get"; ds.createTable(tableName); Map<String,byte[]> val = ds.getValue(tableName, key_1); assertNull(val); // there is no key_1 yet. ds.put(tableName,key_1, value_1); val = ds.getValue(tableName, key_1); assertNull(ds.removeValue(tableName, key_2)); //entry does not exists. for (Entry<String, byte[]> m : val.entrySet()){ System.out.println(m.getKey() + "-" + Arrays.toString(m.getValue())); System.out.println( m.getKey() + "-" + Arrays.toString(value_1.get(m.getKey()))); } assertMapAreEqual(val, value_1); } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#remove(java.lang.String, byte[])}. */ @Test public void testRemoveStringByteArray() { String tableName = "removeStringByteArray"; ds.createTable(tableName); ds.put(tableName, key_1, value_1); Map<String,byte[]> val =ds.removeValue(tableName, key_1); assertNotNull(val); assertMapAreEqual(val, value_1); } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#replace(java.lang.String, byte[], byte[], byte[])}. */ @Test public void testReplace() { String tableName ="replace"; ds.createTable("replace"); assertFalse(ds.replace(tableName, key_1, value_1, value_2)); assertFalse(ds.replace(tableName, key_1, value_1, value_2)); assertFalse(ds.containsKey(tableName, key_1)); ds.put(tableName, key_1, value_1); assertTrue(ds.replace(tableName, key_1, value_1, value_2)); assertMapAreEqual(ds.getValue(tableName, key_1), value_2); assertTrue(ds.replace(tableName, key_1, value_2, value_1)); assertMapAreEqual(ds.getValue(tableName, key_1), value_1); } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#remove(java.lang.String, byte[], byte[])}. */ @Test public void testRemoveStringByteArrayByteArray() { String tableName = "atomicRemove"; ds.createTable(tableName); assertFalse(ds.remove(tableName,key_1, value_1)); //should not remove, key_1 is not mapped to nothing assertFalse(ds.remove(tableName,key_1, value_1));// still.. does not remove. assertFalse(ds.containsKey(tableName,key_1)); //should not contain ds.put(tableName,key_1, value_1); assertTrue(ds.remove(tableName,key_1, value_1)); assertFalse(ds.containsKey(tableName,key_1)); } /** * Test method for {@link bonafide.datastore.KeyValueDatastoreProxy#putIfAbsent(java.lang.String, byte[], byte[])}. */ @Test public void testPutIfAbsent() { String tableName = "putIfAbset"; ds.createTable(tableName); assertNull(ds.putIfAbsent(tableName, key_1, value_1)); assertTrue(ds.containsKey(tableName, key_1)); assertMapAreEqual(ds.getValue(tableName, key_1), value_1); assertMapAreEqual(ds.putIfAbsent(tableName, key_1, value_2), value_1); assertMapAreEqual(ds.putIfAbsent(tableName, key_1, value_2), value_1); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#clear()}. */ @Test public void testClear() { ds.clear(); assertFalse(ds.containsTable("ola")); ds.createTable("ola"); ds.put("ola", key_1, value_1); ds.clear(); assertFalse(ds.containsKey("ola", new byte[10])); ///XXX you can do better } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#createTable(java.lang.String)}. */ @Test public void testCreateTableString() { assertTrue(ds.createTable("createTable")); assertFalse(ds.createTable("createTable")); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#createTable(java.lang.String, long)}. */ @Test public void testCreateTableStringLong() { String tableName="table_created"; assertTrue(ds.createTable(tableName,2)); assertFalse(ds.createTable(tableName,2)); //table already existed. Should not allow creation. ds.put(tableName, key_1, value_1); ds.put(tableName, key_2, value_2); assertTrue(ds.containsKey(tableName,key_1)); assertTrue(ds.containsKey(tableName,key_2)); ds.put(tableName,key_3, value_3); //Removes the eldest element a since max size is 2. assertFalse(ds.containsKey(tableName, key_1)); assertTrue(ds.containsKey(tableName, key_2)); assertTrue(ds.containsKey(tableName, "c".getBytes())); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#removeTable(java.lang.String)}. */ @Test public void testRemoveTable() { assertFalse(ds.removeTable("this_table_does_not_exists")); assertTrue(ds.createTable("table_to_remove")); assertTrue(ds.removeTable("table_to_remove")); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#containsTable(java.lang.String)}. */ @Test public void testContainsTable() { assertTrue(ds.createTable("test_contains")); assertFalse(ds.containsTable("this_table_does_not_exists")); assertTrue(ds.containsTable("test_contains")); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#clear(java.lang.String)}. */ @Test public void testClearString() { String tableName = "test_clear"; assertTrue(ds.createTable(tableName)); assertTrue(ds.insert(tableName,key_1,value_1)); Assert.assertEquals(ds.size(tableName), 1); ds.clear(tableName); Assert.assertEquals((int) ds.size(tableName), 0); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#isEmpty(java.lang.String)}. */ @Test public void testIsEmpty() { String tableName= "testIsEmptyString"; ds.createTable(tableName); assertTrue(ds.isEmpty(tableName)); ds.put(tableName,key_1, value_1); assertFalse(ds.isEmpty(tableName)); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#size(java.lang.String)}. */ @Test public void testSize() { ds.createTable("size"); assertEquals(ds.size("size"), 0); ds.put("size",key_1, value_1); assertEquals(ds.size("size"), 1); ds.put("size", key_2, value_1); assertEquals(ds.size("size"), 2); ds.removeValue("size", key_2); assertEquals(ds.size("size"), 1); ds.clear("size"); assertEquals(ds.size("size"), 0); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#containsKey(java.lang.String, byte[])}. */ @Test public void testContainsKey() { String tableName = "testContainsKey"; ds.createTable(tableName); assertFalse(ds.containsKey(tableName, key_1)); ds.put(tableName,key_1, value_1); assertTrue(ds.containsKey(tableName, key_1)); } /** * Test method for {@link bonafide.datastore.TableDataStoreProxy#getAndIncrement(java.lang.String, java.lang.String)}. */ @Test public void testGetAndIncrement() { String tableName = "getAndIncrement"; ds.createTable(tableName); int i = ds.getAndIncrement(tableName, "1"); assertEquals(i,0); i = ds.getAndIncrement(tableName, "1"); assertEquals(i,1); //ds.put(tableName, "1".getBytes(), value_1); //FIXME: document this behaviour - put override column name... //assertMapAreEqual(ds.getValue(tableName, "1".getBytes()), value_1); } @Test public void testValues(){ String tableName = "values"; ds.createTable(tableName); ds.put(tableName, key_1, value_1); ds.put(tableName, key_2, value_2); ds.put(tableName, key_3, value_3); Collection<Map<String,byte[]>> maps = ds.valueS(tableName); assertSame(maps.size(), 3); boolean c1=false,c2=false,c3=false; for (Map<String,byte[]> m : maps){ if (areByteArrayValueMapEqual(m, value_1)){ c1 = true; } else if (areByteArrayValueMapEqual(m, value_2)){ c2 = true; } else if (areByteArrayValueMapEqual(m, value_3)){ c3 = true; } } if (!(c1 && c2&& c3)){ fail("Not in map"); } } }
apache-2.0
johnzeringue/ET_Redux
src/main/java/org/earthtime/ratioDataModels/AbstractRatiosDataModel.java
39990
/* * AbstractRatiosDataModel.java * * * Copyright 2006-2015 James F. Bowring and www.Earth-Time.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.earthtime.ratioDataModels; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.ConversionException; import com.thoughtworks.xstream.io.xml.DomDriver; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.math.BigDecimal; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.cirdles.commons.util.ResourceExtractor; import org.earthtime.UPb_Redux.ReduxConstants; import org.earthtime.UPb_Redux.user.UPbReduxConfigurator; import org.earthtime.UPb_Redux.valueModels.ValueModel; import org.earthtime.XMLExceptions.BadOrMissingXMLSchemaException; import org.earthtime.archivingTools.URIHelper; import org.earthtime.exceptions.ETException; import org.earthtime.exceptions.ETWarningDialog; import org.earthtime.matrices.matrixModels.AbstractMatrixModel; import org.earthtime.matrices.matrixModels.CorrelationMatrixModel; import org.earthtime.matrices.matrixModels.CovarianceMatrixModel; import org.earthtime.reduxLabData.ReduxLabDataListElementI; import org.earthtime.utilities.DateHelpers; import org.earthtime.xmlUtilities.XMLSerializationI; /** * * @author James F. Bowring */ public abstract class AbstractRatiosDataModel implements Comparable<AbstractRatiosDataModel>, Serializable, XMLSerializationI, ReduxLabDataListElementI { private static final long serialVersionUID = -3311656789053878314L; /** * */ protected transient String XMLSchemaURL; /** * */ protected transient AbstractMatrixModel dataCovariancesVarUnct; /** * */ protected transient AbstractMatrixModel dataCorrelationsVarUnct; /** * */ protected transient AbstractMatrixModel dataCovariancesSysUnct; /** * */ protected transient AbstractMatrixModel dataCorrelationsSysUnct; // Instance variables /** * */ protected String modelName; /** * */ protected int versionNumber; /** * */ protected int minorVersionNumber; /** * */ protected String labName; /** * */ protected String dateCertified; /** * */ protected String reference; /** * */ protected String comment; /** * */ protected ValueModel[] ratios; /** * */ protected Map<String, BigDecimal> rhos;//CAUTION DO NOT RENAME UNLESS PLANNING TO BREAK SCHEMA ETC /** * */ protected Map<String, BigDecimal> rhosSysUnct; /** * */ protected boolean immutable; /** * */ // Constructors /** * */ protected AbstractRatiosDataModel() { this.XMLSchemaURL = ""; this.modelName = ReduxConstants.DEFAULT_OBJECT_NAME; this.versionNumber = 1; this.minorVersionNumber = 0; this.labName = ReduxConstants.DEFAULT_OBJECT_NAME; this.dateCertified = DateHelpers.defaultEarthTimeDateString(); this.reference = "None"; this.comment = "None"; this.ratios = new ValueModel[0]; this.rhos = new HashMap<>(); this.rhosSysUnct = new HashMap<>(); this.dataCovariancesVarUnct = new CovarianceMatrixModel(); this.dataCorrelationsVarUnct = new CorrelationMatrixModel(); this.dataCovariancesSysUnct = new CovarianceMatrixModel(); this.dataCorrelationsSysUnct = new CorrelationMatrixModel(); this.immutable = false; } /** * * * @param modelName * @param versionNumber * @param minorVersionNumber the value of minorVersionNumber * @param labName the value of labName * @param dateCertified * @param reference the value of reference * @param comment the value of comment */ protected AbstractRatiosDataModel(// String modelName, int versionNumber, int minorVersionNumber, String labName, String dateCertified, String reference, String comment) { this(); this.modelName = modelName.trim(); this.versionNumber = versionNumber; this.minorVersionNumber = minorVersionNumber; this.labName = labName; this.dateCertified = dateCertified; this.reference = reference; this.comment = comment; } /** * * @param doAppendName the value of doAppendName * @return the org.earthtime.ratioDataModels.AbstractRatiosDataModel */ public AbstractRatiosDataModel copyModel(boolean doAppendName) { AbstractRatiosDataModel myModel = cloneModel(); myModel.setModelName(myModel.getModelName() + (doAppendName ? "-COPY" : "")); myModel.initializeModel(); return myModel; } /** * * @return */ public abstract AbstractRatiosDataModel cloneModel(); /** * compares this <code>AbstractRatiosDataModel</code> to argument * <code>AbstractRatiosDataModel</code> by their <code>name</code> and * <code>version</code>. * * @pre argument <code>AbstractRatiosDataModel</code> is a valid * <code>AbstractRatiosDataModel</code> * @post returns an <code>int</code> representing the comparison between * this <code>AbstractRatiosDataModel</code> and argument * <code>AbstractRatiosDataModel</code> * * @param model * @return <code>int</code> - 0 if this * <code>AbstractRatiosDataModel</code>'s <code>name</code> and * <code>version</code> is the same as argument * <code>AbstractRatiosDataModel</code>'s, -1 if they are lexicographically * less than argument <code>AbstractRatiosDataModel</code>'s, and 1 if they * are greater than argument <code>AbstractRatiosDataModel</code>'s * @throws java.lang.ClassCastException a ClassCastException */ @Override public int compareTo(AbstractRatiosDataModel model) throws ClassCastException { String modelID =// model.getNameAndVersion().trim(); return (this.getNameAndVersion().trim() // .compareToIgnoreCase(modelID)); } /** * This method supports the loading of XML parameter models into the lab * data from the resources folder corresponding to the model class. The * names of the files are listed line by line in the file * listOfModelFiles.txt. The rationale is that users can propose via a * github.com pull request that models be included in the distributed jar * file and can also see the models easily on github. This method also sets * the model to be immutable so that the user cannot accidentally delete it * from the lab data. * * @param modelInstances */ public static void loadModelsFromResources(Map<String, AbstractRatiosDataModel> modelInstances) { AbstractRatiosDataModel anInstance = modelInstances.entrySet().iterator().next().getValue(); ResourceExtractor RESOURCE_EXTRACTOR = new ResourceExtractor(anInstance.getClass()); File listOfModelFiles = RESOURCE_EXTRACTOR.extractResourceAsFile("listOfModelFiles.txt"); if (listOfModelFiles != null) { try { List<String> fileNames = Files.readLines(listOfModelFiles, Charsets.ISO_8859_1); // process models as xml files for (int i = 0; i < fileNames.size(); i++) { // test for empty string if (fileNames.get(i).trim().length() > 0) { File modelFile = RESOURCE_EXTRACTOR.extractResourceAsFile(fileNames.get(i)); System.out.println(anInstance.getClass().getSimpleName() + " added: " + fileNames.get(i)); try { AbstractRatiosDataModel model = anInstance.readXMLObject(modelFile.getCanonicalPath(), false); modelInstances.put(model.getNameAndVersion(), model); model.setImmutable(true); } catch (IOException | ETException | BadOrMissingXMLSchemaException ex) { if (ex instanceof ETException) { new ETWarningDialog((ETException) ex).setVisible(true); } } } } } catch (IOException iOException) { } } } /** * compares this <code>AbstractRatiosDataModel</code> to argument * <code>AbstractRatiosDataModel<?code> by their <code>name</code> and * <code>version</code>. * * @param model * @pre argument <code>AbstractRatiosDataModel</code> is a valid * <code>AbstractRatiosDataModel</code> * @post returns a <code>boolean</code> representing the equality of this * <code>AbstractRatiosDataModel</code> and argument * <code>AbstractRatiosDataModel</code> based on their <code>name</code> and * <code>version</code> * * @return <code>boolean</code> - <code>true</code> if argument <code> * AbstractRatiosDataModel</code> is this * <code>AbstractRatiosDataModel</code> or their <code>name</code> and * <code>version</code> are identical, else <code>false</code> */ @Override public boolean equals(Object model) { //check for self-comparison if (this == model) { return true; } if (!(model instanceof AbstractRatiosDataModel)) { return false; } AbstractRatiosDataModel myModel = (AbstractRatiosDataModel) model; return (this.getNameAndVersion().trim().compareToIgnoreCase( // myModel.getNameAndVersion().trim()) == 0); } /** * returns 0 as the hashcode for this <code>AbstractRatiosDataModel</code>. * Implemented to meet equivalency requirements as documented by * <code>java.lang.Object</code> * * @pre this <code>AbstractRatiosDataModel</code> exists * @post hashcode of 0 is returned for this * <code>AbstractRatiosDataModel</code> * * @return <code>int</code> - 0 */ // http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html?page=4 @Override public int hashCode() { return 0; } /** * */ public void initializeModel() { dataCovariancesVarUnct = new CovarianceMatrixModel(); dataCorrelationsVarUnct = new CorrelationMatrixModel(); dataCovariancesSysUnct = new CovarianceMatrixModel(); dataCorrelationsSysUnct = new CorrelationMatrixModel(); refreshModel(); } /** * */ public void refreshModel() { try { initializeBothDataCorrelationM(); generateBothUnctCovarianceMFromEachUnctCorrelationM(); } catch (Exception e) { // System.out.println(e.getMessage()); } } /** * * @param dataIncoming * @param myRhos * @param myRhosSysUnct the value of myRhosSysUnct */ public void initializeModel(ValueModel[] dataIncoming, Map<String, BigDecimal> myRhos, Map<String, BigDecimal> myRhosSysUnct) { // precondition: the data model has been created with a prescribed set of ratios with names // need to check each incoming ratio for validity for (int i = 0; i < dataIncoming.length; i++) { ValueModel ratio = getDatumByName(dataIncoming[i].getName()); if (ratio != null) { ratio.copyValuesFrom(dataIncoming[i]); } } // introduce special comparator that puts concentrations (conc) after dataIncoming)//dec 2014 not needed Arrays.sort(this.ratios, new DataValueModelNameComparator()); if (myRhos == null) { buildRhosMap(); } else { for (String key : myRhos.keySet()) { String rhoName = key; if (rhos.get(rhoName) != null) { rhos.put(rhoName, myRhos.get(rhoName)); } } } if (myRhosSysUnct == null) { buildRhosSysUnctMap(); } else { for (String key : myRhosSysUnct.keySet()) { String rhoName = key; if (rhosSysUnct.get(rhoName) != null) { rhosSysUnct.put(rhoName, myRhosSysUnct.get(rhoName)); } } } initializeModel(); } /** * @return the immutable */ public boolean isImmutable() { return immutable; } /** * @param immutable the immutable to set */ public void setImmutable(boolean immutable) { this.immutable = immutable; } /** * @return the minorVersionNumber */ public int getMinorVersionNumber() { return minorVersionNumber; } /** * @param minorVersionNumber the minorVersionNumber to set */ public void setMinorVersionNumber(int minorVersionNumber) { this.minorVersionNumber = minorVersionNumber; } /** * @return the dataCovariancesSysUnct */ public AbstractMatrixModel getDataCovariancesSysUnct() { return dataCovariancesSysUnct; } /** * @return the dataCorrelationsSysUnct */ public AbstractMatrixModel getDataCorrelationsSysUnct() { return dataCorrelationsSysUnct; } /** * */ protected class DataValueModelNameComparator implements Comparator<ValueModel> { /** * */ public DataValueModelNameComparator() { } @Override public int compare(ValueModel vm1, ValueModel vm2) { if (vm1.getName().substring(0, 1).equalsIgnoreCase(vm2.getName().substring(0, 1))) { return vm1.compareTo(vm2); } else { return vm2.compareTo(vm1); } } } /** * */ protected void buildRhosMap() { rhos = new HashMap<>(); for (int i = 0; i < ratios.length; i++) { for (int j = i + 1; j < ratios.length; j++) { String key = "rho" + ratios[i].getName().substring(0, 1).toUpperCase() + ratios[i].getName().substring(1) + "__" + ratios[j].getName(); rhos.put(key, BigDecimal.ZERO); } } } /** * */ protected void buildRhosSysUnctMap() { rhosSysUnct = new HashMap<>(); for (int i = 0; i < ratios.length; i++) { for (int j = i + 1; j < ratios.length; j++) { String key = "rho" + ratios[i].getName().substring(0, 1).toUpperCase() + ratios[i].getName().substring(1) + "__" + ratios[j].getName(); rhosSysUnct.put(key, BigDecimal.ZERO); } } } /** * * */ protected void initializeBothDataCorrelationM() { Map<Integer, String> dataNamesList = new HashMap<>(); // only build matrices for values with positive uncertainties int ratioCount = 0; for (ValueModel ratio : ratios) { if (ratio.hasPositiveVarUnct()) { dataNamesList.put(ratioCount, ratio.getName()); ratioCount++; } } dataCorrelationsVarUnct.setRows(dataNamesList); dataCorrelationsVarUnct.setCols(dataNamesList); dataCorrelationsVarUnct.initializeMatrix(); ((CorrelationMatrixModel) dataCorrelationsVarUnct).initializeCorrelations(rhos); // sept 2014 new sys unct dataNamesList = new HashMap<>(); ratioCount = 0; for (ValueModel ratio : ratios) { if (ratio.hasPositiveSysUnct()) { dataNamesList.put(ratioCount, ratio.getName()); ratioCount++; } } dataCorrelationsSysUnct.setRows(dataNamesList); dataCorrelationsSysUnct.setCols(dataNamesList); dataCorrelationsSysUnct.initializeMatrix(); ((CorrelationMatrixModel) dataCorrelationsSysUnct).initializeCorrelations(rhosSysUnct); } /** * */ protected void copyBothRhosFromEachCorrelationM() { // sept 2014 backwards compat if (rhos == null) { buildRhosMap(); } for (String rhoName : rhos.keySet()) { rhos.put(rhoName, new BigDecimal(((CorrelationMatrixModel) dataCorrelationsVarUnct).getCorrelationCell(rhoName))); } // sept 2014 backwards compat if (rhosSysUnct == null) { buildRhosSysUnctMap(); } for (String rhoName : rhosSysUnct.keySet()) { rhosSysUnct.put(rhoName, new BigDecimal(((CorrelationMatrixModel) dataCorrelationsSysUnct).getCorrelationCell(rhoName))); } } /** * * * @param checkCovarianceValidity the value of checkCovarianceValidity * @throws ETException */ public void saveEdits(boolean checkCovarianceValidity) throws ETException { if ((dataCorrelationsVarUnct != null) || (dataCorrelationsSysUnct != null)) { generateBothUnctCovarianceMFromEachUnctCorrelationM(); copyBothRhosFromEachCorrelationM(); if (checkCovarianceValidity && !dataCovariancesVarUnct.isCovMatrixSymmetricAndPositiveDefinite()) { throw new ETException(null, "Var Unct Correlations yield Var Unct covariance matrix NOT positive definite."); } if (checkCovarianceValidity && !dataCovariancesSysUnct.isCovMatrixSymmetricAndPositiveDefinite()) { throw new ETException(null, "Sys Unct Correlations yield Sys Unct covariance matrix NOT positive definite."); } } } /** * ************** * section for translating correlation to covariance and back Correlation * coefficient (x,y) = covariance(x,y) / (1-sigma for x * 1-sigma for y) * both matrices have the same ratio names in rows and columns in the same * order */ protected void generateBothUnctCorrelationMFromEachUnctCovarianceM() { Iterator<String> colNames; try { dataCorrelationsVarUnct.copyValuesFrom(dataCovariancesVarUnct); // divide each cell by (1-sigma for x * 1-sigma for y) colNames = dataCorrelationsVarUnct.getCols().keySet().iterator(); while (colNames.hasNext()) { String colName = colNames.next(); ValueModel colData = getDatumByName(colName); int col = dataCorrelationsVarUnct.getCols().get(colName); //calculate values for this column int rowColDimension = dataCorrelationsVarUnct.getMatrix().getColumnDimension(); for (int row = 0; row < rowColDimension; row++) { String rowName = dataCorrelationsVarUnct.getRows().get(row); ValueModel rowData = getDatumByName(rowName); double correlation = // dataCovariancesVarUnct.getMatrix().get(row, col)// / rowData.getOneSigmaAbs().doubleValue() // / colData.getOneSigmaAbs().doubleValue(); dataCorrelationsVarUnct.setValueAt(row, col, correlation); } } } catch (Exception e) { } try { dataCorrelationsSysUnct.copyValuesFrom(dataCovariancesSysUnct); // divide each cell by (1-sigma for x * 1-sigma for y) colNames = dataCorrelationsSysUnct.getCols().keySet().iterator(); while (colNames.hasNext()) { String colName = colNames.next(); ValueModel colData = getDatumByName(colName); int col = dataCorrelationsSysUnct.getCols().get(colName); //calculate values for this column int rowColDimension = dataCorrelationsSysUnct.getMatrix().getColumnDimension(); for (int row = 0; row < rowColDimension; row++) { String rowName = dataCorrelationsSysUnct.getRows().get(row); ValueModel rowData = getDatumByName(rowName); double correlation = // dataCovariancesSysUnct.getMatrix().get(row, col)// / rowData.getOneSigmaSysAbs().doubleValue() // / colData.getOneSigmaSysAbs().doubleValue(); dataCorrelationsSysUnct.setValueAt(row, col, correlation); } } } catch (Exception e) { } } /** * */ protected void generateBothUnctCovarianceMFromEachUnctCorrelationM() { Iterator<String> colNames; try { dataCovariancesVarUnct.copyValuesFrom(dataCorrelationsVarUnct); // divide each cell by (1-sigma for x * 1-sigma for y) colNames = dataCovariancesVarUnct.getCols().keySet().iterator(); while (colNames.hasNext()) { String colName = colNames.next(); ValueModel colData = getDatumByName(colName); int col = dataCovariancesVarUnct.getCols().get(colName); //calculate values for this column int rowColDimension = dataCovariancesVarUnct.getMatrix().getColumnDimension(); for (int row = 0; row < rowColDimension; row++) { String rowName = dataCovariancesVarUnct.getRows().get(row); ValueModel rowData = getDatumByName(rowName); double covariance = // dataCorrelationsVarUnct.getMatrix().get(row, col)// * rowData.getOneSigmaAbs().doubleValue() // * colData.getOneSigmaAbs().doubleValue(); dataCovariancesVarUnct.setValueAt(row, col, covariance); } } } catch (Exception e) { } try { dataCovariancesSysUnct.copyValuesFrom(dataCorrelationsSysUnct); // divide each cell by (1-sigma for x * 1-sigma for y) colNames = dataCovariancesSysUnct.getCols().keySet().iterator(); while (colNames.hasNext()) { String colName = colNames.next(); ValueModel colData = getDatumByName(colName); int col = dataCovariancesSysUnct.getCols().get(colName); //calculate values for this column int rowColDimension = dataCovariancesSysUnct.getMatrix().getColumnDimension(); for (int row = 0; row < rowColDimension; row++) { String rowName = dataCovariancesSysUnct.getRows().get(row); ValueModel rowData = getDatumByName(rowName); double covariance = // dataCorrelationsSysUnct.getMatrix().get(row, col)// * rowData.getOneSigmaSysAbs().doubleValue() // * colData.getOneSigmaSysAbs().doubleValue(); dataCovariancesSysUnct.setValueAt(row, col, covariance); } } } catch (Exception e) { } } /** * gets the <code>modelName</code> of this * <code>AbstractRatiosDataModel</code>. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns this <code>AbstractRatiosDataModel</code>'s * <code>modelName</code> * * @return <code>String</code> - this <code>AbstractRatiosDataModel</code>'s * <code>modelName</code> */ public String getModelName() { return modelName; } // // for backward compatibility // public String getName () { // return getModelName(); // } /** * gets the <code>versionNumber</code> of this * <code>AbstractRatiosDataModel</code>. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns this <code>AbstractRatiosDataModel</code>'s * <code>versionNumber</code> * * @return <code>int</code> - this <code>AbstractRatiosDataModel</code>'s * <code>versionNumber</code> */ public int getVersionNumber() { return versionNumber; } /** * gets the <code>labName</code> of this * <code>AbstractRatiosDataModel</code>. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns this <code>AbstractRatiosDataModel</code>'s * <code>labName</code> * * @return <code>String</code> - this <code>AbstractRatiosDataModel</code>'s * <code>labName</code> */ public String getLabName() { return labName; } /** * gets the <code>dateCertified</code> of this * <code>AbstractRatiosDataModel</code>. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns this <code>AbstractRatiosDataModel</code>'s * <code>dateCertified</code> * * @return <code>String</code> - this <code>AbstractRatiosDataModel</code>'s * <code>dateCertified</code> */ public String getDateCertified() { return dateCertified; } /** * gets a <code>String</code> containing this * <code>AbstractRatiosDataModel</code>'s <code>modelName</code> and * <code>versionNumber</code>. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns a <code>String</code> containing this * <code>AbstractRatiosDataModel</code>'s <code>modelName</code> and * <code>versionNumber</code> * * @return <code>String</code> - this <code>AbstractRatiosDataModel</code>'s * <code>modelName</code> and <code>versionNumber</code> */ public String getNameAndVersion() { return makeNameAndVersion(modelName, versionNumber, minorVersionNumber); } /** * * * @param name * @param version * @param minorVersionNumber the value of minorVersionNumber * @return */ protected static String makeNameAndVersion(String name, int version, int minorVersionNumber) { return name.trim()// + " v." + version + "." + minorVersionNumber; } /** * gets the <code>ratios</code> of this * <code>AbstractRatiosDataModel</code>. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns this <code>AbstractRatiosDataModel</code>'s * <code>ratios</code> * * @return <code>ValueModel[]</code> - collection of this * <code>AbstractRatiosDataModel</code>'s <code>ratios</code> */ public ValueModel[] getData() { return ratios; } /** * * @return */ public ValueModel[] cloneData() { ValueModel[] clonedData = new ValueModel[ratios.length]; for (int i = 0; i < ratios.length; i++) { clonedData[i] = ratios[i].copy(); } return clonedData; } /** * gets the <code>modelName</code> and <code>versionNumber</code> of this * <code>AbstractRatiosDataModel</code> via * {@link #getNameAndVersion getNameAndVersion}. * * @pre this <code>AbstractRatiosDataModel</code> exists * @post returns a <code>String</code> containing this * <code>AbstractRatiosDataModel</code>'s <code>modelName</code> and * <code>versionNumber</code> * * @return <code>String</code> - this <code>AbstractRatiosDataModel</code>'s <code> * modelName</code> and <code>versionNumber</code> */ @Override public String getReduxLabDataElementName() { return getNameAndVersion(); } /** * gets a single ratio from this <code>AbstractRatiosDataModel</code>'s * <code>ratios</code> specified by argument <code>datumName</code>. Returns * a new, empty <code> * ValueModel</code> if no matching ratio is found. * * @pre argument <code>datumName</code> is a valid <code>String</code> * @post returns the <code>ValueModel</code> found in this * <code>AbstractRatiosDataModel</code>'s <code>ratios</code> whose name * matches argument <code>datumName</code> * * @param datumName name of the ratio to search for * @return <code>ValueModel</code> - ratio found in <code>ratios</code> * whose name matches argument <code>datumName</code> or a new <code> * ValueModel</code> if no match is found */ public ValueModel getDatumByName(String datumName) { ValueModel retVal = new ValueModel(datumName); for (int i = 0; i < ratios.length; i++) { if (ratios[i].getName().equals(datumName)) { retVal = ratios[i]; } } return retVal; } /** * * @param updateOnly */ public abstract void initializeNewRatiosAndRhos(boolean updateOnly); /** * * @param name * @return */ public BigDecimal getRhoByName(String name) { return rhos.get(name); } /** * * @param coeffName * @return */ public ValueModel getRhoSysUnctByName(String coeffName) { BigDecimal myRhoValue = rhosSysUnct.get(coeffName); if (myRhoValue == null) { myRhoValue = BigDecimal.ZERO; } ValueModel coeffModel = new ValueModel(// // coeffName, myRhoValue, "NONE", BigDecimal.ZERO, BigDecimal.ZERO); return coeffModel; } /** * @return the dataCovariancesVarUnct */ public AbstractMatrixModel getDataCovariancesVarUnct() { return dataCovariancesVarUnct; } /** * @return the dataCorrelationsVarUnct */ public AbstractMatrixModel getDataCorrelationsVarUnct() { return dataCorrelationsVarUnct; } /** * @return the rhos */ public Map<String, BigDecimal> getRhosVarUnct() { return rhos; } /** * * @return */ public Map<String, BigDecimal> getRhosVarUnctForXMLSerialization() { Map<String, BigDecimal> tightRhos = new HashMap<>(); Iterator<String> rhosKeyIterator = rhos.keySet().iterator(); while (rhosKeyIterator.hasNext()) { String key = rhosKeyIterator.next(); if (rhos.get(key).compareTo(BigDecimal.ZERO) != 0) { tightRhos.put(key, rhos.get(key)); } } return tightRhos; } /** * * @return */ public Map<String, BigDecimal> getRhosSysUnctForXMLSerialization() { Map<String, BigDecimal> tightRhos = new HashMap<>(); Iterator<String> rhosKeyIterator = rhosSysUnct.keySet().iterator(); while (rhosKeyIterator.hasNext()) { String key = rhosKeyIterator.next(); if (rhosSysUnct.get(key).compareTo(BigDecimal.ZERO) != 0) { tightRhos.put(key, rhosSysUnct.get(key)); } } return tightRhos; } /** * * @return */ public Map<String, BigDecimal> cloneRhosVarUnct() { Map<String, BigDecimal> clonedRhosVarUnct = new HashMap<>(); rhos.entrySet().stream().forEach((entry) -> { clonedRhosVarUnct.put(entry.getKey(), entry.getValue()); }); return clonedRhosVarUnct; } /** * * @return */ public Map<String, BigDecimal> cloneRhosSysUnct() { Map<String, BigDecimal> clonedRhosSysUnct = new HashMap<>(); rhosSysUnct.entrySet().stream().forEach((entry) -> { clonedRhosSysUnct.put(entry.getKey(), entry.getValue()); }); return clonedRhosSysUnct; } // backward compatible /** * * @param coeffName * @return */ public ValueModel getRhoVarUnctByName(String coeffName) { BigDecimal myRhoValue = rhos.get(coeffName); if (myRhoValue == null) { myRhoValue = BigDecimal.ZERO; } ValueModel coeffModel = new ValueModel(// // coeffName, myRhoValue, "NONE", BigDecimal.ZERO, BigDecimal.ZERO); return coeffModel; } /** * @return the rhosSysUnct */ public Map<String, BigDecimal> getRhosSysUnct() { return rhosSysUnct; } /** * @param rhosSysUnct the rhosSysUnct to set */ public void setRhosSysUnct(Map<String, BigDecimal> rhosSysUnct) { this.rhosSysUnct = rhosSysUnct; } // XML Serialization ******************************************************* /** * * @return */ protected XStream getXStream() { XStream xstream = new XStream(new DomDriver()); customizeXstream(xstream); return xstream; } /** * registers converter for argument <code>xstream</code> and sets aliases to * make the XML file more human-readable * * @pre argument <code>xstream</code> is a valid <code>XStream</code> * @post argument <code>xstream</code> is customized to produce a cleaner * output <code>file</code> * * @param xstream <code>XStream</code> to be customized */ protected abstract void customizeXstream(XStream xstream); /** * sets the XML schema. Initializes <code>UPbReduxConfigurator</code> and * sets the location of the XML Schema * * @param resourceURI * @pre <code>UPbReduxConfigurator</code> class is available * @post <code>AbstractRatiosDataModelXMLSchemaURL</code> will be set */ protected void setClassXMLSchemaURL(String resourceURI) { UPbReduxConfigurator myConfigurator = new UPbReduxConfigurator(); XMLSchemaURL = myConfigurator.getResourceURI(resourceURI); } /** * encodes this <code>AbstractRatiosDataModel</code> to the * <code>file</code> specified by the argument <code>filename</code> * * @param filename location to store data to * @pre this <code>AbstractRatiosDataModel</code> exists * @post this <code>AbstractRatiosDataModel</code> is stored in the * specified XML <code>file</code> */ @Override public void serializeXMLObject(String filename) { XStream xstream = getXStream(); String xml = xstream.toXML(this); xml = ReduxConstants.XML_Header + xml; xml = xml.replaceFirst(this.getClassNameAliasForXML(), this.getClassNameAliasForXML() + " "// + ReduxConstants.XML_ResourceHeader// + XMLSchemaURL// + "\""); try { FileWriter outFile = new FileWriter(filename); PrintWriter out = new PrintWriter(outFile); // Write xml to file out.println(xml); out.flush(); out.close(); outFile.close(); } catch (IOException e) { } } /** * decodes <code>AbstractRatiosDataModel</code> from <code>file</code> * specified by argument <code>filename</code> * * @throws org.earthtime.exceptions.ETException * @pre <code>filename</code> references an XML <code>file</code> * @post <code>AbstractRatiosDataModel</code> stored in * <code>filename</code> is returned * * @param filename location to read data from * @param doValidate * @return <code>Object</code> - the <code>AbstractRatiosDataModel</code> * created from the specified XML <code>file</code> * @throws java.io.FileNotFoundException * @throws org.earthtime.XMLExceptions.BadOrMissingXMLSchemaException */ @Override public AbstractRatiosDataModel readXMLObject(String filename, boolean doValidate) throws FileNotFoundException, ETException, BadOrMissingXMLSchemaException { AbstractRatiosDataModel myModelClassInstance = null; BufferedReader reader = URIHelper.getBufferedReader(filename); if (reader != null) { XStream xstream = getXStream(); boolean isValidOrAirplaneMode = !doValidate; if (doValidate) { isValidOrAirplaneMode = URIHelper.validateXML(reader, filename, XMLSchemaURL); } if (isValidOrAirplaneMode) { // re-create reader reader = URIHelper.getBufferedReader(filename); try { myModelClassInstance = (AbstractRatiosDataModel) xstream.fromXML(reader); myModelClassInstance.initializeModel(); } catch (ConversionException e) { throw new ETException(null, e.getMessage()); } } else { throw new ETException(null, "XML data file does not conform to schema."); } } else { throw new FileNotFoundException("Missing XML data file."); } return myModelClassInstance; } // END XML Serialization *************************************************** /** * @return the reference */ public String getReference() { return reference; } /** * @return the comment */ public String getComment() { return comment; } /** * @return the classNameAliasForXML */ public abstract String getClassNameAliasForXML(); /** * @param modelName the modelName to set */ public void setModelName(String modelName) { this.modelName = modelName; } /** * @param reference the reference to set */ public void setReference(String reference) { this.reference = reference; } /** * @param comment the comment to set */ public void setComment(String comment) { this.comment = comment; } /** * @param versionNumber the versionNumber to set */ public void setVersionNumber(int versionNumber) { this.versionNumber = versionNumber; } /** * @param labName the labName to set */ public void setLabName(String labName) { this.labName = labName; } /** * @param dateCertified the dateCertified to set */ public void setDateCertified(String dateCertified) { this.dateCertified = dateCertified; } /** * @param ratios the ratios to set */ public void setRatios(ValueModel[] ratios) { this.ratios = ratios; } /** * @param rhos the rhos to set */ public void setRhosVarUnct(Map<String, BigDecimal> rhos) { this.rhos = rhos; } /** * * @return */ @Override public String toString() { return getNameAndVersion(); } }
apache-2.0
falko/camunda-bpm-platform
engine/src/test/java/org/camunda/bpm/engine/test/api/repository/diagram/ProcessDiagramParseTest.java
4791
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.test.api.repository.diagram; import org.camunda.bpm.engine.impl.bpmn.diagram.ProcessDiagramLayoutFactory; import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.camunda.bpm.engine.impl.interceptor.Command; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.repository.DiagramLayout; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * @author Nikola Koevski */ public class ProcessDiagramParseTest { private static final String resourcePath = "src/test/resources/org/camunda/bpm/engine/test/api/repository/diagram/testXxeParsingIsDisabled"; @Rule public ProcessEngineRule engineRule = new ProvidedProcessEngineRule(); protected ProcessEngineConfigurationImpl processEngineConfiguration; boolean xxeProcessingValue; @Before public void setUp() { processEngineConfiguration = engineRule.getProcessEngineConfiguration(); xxeProcessingValue = processEngineConfiguration.isEnableXxeProcessing(); } @After public void tearDown() { processEngineConfiguration.setEnableXxeProcessing(xxeProcessingValue); } @Test public void testXxeParsingIsDisabled() { processEngineConfiguration.setEnableXxeProcessing(false); try { final InputStream bpmnXmlStream = new FileInputStream( resourcePath + ".bpmn20.xml"); final InputStream imageStream = new FileInputStream( resourcePath + ".png"); assertNotNull(bpmnXmlStream); // when we run this in the ProcessEngine context engineRule.getProcessEngineConfiguration() .getCommandExecutorTxRequired() .execute(new Command<DiagramLayout>() { @Override public DiagramLayout execute(CommandContext commandContext) { return new ProcessDiagramLayoutFactory().getProcessDiagramLayout(bpmnXmlStream, imageStream); } }); fail("The test model contains a DOCTYPE declaration! The test should fail."); } catch (FileNotFoundException ex) { fail("The test BPMN model file is missing. " + ex.getMessage()); } catch (Exception e) { // then assertThat(e.getMessage(), containsString("Error while parsing BPMN model")); assertThat(e.getCause().getMessage(), containsString("http://apache.org/xml/features/disallow-doctype-decl")); } } @Test public void testXxeParsingIsEnabled() { processEngineConfiguration.setEnableXxeProcessing(true); try { final InputStream bpmnXmlStream = new FileInputStream( resourcePath + ".bpmn20.xml"); final InputStream imageStream = new FileInputStream( resourcePath + ".png"); assertNotNull(bpmnXmlStream); // when we run this in the ProcessEngine context engineRule.getProcessEngineConfiguration() .getCommandExecutorTxRequired() .execute(new Command<DiagramLayout>() { @Override public DiagramLayout execute(CommandContext commandContext) { return new ProcessDiagramLayoutFactory().getProcessDiagramLayout(bpmnXmlStream, imageStream); } }); fail("The test model contains a DOCTYPE declaration! The test should fail."); } catch (FileNotFoundException ex) { fail("The test BPMN model file is missing. " + ex.getMessage()); } catch (Exception e) { // then assertThat(e.getMessage(), containsString("Error while parsing BPMN model")); assertThat(e.getCause().getMessage(), containsString("file.txt")); } } }
apache-2.0
b2ihealthcare/snow-owl
commons/com.b2international.collections.fastutil/src/com/b2international/collections/bytes/ByteArrayListWrapper.java
3372
/* * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.collections.bytes; import it.unimi.dsi.fastutil.bytes.ByteArrayList; /** * @since 4.7 */ public final class ByteArrayListWrapper extends ByteCollectionWrapper implements ByteList { private ByteArrayListWrapper(it.unimi.dsi.fastutil.bytes.ByteList delegate) { super(delegate); } @Override public int hashCode() { return AbstractByteCollection.hashCode(this); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ByteList)) { return false; } ByteList other = (ByteList) obj; if (size() != other.size()) { return false; } return AbstractByteCollection.elementsEqual(iterator(), other.iterator()); } @Override protected it.unimi.dsi.fastutil.bytes.ByteList delegate() { return (it.unimi.dsi.fastutil.bytes.ByteList) super.delegate(); } @Override public void trimToSize() { final it.unimi.dsi.fastutil.bytes.ByteList list = delegate(); if (list instanceof ByteArrayList) { ((ByteArrayList) list).trim(); } else { super.trimToSize(); } } @Override public byte get(int index) { return delegate().getByte(index); } @Override public ByteListIterator listIterator() { return new ByteListIteratorWrapper(delegate().listIterator()); } @Override public ByteListIterator listIterator(int startIndex) { return new ByteListIteratorWrapper(delegate().listIterator(startIndex)); } @Override public byte set(int index, byte value) { return delegate().set(index, value); } @Override public byte removeByte(int index) { return delegate().removeByte(index); } // Builder methods public static ByteList create(ByteCollection collection) { if (collection instanceof ByteArrayListWrapper) { final it.unimi.dsi.fastutil.bytes.ByteList sourceDelegate = ((ByteArrayListWrapper) collection).delegate(); return new ByteArrayListWrapper(clone(sourceDelegate)); } else { final ByteList result = createWithExpectedSize(collection.size()); result.addAll(collection); return result; } } public static ByteList create(byte[] source) { return new ByteArrayListWrapper(new ByteArrayList(source)); } public static ByteList createWithExpectedSize(int expectedSize) { return new ByteArrayListWrapper(new ByteArrayList(expectedSize)); } public static ByteList create() { return new ByteArrayListWrapper(new ByteArrayList()); } // FastUtil helpers private static it.unimi.dsi.fastutil.bytes.ByteList clone(it.unimi.dsi.fastutil.bytes.ByteList list) { if (list instanceof ByteArrayList) { return ((ByteArrayList) list).clone(); } else { throw new UnsupportedOperationException("Unsupported list implementation: " + list.getClass().getSimpleName()); } } }
apache-2.0
minanos/minano
modules/api/src/main/java/org/rest/sec/model/Role.java
3150
package org.rest.sec.model; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang3.builder.ToStringBuilder; import org.rest.common.persistence.model.INameableEntity; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; import com.thoughtworks.xstream.annotations.XStreamImplicit; @Entity @XmlRootElement @XStreamAlias("role") public class Role implements INameableEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ROLE_ID") @XStreamAsAttribute private Long id; @Column(unique = true, nullable = false) private String name; // @formatter:off @ManyToMany( /* cascade = { CascadeType.REMOVE }, */fetch = FetchType.EAGER) @JoinTable(joinColumns = { @JoinColumn(name = "ROLE_ID", referencedColumnName = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "PRIV_ID", referencedColumnName = "PRIV_ID") }) @XStreamImplicit private Set<Privilege> privileges; // @formatter:on public Role() { super(); } public Role(final String nameToSet) { super(); name = nameToSet; } public Role(final String nameToSet, final Set<Privilege> privilegesToSet) { super(); name = nameToSet; privileges = privilegesToSet; } // API @Override public Long getId() { return id; } @Override public void setId(final Long idToSet) { id = idToSet; } @Override public String getName() { return name; } public void setName(final String nameToSet) { name = nameToSet; } public Set<Privilege> getPrivileges() { return privileges; } public void setPrivileges(final Set<Privilege> privilegesToSet) { privileges = privilegesToSet; } // @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Role other = (Role) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return new ToStringBuilder(this).append("id", id).append("name", name).toString(); } }
apache-2.0
hss01248/ImageLoader
imageloader/src/main/java/com/hss01248/image/exif/ExifUtil.java
37509
package com.hss01248.image.exif; import android.text.Html; import android.text.TextUtils; import android.util.Log; import com.hss01248.image.MyUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import it.sephiroth.android.library.exif2.ExifInterface; import it.sephiroth.android.library.exif2.ExifTag; import it.sephiroth.android.library.exif2.IfdId; /** * time:2019/11/9 * author:hss * desription: */ public class ExifUtil { private static final String LOG_TAG = "ExifUtil"; private static int mTagsCount; public static CharSequence printFile(String path) { try { FileInputStream inputStream = new FileInputStream(path); return processInputStream(inputStream); } catch (FileNotFoundException e) { e.printStackTrace(); return e.getMessage(); } } static List<String> tags; private static List<String> getTags() { if (tags != null && !tags.isEmpty()) { return tags; } tags = new ArrayList<>(); Class clazz = android.media.ExifInterface.class; Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getName().startsWith("TAG_")) { try { tags.add(field.get(null).toString()); } catch (Throwable e) { //e.printStackTrace(); } } } return tags; } public int readDegree(String path) { int degree = 0; try { androidx.exifinterface.media.ExifInterface exifInterface = new androidx.exifinterface.media.ExifInterface(path); int orientation = exifInterface.getAttributeInt( androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, androidx.exifinterface.media.ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } return degree; } catch (Throwable e) { e.printStackTrace(); return 0; } } public static String readExif(String path) { int degree = 0; try { androidx.exifinterface.media.ExifInterface exifInterface = new androidx.exifinterface.media.ExifInterface(path); int orientation = exifInterface.getAttributeInt( androidx.exifinterface.media.ExifInterface.TAG_ORIENTATION, androidx.exifinterface.media.ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case androidx.exifinterface.media.ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } List<String> tags = getTags(); ExifInterface exifInterface1 = new ExifInterface(); exifInterface1.readExif(path, ExifInterface.Options.OPTION_ALL); int quality = exifInterface1.getQualityGuess(); int[] wh = MyUtil.getImageWidthHeight(path); StringBuilder sb = new StringBuilder(); sb.append("file info:"); sb.append("\n") .append(path) .append("\nwh") .append(wh[0]) .append("x") .append(wh[1]) .append("\nsize:") .append(MyUtil.formatFileSize(new File(path).length())) .append("\ntype:") .append(MyUtil.getRealType(new File(path))); sb.append("\njpeg quality guess:").append(quality); sb.append("\norientation degree:").append(degree); for (String tag : tags) { if(!TextUtils.isEmpty(tag)){ String attr = exifInterface.getAttribute(tag); if (!TextUtils.isEmpty(attr)) { sb.append("\n").append(tag) .append(":") .append(attr); } } } return sb.toString(); } catch (Throwable e) { e.printStackTrace(); return e.getMessage(); } } private static CharSequence processInputStream(InputStream stream) { ExifInterface mExif = new ExifInterface(); List<ExifTag> all_tags = null; String exifInfoStr = ""; mTagsCount = 0; if (null != stream) { long t1 = System.currentTimeMillis(); try { mExif.readExif(stream, ExifInterface.Options.OPTION_ALL); } catch (IOException e) { e.printStackTrace(); mExif = null; } long t2 = System.currentTimeMillis(); Log.d(LOG_TAG, "parser time: " + (t2 - t1) + "ms"); if (null != mExif) { all_tags = mExif.getAllTags(); Log.d(LOG_TAG, "total tags: " + (all_tags != null ? all_tags.size() : 0)); } } if (null != mExif) { mTagsCount = 0; StringBuilder string = new StringBuilder(); NumberFormat numberFormatter = DecimalFormat.getNumberInstance(); // dumpToFile( mExif ); string.append("JPEG EXIF<br/>"); // new LoadThumbnailTask().execute( mExif ); if (mExif.getQualityGuess() > 0) { string.append("<b>JPEG quality:</b> " + mExif.getQualityGuess() + "<br>"); } int[] imagesize = mExif.getImageSize(); if (imagesize[0] > 0 && imagesize[1] > 0) { string.append("<b>Image Size: </b>" + imagesize[0] + "x" + imagesize[1] + "<br>"); } string.append(createStringFromIfFound(mExif, ExifInterface.TAG_IMAGE_WIDTH, "TAG_IMAGE_WIDTH", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_IMAGE_LENGTH, "TAG_IMAGE_LENGTH", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_BITS_PER_SAMPLE, "TAG_BITS_PER_SAMPLE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_COMPRESSION, "TAG_COMPRESSION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_PHOTOMETRIC_INTERPRETATION, "TAG_PHOTOMETRIC_INTERPRETATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_IMAGE_DESCRIPTION, "TAG_IMAGE_DESCRIPTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_MAKE, "TAG_MAKE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_MODEL, "TAG_MODEL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_STRIP_OFFSETS, "TAG_STRIP_OFFSETS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_ORIENTATION, "TAG_ORIENTATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SAMPLES_PER_PIXEL, "TAG_SAMPLES_PER_PIXEL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_ROWS_PER_STRIP, "TAG_ROWS_PER_STRIP", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_STRIP_BYTE_COUNTS, "TAG_STRIP_BYTE_COUNTS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_X_RESOLUTION, "TAG_X_RESOLUTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_Y_RESOLUTION, "TAG_Y_RESOLUTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_PLANAR_CONFIGURATION, "TAG_PLANAR_CONFIGURATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_RESOLUTION_UNIT, "TAG_RESOLUTION_UNIT", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_TRANSFER_FUNCTION, "TAG_TRANSFER_FUNCTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SOFTWARE, "TAG_SOFTWARE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_DATE_TIME, "TAG_DATE_TIME", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_ARTIST, "TAG_ARTIST", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_WHITE_POINT, "TAG_WHITE_POINT", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_PRIMARY_CHROMATICITIES, "TAG_PRIMARY_CHROMATICITIES", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_Y_CB_CR_COEFFICIENTS, "TAG_Y_CB_CR_COEFFICIENTS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_Y_CB_CR_SUB_SAMPLING, "TAG_Y_CB_CR_SUB_SAMPLING", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_Y_CB_CR_POSITIONING, "TAG_Y_CB_CR_POSITIONING", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_REFERENCE_BLACK_WHITE, "TAG_REFERENCE_BLACK_WHITE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_COPYRIGHT, "TAG_COPYRIGHT", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXIF_IFD, "TAG_EXIF_IFD", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_IFD, "TAG_GPS_IFD", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT, "TAG_JPEG_INTERCHANGE_FORMAT", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, "TAG_JPEG_INTERCHANGE_FORMAT_LENGTH", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXPOSURE_TIME, "TAG_EXPOSURE_TIME", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_F_NUMBER, "TAG_F_NUMBER", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXPOSURE_PROGRAM, "TAG_EXPOSURE_PROGRAM", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SPECTRAL_SENSITIVITY, "TAG_SPECTRAL_SENSITIVITY", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_ISO_SPEED_RATINGS, "TAG_ISO_SPEED_RATINGS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_OECF, "TAG_OECF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXIF_VERSION, "TAG_EXIF_VERSION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_DATE_TIME_ORIGINAL, "TAG_DATE_TIME_ORIGINAL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_DATE_TIME_DIGITIZED, "TAG_DATE_TIME_DIGITIZED", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_COMPONENTS_CONFIGURATION, "TAG_COMPONENTS_CONFIGURATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_COMPRESSED_BITS_PER_PIXEL, "TAG_COMPRESSED_BITS_PER_PIXEL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SHUTTER_SPEED_VALUE, "TAG_SHUTTER_SPEED_VALUE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_APERTURE_VALUE, "TAG_APERTURE_VALUE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_BRIGHTNESS_VALUE, "TAG_BRIGHTNESS_VALUE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXPOSURE_BIAS_VALUE, "TAG_EXPOSURE_BIAS_VALUE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_MAX_APERTURE_VALUE, "TAG_MAX_APERTURE_VALUE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUBJECT_DISTANCE, "TAG_SUBJECT_DISTANCE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_METERING_MODE, "TAG_METERING_MODE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_LIGHT_SOURCE, "TAG_LIGHT_SOURCE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FLASH, "TAG_FLASH", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FOCAL_LENGTH, "TAG_FOCAL_LENGTH", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUBJECT_AREA, "TAG_SUBJECT_AREA", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_MAKER_NOTE, "TAG_MAKER_NOTE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_USER_COMMENT, "TAG_USER_COMMENT", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUB_SEC_TIME, "TAG_SUB_SEC_TIME", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUB_SEC_TIME_ORIGINAL, "TAG_SUB_SEC_TIME_ORIGINAL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUB_SEC_TIME_DIGITIZED, "TAG_SUB_SEC_TIME_DIGITIZED", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FLASHPIX_VERSION, "TAG_FLASHPIX_VERSION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_COLOR_SPACE, "TAG_COLOR_SPACE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_PIXEL_X_DIMENSION, "TAG_PIXEL_X_DIMENSION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_PIXEL_Y_DIMENSION, "TAG_PIXEL_Y_DIMENSION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_RELATED_SOUND_FILE, "TAG_RELATED_SOUND_FILE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_INTEROPERABILITY_IFD, "TAG_INTEROPERABILITY_IFD", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FLASH_ENERGY, "TAG_FLASH_ENERGY", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SPATIAL_FREQUENCY_RESPONSE, "TAG_SPATIAL_FREQUENCY_RESPONSE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FOCAL_PLANE_X_RESOLUTION, "TAG_FOCAL_PLANE_X_RESOLUTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FOCAL_PLANE_Y_RESOLUTION, "TAG_FOCAL_PLANE_Y_RESOLUTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FOCAL_PLANE_RESOLUTION_UNIT, "TAG_FOCAL_PLANE_RESOLUTION_UNIT", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUBJECT_LOCATION, "TAG_SUBJECT_LOCATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXPOSURE_INDEX, "TAG_EXPOSURE_INDEX", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SENSING_METHOD, "TAG_SENSING_METHOD", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FILE_SOURCE, "TAG_FILE_SOURCE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SCENE_TYPE, "TAG_SCENE_TYPE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_CFA_PATTERN, "TAG_CFA_PATTERN", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_CUSTOM_RENDERED, "TAG_CUSTOM_RENDERED", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_EXPOSURE_MODE, "TAG_EXPOSURE_MODE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_WHITE_BALANCE, "TAG_WHITE_BALANCE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_DIGITAL_ZOOM_RATIO, "TAG_DIGITAL_ZOOM_RATIO", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_FOCAL_LENGTH_IN_35_MM_FILE, "TAG_FOCAL_LENGTH_IN_35_MM_FILE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SCENE_CAPTURE_TYPE, "TAG_SCENE_CAPTURE_TYPE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GAIN_CONTROL, "TAG_GAIN_CONTROL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_CONTRAST, "TAG_CONTRAST", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SATURATION, "TAG_SATURATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SHARPNESS, "TAG_SHARPNESS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_DEVICE_SETTING_DESCRIPTION, "TAG_DEVICE_SETTING_DESCRIPTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SUBJECT_DISTANCE_RANGE, "TAG_SUBJECT_DISTANCE_RANGE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_IMAGE_UNIQUE_ID, "TAG_IMAGE_UNIQUE_ID", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_VERSION_ID, "TAG_GPS_VERSION_ID", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_LATITUDE_REF, "TAG_GPS_LATITUDE_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_LATITUDE, "TAG_GPS_LATITUDE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_LONGITUDE_REF, "TAG_GPS_LONGITUDE_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_LONGITUDE, "TAG_GPS_LONGITUDE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_ALTITUDE_REF, "TAG_GPS_ALTITUDE_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_ALTITUDE, "TAG_GPS_ALTITUDE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_TIME_STAMP, "TAG_GPS_TIME_STAMP", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_SATTELLITES, "TAG_GPS_SATTELLITES", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_STATUS, "TAG_GPS_STATUS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_MEASURE_MODE, "TAG_GPS_MEASURE_MODE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DOP, "TAG_GPS_DOP", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_SPEED_REF, "TAG_GPS_SPEED_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_SPEED, "TAG_GPS_SPEED", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_TRACK_REF, "TAG_GPS_TRACK_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_TRACK, "TAG_GPS_TRACK", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_IMG_DIRECTION_REF, "TAG_GPS_IMG_DIRECTION_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_IMG_DIRECTION, "TAG_GPS_IMG_DIRECTION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_MAP_DATUM, "TAG_GPS_MAP_DATUM", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_LATITUDE_REF, "TAG_GPS_DEST_LATITUDE_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_LATITUDE, "TAG_GPS_DEST_LATITUDE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_LONGITUDE_REF, "TAG_GPS_DEST_LONGITUDE_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_LONGITUDE, "TAG_GPS_DEST_LONGITUDE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_BEARING_REF, "TAG_GPS_DEST_BEARING_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_BEARING, "TAG_GPS_DEST_BEARING", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_DISTANCE_REF, "TAG_GPS_DEST_DISTANCE_REF", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DEST_DISTANCE, "TAG_GPS_DEST_DISTANCE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_PROCESSING_METHOD, "TAG_GPS_PROCESSING_METHOD", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_AREA_INFORMATION, "TAG_GPS_AREA_INFORMATION", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DATE_STAMP, "TAG_GPS_DATE_STAMP", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_GPS_DIFFERENTIAL, "TAG_GPS_DIFFERENTIAL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_INTEROPERABILITY_INDEX, "TAG_INTEROPERABILITY_INDEX", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_LENS_MAKE, "TAG_LENS_MAKE", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_LENS_MODEL, "TAG_LENS_MODEL", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_LENS_SPECS, "TAG_LENS_SPECS", all_tags)); string.append(createStringFromIfFound(mExif, ExifInterface.TAG_SENSITIVITY_TYPE, "TAG_SENSITIVITY_TYPE", all_tags)); // string.append( createStringFromIfFound( mExif, ExifInterface.TAG_INTEROP_VERSION, "TAG_INTEROP_VERSION", all_tags ) ); List<ExifTag> tags = mExif.getTagsForTagId(ExifInterface.getTrueTagKey(ExifInterface.TAG_ORIENTATION)); Log.d(LOG_TAG, "tags: " + tags); string.append("<br>--------------<br>"); string.append("<b>Total tags parsed:</b> " + mTagsCount + "<br>"); string.append("<b>Remaining tags:</b> " + (all_tags != null ? all_tags.size() : 0) + "<br>"); string.append("<b>Has Thumbnail:</b> " + mExif.hasThumbnail() + "<br>"); ExifTag tag = mExif.getTag(ExifInterface.TAG_EXIF_VERSION); if (null != tag) { string.append("<b>Exif version: </b> " + tag.getValueAsString() + "<br>"); } String latitude = mExif.getLatitude(); String longitude = mExif.getLongitude(); if (null != latitude && null != longitude) { string.append("<b>Latitude: </b> " + latitude + "<br>"); string.append("<b>Longitude: </b> " + longitude + "<br>"); } Integer val = mExif.getTagIntValue(ExifInterface.TAG_ORIENTATION); int orientation = 0; if (null != val) { orientation = ExifInterface.getRotationForOrientationValue(val.shortValue()); } string.append("<b>Orientation: </b> " + orientation + "<br>"); double aperture = mExif.getApertureSize(); if (aperture > 0) { string.append("<b>Aperture Size: </b> " + String.format("%.2f", aperture) + "<br>"); } ExifTag shutterSpeed = mExif.getTag(ExifInterface.TAG_SHUTTER_SPEED_VALUE); if (null != shutterSpeed) { double speed = shutterSpeed.getValueAsRational(0).toDouble(); Log.d(LOG_TAG, "speed: " + speed); NumberFormat decimalFormatter = DecimalFormat.getNumberInstance(); decimalFormatter.setMaximumFractionDigits(1); String speedString = "1/" + decimalFormatter.format(Math.pow(2, speed)) + "s"; string.append("<b>Shutter Speed: </b> " + speedString + "<br>"); } String lensModel = mExif.getLensModelDescription(); if (null != lensModel) { string.append("<b>Lens Specifications: </b> " + lensModel + "<br>"); } short process = mExif.getJpegProcess(); string.append("<b>JPEG Process: </b> " + process + "<br>"); if (null != all_tags) { Log.i(LOG_TAG, "---- remaining tags ---"); for (ExifTag remaining_tag : all_tags) { Log.v(LOG_TAG, "tag: " + String.format("0x%X", remaining_tag.getTagId()) + ", value: " + remaining_tag); } } return Html.fromHtml(string.toString()); /*double[] latlon = mExif.getLatLongAsDoubles(); if( null != latlon ) { GetGeoLocationTask task = new GetGeoLocationTask(); task.execute( latlon[0], latlon[1] ); }*/ } else { return "exif info: null"; } } private String processSharpness(int value) { switch (value) { case 0: return "Normal"; case 1: return "Soft"; case 2: return "Hard"; default: return "Unknown"; } } private String processContrast(int value) { switch (value) { case 0: return "Normal"; case 1: return "Soft"; case 2: return "Hard"; default: return "Unknown"; } } private String processSaturation(int value) { switch (value) { case 0: return "Normal"; case 1: return "Low Saturation"; case 2: return "High Saturation"; default: return "Unknown"; } } private String processGainControl(int value) { switch (value) { case 0: return "None"; case 1: return "Low Gain Up"; case 2: return "High Gain Up"; case 3: return "Low Gain Down"; case 4: return "High Gain Down"; default: return "Unknown"; } } private String processSceneCaptureType(int value) { switch (value) { case 0: return "Standard"; case 1: return "Landscape"; case 2: return "Portrait"; case 3: return "Night scene"; default: return "Unknown"; } } private String processSensingMethod(int value) { switch (value) { case 1: return "Not defined"; case 2: return "One-chip color area sensor"; case 3: return "Two-chip color area sensor JEITA CP-3451 - 41"; case 4: return "Three-chip color area sensor"; case 5: return "Color sequential area sensor"; case 7: return "Trilinear sensor"; case 8: return "Color sequential linear sensor"; default: return "Unknown"; } } private String processColorSpace(int value) { switch (value) { case 1: return "sRGB"; case 0xFFFF: return "Uncalibrated"; default: return "Unknown"; } } private String processExposureMode(int mode) { switch (mode) { case 0: return "Auto exposure"; case 1: return "Manual exposure"; case 2: return "Auto bracket"; default: return "Unknown"; } } private String processExposureProgram(int program) { switch (program) { case 1: return "Manual control"; case 2: return "Program normal"; case 3: return "Aperture priority"; case 4: return "Shutter priority"; case 5: return "Program creative (slow program)"; case 6: return "Program action(high-speed program)"; case 7: return "Portrait mode"; case 8: return "Landscape mode"; default: return "Unknown"; } } private String processMeteringMode(int mode) { switch (mode) { case 1: return "Average"; case 2: return "CenterWeightedAverage"; case 3: return "Spot"; case 4: return "MultiSpot"; case 5: return "Pattern"; case 6: return "Partial"; case 255: return "Other"; default: return "Unknown"; } } private String processLightSource(int value) { switch (value) { case 0: return "Auto"; case 1: return "Daylight"; case 2: return "Fluorescent"; case 3: return "Tungsten (incandescent light)"; case 4: return "Flash"; case 9: return "Fine weather"; case 10: return "Cloudy weather"; case 11: return "Shade"; case 12: return "Daylight fluorescent (D 5700 - 7100K)"; case 13: return "Day white fluorescent (N 4600 - 5400K)"; case 14: return "Cool white fluorescent (W 3900 - 4500K)"; case 15: return "White fluorescent (WW 3200 - 3700K)"; case 17: return "Standard light A"; case 18: return "Standard light B"; case 19: return "Standard light C"; case 20: return "D55"; case 21: return "D65"; case 22: return "D75"; case 23: return "D50"; case 24: return "ISO studio tungsten"; case 255: return "Other light source"; default: return "Unknown"; } } private String processWhiteBalance(int value) { switch (value) { case 0: return "Auto"; case 1: return "Manual"; default: return "Unknown"; } } private String processSubjectDistanceRange(int value) { switch (value) { case 1: return "Macro"; case 2: return "Close View"; case 3: return "Distant View"; default: return "Unknown"; } } private String processFlash(int flash) { Log.i(LOG_TAG, "flash: " + flash + ", " + (flash & 1)); switch (flash) { case 0x0000: return "Flash did not fire"; case 0x0001: return "Flash fired"; case 0x0005: return "Strobe return light not detected"; case 0x0007: return "Strobe return light detected"; case 0x0009: return "Flash fired, compulsory flash mode"; case 0x000D: return "Flash fired, compulsory flash mode, return light not detected"; case 0x000F: return "Flash fired, compulsory flash mode, return light detected"; case 0x0010: return "Flash did not fire, compulsory flash mode"; case 0x0018: return "Flash did not fire, auto mode"; case 0x0019: return "Flash fired, auto mode"; case 0x001D: return "Flash fired, auto mode, return light not detected"; case 0x001F: return "Flash fired, auto mode, return light detected"; case 0x0020: return "No flash function"; case 0x0041: return "Flash fired, red-eye reduction mode"; case 0x0045: return "Flash fired, red-eye reduction mode, return light not detected"; case 0x0047: return "Flash fired, red-eye reduction mode, return light detected"; case 0x0049: return "Flash fired, compulsory flash mode, red-eye reduction mode"; case 0x004D: return "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected"; case 0x004F: return "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected"; case 0x0059: return "Flash fired, auto mode, red-eye reduction mode"; case 0x005D: return "Flash fired, auto mode, return light not detected, red-eye reduction mode"; case 0x005F: return "Flash fired, auto mode, return light detected, red-eye reduction mode"; default: return "Reserved"; } } private String parseProcess(int process) { switch (process) { case 192: return "Baseline"; case 193: return "Extended sequential"; case 194: return "Progressive"; case 195: return "Lossless"; case 197: return "Differential sequential"; case 198: return "Differential progressive"; case 199: return "Differential lossless"; case 201: return "Extended sequential, arithmetic coding"; case 202: return "Progressive, arithmetic coding"; case 203: return "Lossless, arithmetic coding"; case 205: return "Differential sequential, arithmetic coding"; case 206: return "Differential progressive, arithmetic codng"; case 207: return "Differential lossless, arithmetic coding"; } return "Unknown"; } private static String createStringFromIfFound(ExifInterface exif, int key, String label, final List<ExifTag> all_tags) { String exifString = ""; ExifTag tag = exif.getTag(key); if (null != tag) { all_tags.remove(tag); int ifid = tag.getIfd(); String ifdid_str = ""; switch (ifid) { case IfdId.TYPE_IFD_0: ifdid_str = "ifd0"; break; case IfdId.TYPE_IFD_1: ifdid_str = "ifd1"; break; case IfdId.TYPE_IFD_EXIF: ifdid_str = "exif"; break; case IfdId.TYPE_IFD_GPS: ifdid_str = "gps"; break; case IfdId.TYPE_IFD_INTEROPERABILITY: ifdid_str = "interop"; break; } mTagsCount++; exifString += "<b>" + label.toLowerCase() + "(" + ifdid_str + "): </b>"; if (key == ExifInterface.TAG_DATE_TIME || key == ExifInterface.TAG_DATE_TIME_DIGITIZED || key == ExifInterface.TAG_DATE_TIME_ORIGINAL) { Date date = ExifInterface.getDateTime(tag.getValueAsString(), TimeZone.getDefault()); if (null != date) { exifString += java.text.DateFormat.getDateTimeInstance().format(date); } else { Log.e(LOG_TAG, "failed to format the date"); } } else { exifString += tag.forceGetValueAsString(); } exifString += "<br>"; } else { Log.w(LOG_TAG, "'" + label + "' not found"); } return exifString; } }
apache-2.0
bobmcwhirter/drools
drools-core/src/main/java/org/drools/common/PriorityQueueAgendaGroupFactory.java
818
package org.drools.common; import java.io.Externalizable; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; public class PriorityQueueAgendaGroupFactory implements AgendaGroupFactory, Externalizable { private static final AgendaGroupFactory INSTANCE = new PriorityQueueAgendaGroupFactory(); public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { } public void writeExternal(ObjectOutput out) throws IOException { } public static AgendaGroupFactory getInstance() { return INSTANCE; } public InternalAgendaGroup createAgendaGroup(String name, InternalRuleBase ruleBase) { return new BinaryHeapQueueAgendaGroup( name, ruleBase ); } }
apache-2.0
jithsjoy/speech-android-sdk
speech-android-wrapper/src/main/java/com/ibm/watson/developer_cloud/android/text_to_speech/v1/TextToSpeech.java
5183
/** * © Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package com.ibm.watson.developer_cloud.android.text_to_speech.v1; import android.util.Log; import com.ibm.watson.developer_cloud.android.speech_common.v1.TokenProvider; import org.apache.http.HttpResponse; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; /** * Speech Recognition Class for SDK functions * @author Viney Ugave (vaugave@us.ibm.com) */ public class TextToSpeech { protected static final String TAG = "TextToSpeech"; private TTSUtility ttsUtility; private String username; private String password; private URI hostURL; private TokenProvider tokenProvider = null; private String voice; /**Speech Recognition Shared Instance * */ private static TextToSpeech _instance = null; public static TextToSpeech sharedInstance(){ if(_instance == null){ synchronized(TextToSpeech.class){ _instance = new TextToSpeech(); } } return _instance; } /** * Init the shared instance with the context * @param uri */ public void initWithContext(URI uri){ this.setHostURL(uri); } /** * Send request of TTS * @param ttsString */ public void synthesize(String ttsString) { Log.d(TAG, "synthesize called: " + this.hostURL.toString() + "/v1/synthesize"); String[] Arguments = { this.hostURL.toString()+"/v1/synthesize", this.username, this.password, this.voice, ttsString, this.tokenProvider == null ? null : this.tokenProvider.getToken()}; try { ttsUtility = new TTSUtility(); ttsUtility.setCodec(TTSUtility.CODEC_WAV); ttsUtility.synthesize(Arguments); } catch (Exception e) { e.printStackTrace(); } } private void buildAuthenticationHeader(HttpGet httpGet) { // use token based authentication if possible, otherwise Basic Authentication will be used if (this.tokenProvider != null) { Log.d(TAG, "using token based authentication"); httpGet.setHeader("X-Watson-Authorization-Token",this.tokenProvider.getToken()); } else { Log.d(TAG, "using basic authentication"); httpGet.setHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(this.username, this.password), "UTF-8",false)); } } public JSONObject getVoices() { JSONObject object = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(this.hostURL+"/v1/voices"); Log.d(TAG,"url: " + this.hostURL+"/v1/voices"); this.buildAuthenticationHeader(httpGet); httpGet.setHeader("accept", "application/json"); HttpResponse executed = httpClient.execute(httpGet); InputStream is = executed.getEntity().getContent(); // get the JSON object containing the models from the InputStream BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); object = new JSONObject(responseStrBuilder.toString()); Log.d(TAG, object.toString()); } catch (IOException | JSONException e) { e.printStackTrace(); } return object; } /** * Set credentials * @param username * @param password */ public void setCredentials(String username, String password) { this.username = username; this.password = password; } /** * Set host URL * @param hostURL */ public void setHostURL(URI hostURL) { this.hostURL = hostURL; } /** * Set token provider (for token based authentication) */ public void setTokenProvider(TokenProvider tokenProvider) { this.tokenProvider = tokenProvider; } /** * Set TTS voice */ public void setVoice(String voice) { this.voice = voice; } }
apache-2.0
aravindc/databenecommons
src/test/java/org/databene/commons/math/IntervalParserTest.java
2106
/* * Copyright (C) 2004-2015 Volker Bergmann (volker.bergmann@bergmann-it.de). * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.databene.commons.math; import static org.junit.Assert.*; import java.text.ParsePosition; import org.databene.commons.ComparableComparator; import org.databene.commons.comparator.IntComparator; import org.junit.Test; /** * Tests the {@link IntervalParser}. * Created: 10.03.2011 16:04:54 * @since 0.5.8 * @author Volker Bergmann */ public class IntervalParserTest { @Test public void testClosedInterval() { Interval<Integer> parsedInterval = parseInterval("[1,2]"); assertEquals(new Interval<Integer>(1, true, 2, true, new ComparableComparator<Integer>()), parsedInterval); } @Test public void testOpenInterval() { Interval<Integer> parsedInterval = parseInterval("]1,2["); assertEquals(new Interval<Integer>(1, false, 2, false, new ComparableComparator<Integer>()), parsedInterval); } @Test public void testWhitespace() { Interval<Integer> parsedInterval = parseInterval(" [ 1 , 2 ] "); assertEquals(new Interval<Integer>(1, true, 2, true, new ComparableComparator<Integer>()), parsedInterval); } // helpers --------------------------------------------------------------------------------------------------------- private static Interval<Integer> parseInterval(String text) { IntervalParser<Integer> parser = new IntervalParser<Integer>(new IntParser(), new IntComparator()); return parser.parseObject(text, new ParsePosition(0)); } }
apache-2.0
EvilMcJerkface/crate
server/src/test/java/io/crate/analyze/DropFunctionAnalyzerTest.java
4225
/* * Licensed to Crate.io Inc. ("Crate.io") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate.io licenses * this file to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * To enable or use any of the enterprise features, Crate.io must have given * you permission to enable and use the Enterprise Edition of CrateDB and you * must have a valid Enterprise or Subscription Agreement with Crate.io. If * you enable or use features that are part of the Enterprise Edition, you * represent and warrant that you have a valid Enterprise or Subscription * Agreement with Crate.io. Your use of features of the Enterprise Edition * is governed by the terms and conditions of your Enterprise or Subscription * Agreement with Crate.io. */ package io.crate.analyze; import io.crate.action.sql.SessionContext; import io.crate.auth.user.User; import io.crate.sql.parser.SqlParser; import io.crate.test.integration.CrateDummyClusterServiceUnitTest; import io.crate.testing.SQLExecutor; import io.crate.types.DataTypes; import io.crate.types.ObjectType; import org.junit.Before; import org.junit.Test; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; public class DropFunctionAnalyzerTest extends CrateDummyClusterServiceUnitTest { private SQLExecutor e; @Before public void initExecutor() throws Exception { e = SQLExecutor.builder(clusterService).build(); } @Test public void testDropFunctionSimple() throws Exception { AnalyzedStatement analyzedStatement = e.analyze("DROP FUNCTION bar(long, object)"); assertThat(analyzedStatement, instanceOf(AnalyzedDropFunction.class)); AnalyzedDropFunction analysis = (AnalyzedDropFunction) analyzedStatement; assertThat(analysis.schema(), is("doc")); assertThat(analysis.name(), is("bar")); assertThat(analysis.ifExists(), is(false)); assertThat(analysis.argumentTypes().get(0), is(DataTypes.LONG)); assertThat(analysis.argumentTypes().get(1).id(), is(ObjectType.ID)); } @Test public void testDropFunctionWithSessionSetSchema() throws Exception { AnalyzedDropFunction analysis = (AnalyzedDropFunction) e.analyzer.analyze( SqlParser.createStatement("DROP FUNCTION bar(long, object)"), new SessionContext(User.CRATE_USER, "my_schema"), ParamTypeHints.EMPTY); assertThat(analysis.schema(), is("my_schema")); assertThat(analysis.name(), is("bar")); } @Test public void testDropFunctionExplicitSchemaSupersedesSessionSchema() throws Exception { AnalyzedDropFunction analysis = (AnalyzedDropFunction) e.analyzer.analyze( SqlParser.createStatement("DROP FUNCTION my_other_schema.bar(long, object)"), new SessionContext(User.CRATE_USER, "my_schema"), ParamTypeHints.EMPTY); assertThat(analysis.schema(), is("my_other_schema")); assertThat(analysis.name(), is("bar")); } @Test public void testDropFunctionIfExists() throws Exception { AnalyzedStatement analyzedStatement = e.analyze("DROP FUNCTION IF EXISTS bar(arg_long long, arg_obj object)"); assertThat(analyzedStatement, instanceOf(AnalyzedDropFunction.class)); AnalyzedDropFunction analysis = (AnalyzedDropFunction) analyzedStatement; assertThat(analysis.name(), is("bar")); assertThat(analysis.ifExists(), is(true)); assertThat(analysis.argumentTypes().get(0), is(DataTypes.LONG)); assertThat(analysis.argumentTypes().get(1).id(), is(ObjectType.ID)); } }
apache-2.0
PuneetKadian/bigdata-examples
bigdata-java/src/main/java/hackerrank/challenge/DiscountedPrice.java
868
package hackerrank.challenge; public class DiscountedPrice { public static void main(String[] args) { int[] arr = new int[5]; arr[0] = 1; arr[1] = 3; arr[2] = 3; arr[3] = 2; arr[4] = 5; finalPrice(arr); } // 1 3 3 2 5 static void finalPrice(int[] prices) { int sum = prices[prices.length - 1]; int min = prices[prices.length - 1]; String str = String.valueOf(prices.length - 1); for (int i = prices.length - 2; i >= 0; i--) { if(prices[i] < min) { sum += prices[i]; min = prices[i]; str = i + " " + str; } else { sum += prices[i] - min; } } System.out.println(sum); System.out.println(str); } }
apache-2.0
GwtMaterialDesign/gwt-material-addins
src/main/java/gwt/material/design/addins/client/StartupState.java
866
/* * #%L * GwtMaterial * %% * Copyright (C) 2015 - 2017 GwtMaterialDesign * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package gwt.material.design.addins.client; public class StartupState { public StartupState() { } public static class DebugState extends StartupState { public DebugState() { } } }
apache-2.0
dingjun84/mq-backup
rocketmq-client/src/main/java/com/alibaba/rocketmq/client/consumer/listener/MessageListenerConcurrently.java
1466
/** * Copyright (C) 2010-2013 Alibaba Group Holding Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.rocketmq.client.consumer.listener; import java.util.List; import com.alibaba.rocketmq.common.message.MessageExt; /** * 同一队列的消息并行消费 * * @author shijia.wxr<vintage.wang@gmail.com> * @since 2013-7-24 */ public interface MessageListenerConcurrently extends MessageListener { /** * 方法抛出异常等同于返回 ConsumeConcurrentlyStatus.RECONSUME_LATER<br> * P.S: 建议应用不要抛出异常 * * @param msgs * msgs.size() >= 1<br> * DefaultMQPushConsumer.consumeMessageBatchMaxSize=1,默认消息数为1 * @param context * @return */ public ConsumeConcurrentlyStatus consumeMessage(final List<MessageExt> msgs, final ConsumeConcurrentlyContext context); }
apache-2.0
trejkaz/derby
java/testing/org/apache/derby/impl/jdbc/UTF8ReaderTest.java
10873
/* Derby - Class org.apache.derby.impl.jdbc.UTF8ReaderTest Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.derby.impl.jdbc; import java.io.EOFException; import java.io.IOException; import java.io.Reader; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.types.StringDataValue; import org.apache.derbyTesting.functionTests.util.streams.LoopingAlphabetReader; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.BaseTestSuite; import org.apache.derbyTesting.junit.CleanDatabaseTestSetup; /** * Tests {@code UTF8Reader} using package-private classes/methods. */ public class UTF8ReaderTest extends BaseJDBCTestCase { public UTF8ReaderTest(String name) { super(name); } /** * Tests simple repositioning. */ public void testRepositioningSimple() throws IOException, SQLException, StandardException { setAutoCommit(false); Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery( "select * from Utf8ReaderTest where id = 101"); rs.next(); final int size = rs.getInt(2); StringDataValue dvd = (StringDataValue) ((EmbedResultSet)rs).getColumn(3); StoreStreamClob ssClob = new StoreStreamClob( dvd.getStreamWithDescriptor(), (EmbedResultSet)rs); Reader reader = ssClob.getInternalReader(1); assertEquals('a', reader.read()); // Get internal readers and do stuff. checkInternalStream(1, ssClob); // Get first character. checkInternalStream(26, ssClob); // Skip forwards inside buffer. checkInternalStream(17003, ssClob); // Skip forwards, refill buffer. checkInternalStream(size, ssClob); // Skip until end. assertEquals(-1, reader.read()); checkInternalStream(10, ssClob); // Rewind and refill buffer. try { checkInternalStream(size*2, ssClob); // Should fail, invalid pos. fail("Should have failed due to invalid position"); } catch (EOFException eofe) { // As expected, do nothing. } } /** * Tests repositioning withing the buffer. */ public void testRepositioningWithinBuffer() throws IOException, SQLException, StandardException { setAutoCommit(false); Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery( "select * from Utf8ReaderTest where id = 100"); rs.next(); StringDataValue dvd = (StringDataValue) ((EmbedResultSet)rs).getColumn(3); StoreStreamClob ssClob = new StoreStreamClob( dvd.getStreamWithDescriptor(), (EmbedResultSet)rs); Reader reader = ssClob.getInternalReader(1); assertEquals('a', reader.read()); int bufSize = 26000; char[] buf = new char[bufSize]; int count = 0; while (count < bufSize) { count += reader.read(buf, count, bufSize - count); } // We have now read 26001 chars. Next char should be 'b'. // Internal buffer size after the singel read below should be: // 26002 % 8192 = 1426 assertEquals('b', reader.read()); reader.close(); // Get internal readers and do stuff. checkInternalStream(26002, ssClob); checkInternalStream(26001, ssClob); checkInternalStream(26002-1426+1, ssClob); // First char in buffer checkInternalStream(26001+(8192-1426+1), ssClob); // Last char in buffer checkInternalStream(26002-1426, ssClob); // Requires reset checkInternalStream(26002-1426+1, ssClob); // Requires refilling buffer checkInternalStream(26002, ssClob); checkInternalStream(1, ssClob); } /** * Tests repositioning withing buffer with a "real text" to make sure the * correct values are returned. */ public void testRepositioningWithinBufferRealText() throws IOException, SQLException, StandardException { setAutoCommit(false); Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery( // See insertTestData "select * from Utf8ReaderTest where id = 1"); rs.next(); StringDataValue dvd = (StringDataValue) ((EmbedResultSet)rs).getColumn(3); StoreStreamClob ssClob = new StoreStreamClob( dvd.getStreamWithDescriptor(), (EmbedResultSet)rs); Reader reader = ssClob.getInternalReader(1); assertEquals('B', reader.read()); reader = ssClob.getInternalReader(24); assertEquals('\'', reader.read()); reader = ssClob.getInternalReader(42); assertEquals('H', reader.read()); reader = ssClob.getInternalReader(70); assertEquals('M', reader.read()); reader = ssClob.getInternalReader(102); assertEquals('M', reader.read()); reader = ssClob.getInternalReader(128); assertEquals('B', reader.read()); reader = ssClob.getInternalReader(155); assertEquals('A', reader.read()); reader = ssClob.getInternalReader(184); assertEquals('S', reader.read()); reader = ssClob.getInternalReader(207); assertEquals('H', reader.read()); reader = ssClob.getInternalReader(224); assertEquals('O', reader.read()); reader = ssClob.getInternalReader(128); char[] buf = new char[4]; assertEquals(4, reader.read(buf)); assertEquals("But ", new String(buf)); reader = ssClob.getInternalReader(70); buf = new char[32]; assertEquals(32, reader.read(buf)); assertEquals("Men the grocer and butcher sent\n", new String(buf)); } /** * Makes sure the data returned from the internal Clob matches the data * returned by a fresh looping alphabet stream. * * @param pos 1-based Clob position * @param clob internal store stream Clob representation */ private static void checkInternalStream(long pos, StoreStreamClob clob) throws IOException, SQLException { Reader canonStream = new LoopingAlphabetReader(pos + 100); long toSkip = pos -1; // Convert to 0-based index. while (toSkip > 0) { long skipped = canonStream.skip(toSkip); if (skipped > 0) { toSkip -= skipped; } } Reader clobStream = clob.getInternalReader(pos); assertEquals("Data mismatch", canonStream.read(), clobStream.read()); clobStream.close(); } /** * Returns a simple test suite, using the embedded driver only. * * @return A test suite. */ public static Test suite() { BaseTestSuite suite = new BaseTestSuite(UTF8ReaderTest.class); return new CleanDatabaseTestSetup(suite) { public void decorateSQL(Statement stmt) throws SQLException { insertTestData(stmt); } }; } /** * Inserts data used by the tests. * <p> * Use the id to select a Clob with specific contents. */ private static void insertTestData(Statement stmt) throws SQLException { int[][] sizes = new int[][] { {100, 1*1024*1024}, // 1M chars {101, 32*1024}, // 32K chars }; stmt.executeUpdate( "create table Utf8ReaderTest" + "(id int primary key, size int, dClob clob)"); PreparedStatement ps = stmt.getConnection().prepareStatement( "insert into Utf8ReaderTest values (?,?,?)"); for (int i=0; i < sizes.length; i++) { ps.setInt(1, sizes[i][0]); int size = sizes[i][1]; ps.setInt(2, size); ps.setCharacterStream(3, new LoopingAlphabetReader(size), size); ps.executeUpdate(); } // Insert some special pieces of text, repeat to get it represented as // a stream. ps.setInt(1, 1); int size = aintWeGotFun.length(); ps.setInt(2, size); StringBuffer str = new StringBuffer(32*1024 + aintWeGotFun.length()); while (str.length() < 32*1024) { str.append(aintWeGotFun); } ps.setString(3, str.toString()); ps.executeUpdate(); } /** * Test data, first part of "Ain't We Got Fun?" (public domain). * See http://en.wikipedia.org/wiki/Ain%27t_We_Got_Fun%3F */ public static final String aintWeGotFun = // 1-based positions for the first and the last character on line. "Bill collectors gather\n" + // 1 "'Round and rather\n" + // 24 "Haunt the cottage next door\n" + // 42 "Men the grocer and butcher sent\n" + // 70 "Men who call for the rent\n" + // 102 "But with in a happy chappy\n" + // 128 "And his bride of only a year\n" + // 155 "Seem to be so cheerful\n" + // 184 "Here's an earful\n" + // 207 "Of the chatter you hear\n"; // 224 /* // Code that can be used to check the positions in the text. String[] firstWords = new String[] {"Bill", "'Round", "Haunt", "Men th", "Men wh", "But", "And", "Seem", "Here's", "Of"}; for (int i=0; i < firstWords.length; i++) { System.out.println("> " + firstWords[i]); int clobPos = (int)clob.position(firstWords[i], 1); int strPos = aintWeGotFun.indexOf(firstWords[i]); System.out.println("\tClob: " + clobPos); System.out.println("\tString: " + strPos); assertTrue(clobPos == strPos +1); } */ }
apache-2.0
jordansjones/Mvc4j
Razor/src/main/java/nextmethod/codedom/CodeTypeOfExpression.java
862
/* * Copyright 2014 Jordan S. Jones <jordansjones@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nextmethod.codedom; import java.io.Serializable; /** * */ // TODO public class CodeTypeOfExpression extends CodeExpression implements Serializable { private static final long serialVersionUID = -3892990186612711363L; }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-networkservices/v1beta1/1.31.0/com/google/api/services/networkservices/v1beta1/model/Location.java
5310
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.networkservices.v1beta1.model; /** * A resource that represents Google Cloud Platform location. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Network Services API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Location extends com.google.api.client.json.GenericJson { /** * The friendly name for this location, typically a nearby city name. For example, "Tokyo". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String displayName; /** * Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us- * east1"} * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> labels; /** * The canonical id for this location. For example: `"us-east1"`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String locationId; /** * Service-specific metadata. For example the available capacity at the given location. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.Object> metadata; /** * Resource name for the location, which may vary between implementations. For example: `"projects * /example-project/locations/us-east1"` * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * The friendly name for this location, typically a nearby city name. For example, "Tokyo". * @return value or {@code null} for none */ public java.lang.String getDisplayName() { return displayName; } /** * The friendly name for this location, typically a nearby city name. For example, "Tokyo". * @param displayName displayName or {@code null} for none */ public Location setDisplayName(java.lang.String displayName) { this.displayName = displayName; return this; } /** * Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us- * east1"} * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getLabels() { return labels; } /** * Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us- * east1"} * @param labels labels or {@code null} for none */ public Location setLabels(java.util.Map<String, java.lang.String> labels) { this.labels = labels; return this; } /** * The canonical id for this location. For example: `"us-east1"`. * @return value or {@code null} for none */ public java.lang.String getLocationId() { return locationId; } /** * The canonical id for this location. For example: `"us-east1"`. * @param locationId locationId or {@code null} for none */ public Location setLocationId(java.lang.String locationId) { this.locationId = locationId; return this; } /** * Service-specific metadata. For example the available capacity at the given location. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.Object> getMetadata() { return metadata; } /** * Service-specific metadata. For example the available capacity at the given location. * @param metadata metadata or {@code null} for none */ public Location setMetadata(java.util.Map<String, java.lang.Object> metadata) { this.metadata = metadata; return this; } /** * Resource name for the location, which may vary between implementations. For example: `"projects * /example-project/locations/us-east1"` * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Resource name for the location, which may vary between implementations. For example: `"projects * /example-project/locations/us-east1"` * @param name name or {@code null} for none */ public Location setName(java.lang.String name) { this.name = name; return this; } @Override public Location set(String fieldName, Object value) { return (Location) super.set(fieldName, value); } @Override public Location clone() { return (Location) super.clone(); } }
apache-2.0
AndrewJack/moment-for-android-wear
mobile/src/main/java/technology/mainthread/apps/moment/ui/fragment/SignInFriendFinderFragment.java
6762
package technology.mainthread.apps.moment.ui.fragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.List; import javax.inject.Inject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import rx.Observable; import rx.Subscriber; import rx.subscriptions.CompositeSubscription; import technology.mainthread.apps.moment.MomentApp; import technology.mainthread.apps.moment.R; import technology.mainthread.apps.moment.data.rx.api.RxFriendApi; import technology.mainthread.apps.moment.data.rx.api.RxSyncFriends; import technology.mainthread.apps.moment.ui.adapter.FriendDiscoveryAdapter; import technology.mainthread.apps.moment.ui.view.LoaderCheckBox; import technology.mainthread.service.moment.friendApi.model.FriendResponse; public class SignInFriendFinderFragment extends BaseFragment implements FriendDiscoveryAdapter.FriendAddListener { @Inject RxFriendApi rxFriendApi; @Inject RxSyncFriends rxSyncFriends; @Bind(R.id.recycler_found_friends) RecyclerView mFoundFriendsRecycler; @Bind(R.id.txt_info) TextView mInfoText; @Bind(R.id.btn_invite) Button mInviteButton; @Bind(R.id.container_info) View mInfoContainer; @Bind(R.id.progress) View mProgress; private CompositeSubscription compositeSubscription = new CompositeSubscription(); public static Fragment newInstance() { return new SignInFriendFinderFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MomentApp.get(getActivity()).inject(this); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_sign_in_friend_finder, container, false); ButterKnife.bind(this, rootView); mInfoText.setText(R.string.searching_friends); mFoundFriendsRecycler.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false)); searchForFriends(); return rootView; } @Override public void onDestroyView() { compositeSubscription.unsubscribe(); ButterKnife.unbind(this); super.onDestroyView(); } @OnClick(R.id.btn_continue) void onContinueClicked() { getFragmentManager().beginTransaction() .setCustomAnimations(R.animator.slide_in, R.animator.slide_out) .replace(R.id.container, WearablesFragment.newInstance()) .commit(); } private void searchForFriends() { Observable<List<FriendResponse>> searchObservable = rxFriendApi.search() .compose(this.<List<FriendResponse>>bindToLifecycle()) .compose(this.<List<FriendResponse>>applySchedulers()); compositeSubscription.add(searchObservable.subscribe(new Subscriber<List<FriendResponse>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { noFriendsFound(); } @Override public void onNext(List<FriendResponse> response) { friendsFound(response); } })); } private void friendsFound(List<FriendResponse> response) { mProgress.setVisibility(View.GONE); if (response != null && !response.isEmpty()) { mFoundFriendsRecycler.setVisibility(View.VISIBLE); mInfoContainer.setVisibility(View.GONE); mFoundFriendsRecycler.setAdapter(new FriendDiscoveryAdapter(response, this, android.R.color.white)); } else { noFriendsFound(); } } private void noFriendsFound() { mFoundFriendsRecycler.setVisibility(View.GONE); mProgress.setVisibility(View.GONE); mInfoContainer.setVisibility(View.VISIBLE); mInfoText.setVisibility(View.VISIBLE); mInfoText.setText(R.string.no_friends_found); mInviteButton.setVisibility(View.VISIBLE); } @Override public void onAddClicked(final LoaderCheckBox view, long friendId, boolean isChecked) { if (isChecked) { // add Observable<Void> addObservable = rxFriendApi.add(friendId) .compose(this.<Void>bindToLifecycle()) .compose(this.<Void>applySchedulers()); compositeSubscription.add(addObservable.subscribe(new LoaderCheckBox.RxSubscriber(view) { @Override public void onNext(Void aVoid) { super.onNext(aVoid); Observable<Void> syncPending = rxSyncFriends.syncFriends() .compose(SignInFriendFinderFragment.this.<Void>bindToLifecycle()) .compose(SignInFriendFinderFragment.this.<Void>applySchedulers()); compositeSubscription.add(syncPending.subscribe()); } @Override public void onError(Throwable e) { super.onError(e); Toast.makeText(getActivity(), getString(R.string.toast_friend_add_error), Toast.LENGTH_SHORT).show(); } })); } else { // remove Observable<Void> removeObservable = rxFriendApi.remove(friendId) .compose(this.<Void>bindToLifecycle()) .compose(this.<Void>applySchedulers()); compositeSubscription.add(removeObservable.subscribe(new LoaderCheckBox.RxSubscriber(view) { @Override public void onNext(Void aVoid) { super.onNext(aVoid); Observable<Void> syncPending = rxSyncFriends.syncFriends() .compose(SignInFriendFinderFragment.this.<Void>bindToLifecycle()) .compose(SignInFriendFinderFragment.this.<Void>applySchedulers()); compositeSubscription.add(syncPending.subscribe()); } @Override public void onError(Throwable e) { super.onError(e); Toast.makeText(getActivity(), getString(R.string.toast_friend_remove_error), Toast.LENGTH_SHORT).show(); } })); } } }
apache-2.0
hs-web/hsweb-framework
hsweb-authorization/hsweb-authorization-basic/src/main/java/org/hswebframework/web/authorization/basic/define/DefaultBasicAuthorizeDefinition.java
5366
package org.hswebframework.web.authorization.basic.define; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import org.hswebframework.web.authorization.annotation.*; import org.hswebframework.web.authorization.define.*; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.util.StringUtils; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 默认权限权限定义 * * @author zhouhao * @since 3.0 */ @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class DefaultBasicAuthorizeDefinition implements AopAuthorizeDefinition { @JsonIgnore private Class<?> targetClass; @JsonIgnore private Method targetMethod; private ResourcesDefinition resources = new ResourcesDefinition(); private DimensionsDefinition dimensions = new DimensionsDefinition(); private String message = "error.access_denied"; private Phased phased; @Override public boolean isEmpty() { return false; } private static final Set<Class<? extends Annotation>> types = new HashSet<>(Arrays.asList( Authorize.class, DataAccess.class, Dimension.class, Resource.class, ResourceAction.class, DataAccessType.class )); public static AopAuthorizeDefinition from(Class<?> targetClass, Method method) { AopAuthorizeDefinitionParser parser = new AopAuthorizeDefinitionParser(targetClass, method); return parser.parse(); } public void putAnnotation(Authorize ann) { if (!ann.merge()) { getResources().getResources().clear(); getDimensions().getDimensions().clear(); } getResources().setPhased(ann.phased()); for (Resource resource : ann.resources()) { putAnnotation(resource); } for (Dimension dimension : ann.dimension()) { putAnnotation(dimension); } } public void putAnnotation(Dimension ann) { if (ann.ignore()) { getDimensions().getDimensions().clear(); return; } DimensionDefinition definition = new DimensionDefinition(); definition.setTypeId(ann.type()); definition.setDimensionId(new HashSet<>(Arrays.asList(ann.id()))); definition.setLogical(ann.logical()); getDimensions().addDimension(definition); } public void putAnnotation(Resource ann) { ResourceDefinition resource = new ResourceDefinition(); resource.setId(ann.id()); resource.setName(ann.name()); resource.setLogical(ann.logical()); resource.setPhased(ann.phased()); resource.setDescription(String.join("\n", ann.description())); for (ResourceAction action : ann.actions()) { putAnnotation(resource, action); } resource.setGroup(new ArrayList<>(Arrays.asList(ann.group()))); resources.addResource(resource, ann.merge()); } public ResourceActionDefinition putAnnotation(ResourceDefinition definition, ResourceAction ann) { ResourceActionDefinition actionDefinition = new ResourceActionDefinition(); actionDefinition.setId(ann.id()); actionDefinition.setName(ann.name()); actionDefinition.setDescription(String.join("\n", ann.description())); for (DataAccess dataAccess : ann.dataAccess()) { putAnnotation(actionDefinition, dataAccess); } definition.addAction(actionDefinition); return actionDefinition; } public void putAnnotation(ResourceActionDefinition definition, DataAccess ann) { if (ann.ignore()) { return; } DataAccessTypeDefinition typeDefinition = new DataAccessTypeDefinition(); for (DataAccessType dataAccessType : ann.type()) { if (dataAccessType.ignore()) { continue; } typeDefinition.setId(dataAccessType.id()); typeDefinition.setName(dataAccessType.name()); typeDefinition.setController(dataAccessType.controller()); typeDefinition.setConfiguration(dataAccessType.configuration()); typeDefinition.setDescription(String.join("\n", dataAccessType.description())); } if (StringUtils.isEmpty(typeDefinition.getId())) { return; } definition.getDataAccess() .getDataAccessTypes() .add(typeDefinition); } public void putAnnotation(ResourceActionDefinition definition, DataAccessType dataAccessType) { if (dataAccessType.ignore()) { return; } DataAccessTypeDefinition typeDefinition = new DataAccessTypeDefinition(); typeDefinition.setId(dataAccessType.id()); typeDefinition.setName(dataAccessType.name()); typeDefinition.setController(dataAccessType.controller()); typeDefinition.setConfiguration(dataAccessType.configuration()); typeDefinition.setDescription(String.join("\n", dataAccessType.description())); definition.getDataAccess() .getDataAccessTypes() .add(typeDefinition); } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-dialogflow/v2/1.31.0/com/google/api/services/dialogflow/v2/model/GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior.java
8432
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v2.model; /** * Configuration for how the filling of a parameter should be handled. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior extends com.google.api.client.json.GenericJson { /** * Required. The fulfillment to provide the initial prompt that the agent can present to the user * in order to fill the parameter. * The value may be {@code null}. */ @com.google.api.client.util.Key private GoogleCloudDialogflowCxV3beta1Fulfillment initialPromptFulfillment; /** * The handlers for parameter-level events, used to provide reprompt for the parameter or * transition to a different page/flow. The supported events are: * `sys.no-match-`, where N can * be from 1 to 6 * `sys.no-match-default` * `sys.no-input-`, where N can be from 1 to 6 * `sys * .no-input-default` * `sys.invalid-parameter` `initial_prompt_fulfillment` provides the first * prompt for the parameter. If the user's response does not fill the parameter, a no-match/no- * input event will be triggered, and the fulfillment associated with the `sys.no-match-1`/`sys * .no-input-1` handler (if defined) will be called to provide a prompt. The `sys.no-match-2`/`sys * .no-input-2` handler (if defined) will respond to the next no-match/no-input event, and so on. * A `sys.no-match-default` or `sys.no-input-default` handler will be used to handle all following * no-match/no-input events after all numbered no-match/no-input handlers for the parameter are * consumed. A `sys.invalid-parameter` handler can be defined to handle the case where the * parameter values have been `invalidated` by webhook. For example, if the user's response fill * the parameter, however the parameter was invalidated by webhook, the fulfillment associated * with the `sys.invalid-parameter` handler (if defined) will be called to provide a prompt. If * the event handler for the corresponding event can't be found on the parameter, * `initial_prompt_fulfillment` will be re-prompted. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudDialogflowCxV3beta1EventHandler> repromptEventHandlers; static { // hack to force ProGuard to consider GoogleCloudDialogflowCxV3beta1EventHandler used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowCxV3beta1EventHandler.class); } /** * Required. The fulfillment to provide the initial prompt that the agent can present to the user * in order to fill the parameter. * @return value or {@code null} for none */ public GoogleCloudDialogflowCxV3beta1Fulfillment getInitialPromptFulfillment() { return initialPromptFulfillment; } /** * Required. The fulfillment to provide the initial prompt that the agent can present to the user * in order to fill the parameter. * @param initialPromptFulfillment initialPromptFulfillment or {@code null} for none */ public GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior setInitialPromptFulfillment(GoogleCloudDialogflowCxV3beta1Fulfillment initialPromptFulfillment) { this.initialPromptFulfillment = initialPromptFulfillment; return this; } /** * The handlers for parameter-level events, used to provide reprompt for the parameter or * transition to a different page/flow. The supported events are: * `sys.no-match-`, where N can * be from 1 to 6 * `sys.no-match-default` * `sys.no-input-`, where N can be from 1 to 6 * `sys * .no-input-default` * `sys.invalid-parameter` `initial_prompt_fulfillment` provides the first * prompt for the parameter. If the user's response does not fill the parameter, a no-match/no- * input event will be triggered, and the fulfillment associated with the `sys.no-match-1`/`sys * .no-input-1` handler (if defined) will be called to provide a prompt. The `sys.no-match-2`/`sys * .no-input-2` handler (if defined) will respond to the next no-match/no-input event, and so on. * A `sys.no-match-default` or `sys.no-input-default` handler will be used to handle all following * no-match/no-input events after all numbered no-match/no-input handlers for the parameter are * consumed. A `sys.invalid-parameter` handler can be defined to handle the case where the * parameter values have been `invalidated` by webhook. For example, if the user's response fill * the parameter, however the parameter was invalidated by webhook, the fulfillment associated * with the `sys.invalid-parameter` handler (if defined) will be called to provide a prompt. If * the event handler for the corresponding event can't be found on the parameter, * `initial_prompt_fulfillment` will be re-prompted. * @return value or {@code null} for none */ public java.util.List<GoogleCloudDialogflowCxV3beta1EventHandler> getRepromptEventHandlers() { return repromptEventHandlers; } /** * The handlers for parameter-level events, used to provide reprompt for the parameter or * transition to a different page/flow. The supported events are: * `sys.no-match-`, where N can * be from 1 to 6 * `sys.no-match-default` * `sys.no-input-`, where N can be from 1 to 6 * `sys * .no-input-default` * `sys.invalid-parameter` `initial_prompt_fulfillment` provides the first * prompt for the parameter. If the user's response does not fill the parameter, a no-match/no- * input event will be triggered, and the fulfillment associated with the `sys.no-match-1`/`sys * .no-input-1` handler (if defined) will be called to provide a prompt. The `sys.no-match-2`/`sys * .no-input-2` handler (if defined) will respond to the next no-match/no-input event, and so on. * A `sys.no-match-default` or `sys.no-input-default` handler will be used to handle all following * no-match/no-input events after all numbered no-match/no-input handlers for the parameter are * consumed. A `sys.invalid-parameter` handler can be defined to handle the case where the * parameter values have been `invalidated` by webhook. For example, if the user's response fill * the parameter, however the parameter was invalidated by webhook, the fulfillment associated * with the `sys.invalid-parameter` handler (if defined) will be called to provide a prompt. If * the event handler for the corresponding event can't be found on the parameter, * `initial_prompt_fulfillment` will be re-prompted. * @param repromptEventHandlers repromptEventHandlers or {@code null} for none */ public GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior setRepromptEventHandlers(java.util.List<GoogleCloudDialogflowCxV3beta1EventHandler> repromptEventHandlers) { this.repromptEventHandlers = repromptEventHandlers; return this; } @Override public GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior set(String fieldName, Object value) { return (GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior) super.set(fieldName, value); } @Override public GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior clone() { return (GoogleCloudDialogflowCxV3beta1FormParameterFillBehavior) super.clone(); } }
apache-2.0
moosbusch/xbLIDO
src/net/opengis/gml/impl/SymbolDocumentImpl.java
2326
/* * Copyright 2013 Gunnar Kappei. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.opengis.gml.impl; /** * A document containing one symbol(@http://www.opengis.net/gml) element. * * This is a complex type. */ public class SymbolDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements net.opengis.gml.SymbolDocument { private static final long serialVersionUID = 1L; public SymbolDocumentImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName SYMBOL$0 = new javax.xml.namespace.QName("http://www.opengis.net/gml", "symbol"); /** * Gets the "symbol" element */ public net.opengis.gml.SymbolType getSymbol() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.SymbolType target = null; target = (net.opengis.gml.SymbolType)get_store().find_element_user(SYMBOL$0, 0); if (target == null) { return null; } return target; } } /** * Sets the "symbol" element */ public void setSymbol(net.opengis.gml.SymbolType symbol) { generatedSetterHelperImpl(symbol, SYMBOL$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON); } /** * Appends and returns a new empty "symbol" element */ public net.opengis.gml.SymbolType addNewSymbol() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.SymbolType target = null; target = (net.opengis.gml.SymbolType)get_store().add_element_user(SYMBOL$0); return target; } } }
apache-2.0