text
stringlengths
10
2.72M
package com.onplan.adviser.predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.onplan.adviser.predicate.priceaction.PriceSpikePredicate; import com.onplan.adviser.predicate.pricepattern.CandlestickHammerPredicate; import com.onplan.domain.configuration.AdviserPredicateConfiguration; import java.util.Collection; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; public class TestingAdviserPredicateConfigurationFactory { public static AdviserPredicateConfiguration createSampleAdviserPredicateConfiguration( Class<? extends AdviserPredicate> clazz, Map<String, String> parameters) { checkNotNull(clazz); return new AdviserPredicateConfiguration(clazz.getName(), ImmutableMap.copyOf(parameters)); } public static Collection<AdviserPredicateConfiguration> createSampleAdviserPredicateConfigurations() { return ImmutableList.of( createSampleAdviserPredicateConfiguration( PriceSpikePredicate.class, ImmutableMap.of(PriceSpikePredicate.PROPERTY_MINIMUM_PIPS, "10")), createSampleAdviserPredicateConfiguration( CandlestickHammerPredicate.class, ImmutableMap.of( CandlestickHammerPredicate.PROPERTY_TIME_FRAME, "MINUTES_1", CandlestickHammerPredicate.PROPERTY_MINIMUM_CANDLE_SIZE, "10"))); } }
/* * 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 raytracing3; import java.awt.KeyEventDispatcher; import java.awt.event.KeyEvent; /** * * @author ianmahoney */ public class MyDispatcher implements KeyEventDispatcher{ public Driver driver; public MyDispatcher(Driver driver){ this.driver = driver; } public boolean dispatchKeyEvent(KeyEvent e) { synchronized (MyDispatcher.class) { if (e.getID() == KeyEvent.KEY_PRESSED) { //System.out.println("tester"); } else if (e.getID() == KeyEvent.KEY_RELEASED) { //System.out.println("2test2"); } else if (e.getID() == KeyEvent.KEY_TYPED) { //System.out.println("3test3"); } System.out.println(e.getKeyCode()); switch (e.getKeyCode()) { case KeyEvent.VK_ESCAPE: break; case KeyEvent.VK_BACK_QUOTE: break; case KeyEvent.VK_ENTER: //System.out.println("enter"); //driver.run(); break; case KeyEvent.VK_LEFT: //driver.origin.x -= 10; //System.out.println("left"); break; case KeyEvent.VK_RIGHT: //driver.origin.x += 10; //System.out.println("right"); break; } return false; } } }
import javax.sound.sampled.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.File; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Frame { // variables declaration and initialization private static final JButton play = new JButton("PLAY"); private static final JButton quit = new JButton("QUIT"); private static final JButton enter = new JButton("ENTER"); private static final JLabel lblGuess = new JLabel("Enter your guess:"); private static final JLabel errorMsg = new JLabel(""); private static final JTextField guessField = new JTextField(10); private static final JLabel interval = new JLabel(); private static JFrame main, f2; static int tries, start, end, randomNum; static Interval ivl; private static void GUI() { main = new JFrame("Game"); f2 = new JFrame("Game"); main.setSize(280, 150); f2.setSize(600, 330); main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // buttons layout main.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 40)); main.add(play); main.add(quit); main.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); // make buttons work makePlayWork(); makeQuitWork(); makeEnterWork(); // center windows main.setLocationRelativeTo(null); f2.setLocationRelativeTo(null); main.setVisible(true); } // place buttons, text labels, and text fields private static void placeStuff() { f2.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(35, 0, 30, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; f2.add(interval, gbc); gbc.insets = new Insets(35, 0, 0, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 1; f2.add(lblGuess, gbc); gbc.insets = new Insets(5, 0, 0, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 10; gbc.gridx = 0; gbc.gridy = 3; f2.add(guessField, gbc); gbc.insets = new Insets(0, 0, 0, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 4; f2.add(errorMsg, gbc); gbc.insets = new Insets(15, 0, 10, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 5; f2.add(enter, gbc); } private static void secondFrame() { main.dispose(); placeStuff(); // accepts only numeric digits and no other keys guessField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent ke) { char c = ke.getKeyChar(); if ((c < '0') || (c > '9')) { ke.consume(); if (Character.isLetter(c)) { errorMsg.setText("Invalid input"); errorMsg.setForeground(Color.RED); } } else errorMsg.setForeground(f2.getBackground()); } }); guessField.setHorizontalAlignment(JTextField.CENTER); guessField.setFont(new Font("Arial", Font.PLAIN, 20)); interval.setFont(new Font("Arial", Font.BOLD, 25)); ivl = new Interval(0, 100); start = ivl.getStart(); end = ivl.getEnd(); randomNum = (int) (Math.random() * (end - start + 1) + start); updateInterval(); JOptionPane.showMessageDialog(f2, "Welcome to BINGO! A random number has been " + "generated 1 and 100.", "BINGO! Welcome Message", JOptionPane.INFORMATION_MESSAGE, null); playSound("start.wav"); f2.setVisible(true); f2.getRootPane().setDefaultButton(enter); } // from http://suavesnippets.blogspot.com/2011/06/add-sound-on-jbutton-click-in-java.html private static void playSound(String soundName) { try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile()); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.start(); } catch(Exception ex) { System.out.println("Error with playing sound."); ex.printStackTrace(); } } // action listener for play button private static void makePlayWork() { play.addActionListener(e -> { playSound("start.wav"); playSound("logon.wav"); secondFrame(); }); } // action listener for quit button private static void makeQuitWork() { quit.addActionListener(e -> { playSound("start.wav"); int confirmation = JOptionPane.showConfirmDialog(null, "Are you sure" + " you want to quit the game?", "Exit Game?", JOptionPane.YES_NO_CANCEL_OPTION); if (confirmation == JOptionPane.YES_OPTION) { playSound("start.wav"); playSound("logoff.wav"); main.dispose(); } else playSound("start.wav"); }); } // action listener for enter button private static void makeEnterWork() { enter.addActionListener(e -> { playSound("start.wav"); if (!guessField.getText().equals("")) { int guessNum = Integer.parseInt(guessField.getText()); if (ivl.withinBoundary(guessNum)) { if (guessNum != randomNum) { playSound("chord.wav"); tries++; ivl.updateInterval(guessNum, randomNum); JOptionPane.showMessageDialog(null, "WRONG!", "ERROR", JOptionPane.ERROR_MESSAGE); updateInterval(); } else { playSound("tada.wav"); if (tries > 1) { JOptionPane.showMessageDialog(null, "BINGO! The secret number is " + guessNum + ". And it took you " + tries + " tries."); playSound("ding.wav"); } else { JOptionPane.showMessageDialog(null, "What a lucky guy! The secret number is " + guessNum + ". And it took you 1 try ONLY!"); playSound("ding.wav"); } int res = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "One More?", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.YES_OPTION) { playSound("start.wav"); gameReset(); playSound("logon.wav"); JOptionPane.showMessageDialog(null, "A new game has started. Good Luck!"); playSound("start.wav"); } else { playSound("start.wav"); JOptionPane.showMessageDialog(null, "Thanks for your participation! Please come again!"); playSound("start.wav"); playSound("logoff.wav"); System.exit(0); } } } else { playSound("critical-stop.wav"); JOptionPane.showMessageDialog(null, "OUT OF BOUNDARY!", "ERROR", JOptionPane.ERROR_MESSAGE); playSound("start.wav"); } guessField.setText(""); } }); } // update interval displayed private static void updateInterval() { interval.setText(ivl.getStart() + " - " + ivl.getEnd()); } // function for resetting game private static void gameReset() { tries = 0; ivl = new Interval(0, 100); updateInterval(); } public static void main(String[] args) { GUI(); } }
package com.theta360.sample.v2; import android.app.Activity; import android.app.FragmentManager; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.Image; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import com.theta360.sample.v2.glview.GLPhotoView; import com.theta360.sample.v2.model.Photo; import com.theta360.sample.v2.model.RotateInertia; import com.theta360.sample.v2.network.HttpDownloadListener; import com.theta360.sample.v2.network.HttpConnector; import com.theta360.sample.v2.network.ImageData; import com.theta360.sample.v2.view.ConfigurationDialog; //import com.theta360.sample.v2.view.LogView; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * 写真を球体として表示するアクティビティ */ public class GLPhotoActivity extends Activity implements ConfigurationDialog.DialogBtnListener { private static final String CAMERA_IP_ADDRESS = "CAMERA_IP_ADDRESS"; private static final String OBJECT_ID = "OBJECT_ID"; private static final String THUMBNAIL = "THUMBNAIL"; private GLPhotoView mGLPhotoView; private Photo mTexture = null; private LoadPhotoTask mLoadPhotoTask = null; private RotateInertia mRotateInertia = RotateInertia.INERTIA_0; public static final int REQUEST_REFRESH_LIST = 100; public static final int REQUEST_NOT_REFRESH_LIST = 101; /** * onCreate Method * @param savedInstanceState onCreate Status value */ @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_glphoto); Intent intent = getIntent(); String cameraIpAddress = intent.getStringExtra(CAMERA_IP_ADDRESS); String fileId = intent.getStringExtra(OBJECT_ID); byte[] byteThumbnail = intent.getByteArrayExtra(THUMBNAIL); ByteArrayInputStream inputStreamThumbnail = new ByteArrayInputStream(byteThumbnail); Drawable thumbnail = BitmapDrawable.createFromStream(inputStreamThumbnail, null); Photo _thumbnail = new Photo(((BitmapDrawable)thumbnail).getBitmap()); mGLPhotoView = (GLPhotoView) findViewById(R.id.photo_image); mGLPhotoView.setTexture(_thumbnail); mGLPhotoView.setmRotateInertia(mRotateInertia); mLoadPhotoTask = new LoadPhotoTask(cameraIpAddress, fileId); mLoadPhotoTask.execute(); } @Override protected void onDestroy() { if (mTexture != null) { mTexture.getPhoto().recycle(); } if (mLoadPhotoTask != null) { mLoadPhotoTask.cancel(true); } super.onDestroy(); } /** * onCreateOptionsMenu method * @param menu Menu initialization object * @return Menu display feasibility status value */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.configuration, menu); return true; } /** * onOptionsItemSelected Method * @param item Process menu * @return Menu process continuation feasibility value */ @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case R.id.configuration: FragmentManager mgr = getFragmentManager(); ConfigurationDialog.show(mgr, mRotateInertia); break; case R.id.ImageList2D: Intent _intent = getIntent(); String fileId = _intent.getStringExtra(OBJECT_ID); Intent intent = new Intent(getApplication(), ImageList2D_Activity.class); intent.putExtra(OBJECT_ID,fileId); startActivity(intent); break; default: break; } return true; } /** * onResume Method */ @Override protected void onResume() { super.onResume(); mGLPhotoView.onResume(); if (null != mTexture) { if (null != mGLPhotoView) { mGLPhotoView.setTexture(mTexture); } } } /** * onPause Method */ @Override protected void onPause() { this.mGLPhotoView.onPause(); super.onPause(); } /** * onDialogCommitClick Method * @param inertia selected inertia */ @Override public void onDialogCommitClick(RotateInertia inertia) { mRotateInertia = inertia; if (null != mGLPhotoView) { mGLPhotoView.setmRotateInertia(mRotateInertia); } } private class LoadPhotoTask extends AsyncTask<Void, Object, ImageData> { //private LogView logViewer; private ProgressBar progressBar; //private String cameraIpAddress; public String fileId; //private long fileSize; //private long receivedDataSize = 0; public LoadPhotoTask(String cameraIpAddress, String fileId) { // this.logViewer = (LogView) findViewById(R.id.photo_info); this.progressBar = (ProgressBar) findViewById(R.id.loading_photo_progress_bar); // this.cameraIpAddress = cameraIpAddress; this.fileId = fileId; } public String getfilename(){ Log.d("debug","start getfilename"); Log.d("debug",fileId); String[] list = fileId.split("/",0); String fname = list[list.length-1]; Log.d("debug",fname); return fname; } @Override protected void onPreExecute() { progressBar.setVisibility(View.VISIBLE); } @Override protected ImageData doInBackground(Void... params) { try { Log.d("debug","*** Start LoadPhotoTask ***"); String rawPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/image/image360/"; Log.d("debug",rawPath); String infoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/image/info/"; Log.d("debug",infoPath); String raw_fname = rawPath + "image360_" + getfilename(); Log.d("debug",raw_fname); String info_fname = infoPath + "info_"+ getfilename(); info_fname = info_fname.substring(0,info_fname.length()-3) + "txt"; Log.d("debug",info_fname); // byte[] mRowDataをファイル入力 ImageData resizedImageData = new ImageData(); resizedImageData.setRawData(convertFile(new File(raw_fname))); Log.d("debug","End setRawData"); // double pitch, roll, yaw をファイル入力 double[] pitch_roll_yaw = readFileTodoubles(info_fname); resizedImageData.setPitch(pitch_roll_yaw[0]); resizedImageData.setRoll(pitch_roll_yaw[1]); resizedImageData.setYaw(pitch_roll_yaw[2]); Log.d("debug",resizedImageData.getPitch().toString()); Log.d("debug",resizedImageData.getRoll().toString()); Log.d("debug",resizedImageData.getYaw().toString()); Log.d("debug","End setPitch,Roll,Yaw"); return resizedImageData; } catch (Throwable throwable) { String errorLog = Log.getStackTraceString(throwable); publishProgress(errorLog); return null; } } public byte[] convertFile(File file) { try (FileInputStream inputStream = new FileInputStream(file);) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while(true) { int len = inputStream.read(buffer); if(len < 0) { break; } bout.write(buffer, 0, len); } Log.d("debug","END OPEN FILE:"+file.getAbsolutePath()); return bout.toByteArray(); } catch (Exception e) { e.printStackTrace(); Log.d("debug","CANNOT OPEN FILE:"+file.getAbsolutePath()); } return null; } public double[] readFileTodoubles(String filePath) { FileReader fr = null; BufferedReader br = null; double[] res = new double[3]; try { fr = new FileReader(filePath); br = new BufferedReader(fr); String line; for (int i=0; i<3; i++) { if((line = br.readLine()) != null) { res[i] = Double.parseDouble(line); }else{ Log.d("debug","pitch,roll,yawファイルが壊れています。"); } } br.close(); fr.close(); return res; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Object... values) { for (Object param : values) { if (param instanceof Integer) { progressBar.setProgress((Integer) param); } else if (param instanceof String) { // logViewer.append((String) param); } } } @Override protected void onPostExecute(ImageData imageData) { if (imageData != null) { byte[] dataObject = imageData.getRawData(); if (dataObject == null) { // logViewer.append("failed to download image"); return; } Bitmap __bitmap = BitmapFactory.decodeByteArray(dataObject, 0, dataObject.length); progressBar.setVisibility(View.GONE); Double yaw = imageData.getYaw(); Double pitch = imageData.getPitch(); Double roll = imageData.getRoll(); // logViewer.append("<Angle: yaw=" + yaw + ", pitch=" + pitch + ", roll=" + roll + ">"); mTexture = new Photo(__bitmap, yaw, pitch, roll); if (null != mGLPhotoView) { mGLPhotoView.setTexture(mTexture); } } else { // logViewer.append("failed to download image"); } } } /** * Activity call method * * @param activity Call source activity * @param cameraIpAddress IP address for camera device * @param fileId Photo object identifier * @param thumbnail Thumbnail * @param refreshAfterClose true is to refresh list after closing this activity, otherwise is not to refresh */ public static void startActivityForResult(Activity activity, String cameraIpAddress, String fileId, byte[] thumbnail, boolean refreshAfterClose) { int requestCode; if (refreshAfterClose) { requestCode = REQUEST_REFRESH_LIST; // 画像撮影による遷移 } else { requestCode = REQUEST_NOT_REFRESH_LIST; // List選択による遷移 } Intent intent = new Intent(activity, GLPhotoActivity.class); intent.putExtra(CAMERA_IP_ADDRESS, cameraIpAddress); intent.putExtra(OBJECT_ID, fileId); intent.putExtra(THUMBNAIL, thumbnail); activity.startActivityForResult(intent, requestCode); } }
package com.fundwit.sys.shikra.database; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.datasource.init.ScriptException; import org.springframework.jdbc.datasource.init.UncategorizedScriptException; import org.springframework.util.Assert; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; public class DatabaseUtils { private static final Logger logger = LoggerFactory.getLogger(MysqlDatabaseManagerImpl.class); public static void execute(String statement, Connection connection) { try { Statement stmt = connection.createStatement(); try { stmt.execute(statement); logger.info("[sql] execute statement: {}", statement); int rowsAffected = stmt.getUpdateCount(); logger.info("[sql]affected rows: {}", rowsAffected); SQLWarning warningToLog = stmt.getWarnings(); while (warningToLog != null) { logger.warn("[sql] SQLWarning ignored: SQL state '" + warningToLog.getSQLState() + "', error code '" + warningToLog.getErrorCode() + "', message [" + warningToLog.getMessage() + "]"); warningToLog = warningToLog.getNextWarning(); } } finally { try { stmt.close(); } catch (Throwable ex) { logger.warn("[sql] Could not close JDBC Statement", ex); } } }catch (SQLException e){ throw new RuntimeException(e); } } public static void execute(String statement, DataSource dataSource) throws DataAccessException { Assert.notNull(dataSource, "DataSource must not be null"); try { Connection connection = DataSourceUtils.getConnection(dataSource); try { execute(statement, connection); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } } catch (Throwable ex) { if (ex instanceof ScriptException) { throw (ScriptException) ex; } throw new UncategorizedScriptException("Failed to execute database script", ex); } } }
package com.example.useractivity.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.useractivity.R; import com.example.useractivity.model.Credential; import com.example.useractivity.network.SendLoginDataService; import com.example.useractivity.network.RetrofitInstance; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private EditText email_login,pass_login; private Button submit_login; private TextView signup_login,login_reset_pass; private final String unfoundEmail= "Email was not found! Try sign-up"; private final String incorrectPassword= "Login credentials are wrong. Please try again!"; SendLoginDataService service; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setting(); submit_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = email_login.getText().toString().trim(); String pass = pass_login.getText().toString().trim(); if(email.isEmpty()|| pass.isEmpty()) { Toast.makeText(MainActivity.this, "All fields must be filled", Toast.LENGTH_SHORT).show(); } else { postData(email,pass); } } }); signup_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "sign up was pressed", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, SignUp.class); startActivity(intent); } }); login_reset_pass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "reset was pressed", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(MainActivity.this, ResetPassword.class); startActivity(intent); } }); } void setting() { email_login = findViewById(R.id.email_login); pass_login = findViewById(R.id.pass_login); submit_login = findViewById(R.id.submit_login); signup_login = findViewById(R.id.signup_login); login_reset_pass = findViewById(R.id.login_reset_pass); } void postData(String email, final String pass) { service = RetrofitInstance.getRetrofitInstance().create(SendLoginDataService.class); Call<Credential> call = service.sendLogInAData(email,pass); call.enqueue(new Callback<Credential>() { @Override public void onResponse(Call<Credential> call, Response<Credential> response) { Log.d("onResponse", "" + response.body().getErrorMessage()); if (response.isSuccessful()) { Credential credential = response.body(); if((credential.getErrorResult()) && (credential.getErrorMessage().equals(unfoundEmail))) { unfoundEmail(); } else if((credential.getErrorResult()) && (credential.getErrorMessage().equals(incorrectPassword))) { wrongPassword(); } else { loggedIn(); } // } else { Toast.makeText(MainActivity.this, "Unable to connect with Server", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Credential> call, Throwable t) { } }); } void wrongPassword() { Toast.makeText(MainActivity.this, "Wrong Password", Toast.LENGTH_SHORT).show(); } void unfoundEmail() { Toast.makeText(MainActivity.this, "Email is not in DB", Toast.LENGTH_SHORT).show(); } void loggedIn() { Toast.makeText(MainActivity.this, "You are logged in", Toast.LENGTH_SHORT).show(); } }
package webservices; import entity.Article; import entity.Category; import org.codehaus.jackson.map.ObjectMapper; import service.Service; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.*; import javax.ws.rs.core.Context; import java.io.IOException; import java.util.Collection; /** * Created by F on 11/07/2015. */ @RequestScoped @Named @Path("/category") @Produces("application/json; charset=UTF-8") public class CategoryService { @Inject Service service; @GET @Path("get/{categoryId}") public Category getCategory(@PathParam("categoryId") final Integer categoryId) { return service.find(Category.class, categoryId); } @POST @Path("/add") @Consumes("application/json") public Category addCategory(String value) throws IOException { Category category = new ObjectMapper().readValue(value, Category.class); return service.create(category); } @POST @Path("/update") @Consumes("application/json") public Category updateCategory(String value) throws IOException { Category category = new ObjectMapper().readValue(value, Category.class); return service.update(category); } @POST @Path("/delete") @Consumes("application/json") public String deleteCategory(String value) throws IOException { Category category = new ObjectMapper().readValue(value, Category.class); service.delete(category); return "OK"; } @GET @Path("/all") public Collection<Category> getAllCategories(@Context final HttpServletRequest request) { return service.findAll(Category.class); } }
package com.porfolio.service.controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin @RequestMapping(path = "/content") public class ContentApi { }
package com.example.world.repository.orm; import static java.util.Optional.ofNullable; import java.util.Collection; import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.example.world.entity.Country; import com.example.world.repository.CountryRepository; /** * * @author Binnur Kurt <binnur.kurt@gmail.com> */ @Repository public class JpaCountryRepository implements CountryRepository { @PersistenceContext(unitName="worldPU") private EntityManager em; public Optional<Country> findOne(String code) { return ofNullable(em.find(Country.class, code)); } public Collection<Country> findAll() { return em.createNamedQuery("Country.findAll", Country.class).getResultList(); } @Transactional public Country add(Country country) { String code = country.getKod(); Optional<Country> found = findOne(code); if (found.isPresent()) throw new IllegalArgumentException("Country exists!"); em.persist(country); return country; } @Transactional(propagation = Propagation.REQUIRES_NEW) public Country update(Country country) { String code = country.getKod(); Optional<Country> found = findOne(code); if (found.isPresent()) { Country c = found.get(); c.setPopulation(country.getPopulation()); c.setSurface(country.getSurface()); em.merge(c); return c; } throw new IllegalArgumentException("Country does not exist!"); } @Transactional(propagation = Propagation.REQUIRED) public Optional<Country> remove(String key) { return Optional.empty(); } public Collection<Country> getByContinent(String continent) { return em.createNamedQuery("Country.findByContinent", Country.class).setParameter("continent", continent) .getResultList(); } @SuppressWarnings("unchecked") public Collection<String> getContinents() { return em.createNativeQuery("select distinct continent from country").getResultList(); } }
package io.zipcoder.casino.player; import io.zipcoder.casino.Handler; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; public class PlayerTest { @Test public void getName() { Player player = new Player("bob" , 100.0); Assert.assertEquals("bob", player.getName()); } @Test public void setName() { Player player = new Player(); player.setName("bob"); Assert.assertEquals("bob", player.getName()); } @Test public void getAccount() { Player player = new Player("bob", 10000.0); Double expected = 10000.0; Double actual = player.getAccount(); Assert.assertEquals(expected, actual); } @Test public void setAccount() { Player player = new Player(); player.setAccount(100.0); Double expected = 100.0; Double actual = player.getAccount(); Assert.assertEquals(expected, actual); } }
package com.example.nhom11.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.example.nhom11.dao.OrderDAOTuan; import com.example.nhom11.dao.impl.OrderDAOTuanImpl; import com.example.nhom11.model.Order; import com.example.nhom11.model.PhoneSelling; @WebServlet(urlPatterns = "/order-detail") public class OrderDetailController extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long orderId = Long.parseLong(req.getParameter("id")); OrderDAOTuan od = new OrderDAOTuanImpl(); Order order = od.viewDetail(orderId); float price = 0; for(PhoneSelling ps: order.getCart().getPhones()) { price += ps.getQuantity()*ps.getPhone().getPrice(); } if(order.getShipment()!=null) { price +=order.getShipment().getPrice(); } order.setPrice(price); req.setAttribute("order", order); req.getRequestDispatcher("order-detail.jsp").forward(req, resp); } }
package com.za.finger; import java.io.DataOutputStream; /** * @author :Reginer in 2017/11/27 14:22. * 联系方式:QQ:282921012 * 功能描述:指纹操作 */ public class FingerOperation { private static final int DEV_ADDRESS = 0xffffffff; private static final int IMG_SIZE = 0; /** * 打开指纹设备 * * @param a6 ZAandroid * @return 打开结果 */ public static boolean openDev(ZAandroid a6) { byte[] pPassword = new byte[4]; int status; checkEuq(); status = a6.ZAZOpenDeviceEx(-1, 4, 12, 6, 0, 0); if (status == 1 && a6.ZAZVfyPwd(DEV_ADDRESS, pPassword) == 0) { status = 1; } else { status = 0; } a6.ZAZSetImageSize(IMG_SIZE); if (status == 1) { return true; } else { ZA_finger power = new ZA_finger(); power.finger_power_off(); return false; } } /** * 关闭指纹设备 */ public static void closeDev() { ZA_finger power = new ZA_finger(); power.finger_power_off(); } private static void checkEuq() { Process process; DataOutputStream os; String path = "/dev/bus/usb/00*/*"; String command = "chmod 777 " + path; try { process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(command + "\n"); os.writeBytes("exit\n"); os.flush(); process.waitFor(); } catch (Exception e) { } } }
package com.tencent.mm.plugin.emoji.ui; import com.tencent.mm.R; import com.tencent.mm.ui.base.l; import com.tencent.mm.ui.base.n.c; import com.tencent.tmassistantsdk.logreport.BaseReportManager; class EmojiStoreDetailUI$13 implements c { final /* synthetic */ EmojiStoreDetailUI inz; EmojiStoreDetailUI$13(EmojiStoreDetailUI emojiStoreDetailUI) { this.inz = emojiStoreDetailUI; } public final void a(l lVar) { lVar.a(1001, this.inz.getString(R.l.wv_alert_share_to_friend), R.k.bottomsheet_icon_transmit); lVar.a((int) BaseReportManager.MAX_READ_COUNT, this.inz.getString(R.l.wv_alert_share_timeline), R.k.bottomsheet_icon_moment); } }
package com.ireslab.sendx.electra.service; import java.util.Date; import com.ireslab.sendx.electra.dto.ClientTokenConfigurationDto; import com.ireslab.sendx.electra.dto.VerifyRequest; import com.ireslab.sendx.electra.dto.VerifyResponse; import com.ireslab.sendx.electra.entity.Client; import com.ireslab.sendx.electra.entity.ClientConfiguration; import com.ireslab.sendx.electra.entity.ClientUser; import com.ireslab.sendx.electra.entity.TransactionDetail; import com.ireslab.sendx.electra.model.AccountDetailsResponse; import com.ireslab.sendx.electra.model.BankDetailResponse; import com.ireslab.sendx.electra.model.BankDetailsRequest; import com.ireslab.sendx.electra.model.ClentAgentInvitationRequest; import com.ireslab.sendx.electra.model.ClentAgentInvitationResponse; import com.ireslab.sendx.electra.model.ClientInfoRequest; import com.ireslab.sendx.electra.model.ClientInfoResponse; import com.ireslab.sendx.electra.model.CountryListResponse; import com.ireslab.sendx.electra.model.ExchangeRequest; import com.ireslab.sendx.electra.model.ExchangeResponse; import com.ireslab.sendx.electra.model.NotificationRequest; import com.ireslab.sendx.electra.model.NotificationResponse; import com.ireslab.sendx.electra.model.PaymentRequest; import com.ireslab.sendx.electra.model.PaymentResponse; import com.ireslab.sendx.electra.model.ProductAvailabilityRequest; import com.ireslab.sendx.electra.model.ProductAvailabilityResponse; import com.ireslab.sendx.electra.model.ProductGroupResponse; import com.ireslab.sendx.electra.model.ProductRequest; import com.ireslab.sendx.electra.model.ProductResponse; import com.ireslab.sendx.electra.model.SaveProductRequest; import com.ireslab.sendx.electra.model.SaveProductResponse; import com.ireslab.sendx.electra.model.SendxElectraRequest; import com.ireslab.sendx.electra.model.SendxElectraResponse; import com.ireslab.sendx.electra.model.TokenTransferRequest; import com.ireslab.sendx.electra.model.UserProfileResponse; import com.ireslab.sendx.electra.utils.ClientConfigurations; import com.ireslab.sendx.electra.utils.TokenActivity; import com.ireslab.sendx.electra.utils.TokenOperation; /** * @author iRESlab * */ public interface CommonService { /** * @param clientCorrelationId * @return */ public Client getClientDetailsByCorrelationId(String clientCorrelationId); /** * @param clientCorrelationId * @param configCode * @return */ public ClientConfiguration getClientConfigurationByClientIdAndConfigCode(String clientCorrelationId, ClientConfigurations configCode); /** * @param clientId * @param tokenId * @param isLoadInitialAsset * @return */ public ClientTokenConfigurationDto getClientTokenConfigurationByClientIdAndTokenIdAndIsEnabled(Integer clientId, Integer tokenId, boolean isLoadInitialAsset); /** * @param clientCorrelationId * @return */ public ClientUser getClientUserByCorrelationId(String clientCorrelationId); /** * @param clientUser */ public void updateClientUser(ClientUser clientUser); // This method is to get account details. public AccountDetailsResponse getAccountDetails(String account); public TransactionDetail saveTransactionDetails(TokenOperation operation, TokenActivity type, String stellarRequest, String stellarResponse, String sourceAccountName, boolean isSourceAccountUser, String sourceCorrelationId, String destinationAccountName, boolean isDestinationAccountUser, String destinationCorrelationId, short status, String tnxData, String assetCode, String tnxHash, String transactionXdr, Date transactionDate, Date modifiedDate , String transactionPurpose, boolean isFee, boolean offline); public void transferToClientAccount(TokenTransferRequest tokenTransferRequest); public ClentAgentInvitationResponse saveClientInvitationDetails(ClentAgentInvitationRequest clentAgentInvitationRequest); public CountryListResponse getCountryList(String clientCorrelationId); public ClientInfoResponse getClientDetailsByCorrelationId(ClientInfoRequest clientInfoRequest); public ProductResponse getProductList(ProductRequest productRequest); public ProductGroupResponse getProductGroupList(); public SaveProductResponse saveProduct(SaveProductRequest productRequest); public SaveProductResponse editProduct(SaveProductRequest productRequest); public SaveProductResponse deleteProduct(String productCode); public PaymentResponse makePayment(PaymentRequest paymentRequest); public ClientInfoResponse getclientInformation(ClientInfoRequest clientInfoRequest); public PaymentResponse savePurchasedProduct(PaymentRequest paymentRequest); PaymentResponse transferPaymentToClientAccount(TokenTransferRequest tokenTransferRequest); public ProductAvailabilityResponse checkProductAvailability(ProductAvailabilityRequest productAvailabilityRequest); //private VerifyResponse truliooEkycEkyb(VerifyRequest verifyRequest); public VerifyResponse truliooEkycEkyb(VerifyRequest verifyrequest, String username, String password); public BankDetailResponse saveBankDetails(BankDetailsRequest bankDetailsRequest); public void transferFeeToMasterAccount(TokenTransferRequest tokenTransferRequest); public BankDetailResponse getBankDetailsByClientEmail(BankDetailsRequest bankDetailsRequest); public UserProfileResponse getClientOrUserDetailsByUniqueCode(String uniqueCode); public NotificationResponse saveNotification(NotificationRequest notificationRequest); public SendxElectraResponse updateNotification(SendxElectraRequest sendxElectraRequest); public SendxElectraResponse getAllNotification(String mobileNumber); public SendxElectraResponse updateDeviceSpecificParameter(SendxElectraRequest sendxElectraRequest); public PaymentResponse makeOfflinePayment(TokenTransferRequest tokenTransferRequest); public ProductResponse getProductListForConsole(ProductRequest productRequest); public PaymentResponse updateInvoicedProduct(PaymentRequest paymentRequest); public NotificationResponse deleteNotification(NotificationRequest notificationRequest); public ExchangeResponse getExchangeRate(ExchangeRequest exchangeRequest); public UserProfileResponse getClientOrUserDetailsByMobileNumber(String countryDailCode, String mobileNumber); public SendxElectraResponse getAllSettlementReports(); public SendxElectraResponse updateSettlementReport(SendxElectraRequest sendxElectraRequest); public SendxElectraResponse getAllSettlementReports(String correlationId); }
/* * 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 interfaz; /** * * @author ESTUDIANTES */ public interface ReinoAnimalInterface { public final String ALGO ="Pertenecen al Reino Animal"; // final es una constante que no se puede modificar es necesario que este en mayuscula (ALGO) /** Acceder a los metodos segun la lista indicada */ public String alimentarse(); /** Metodo */ public String dientes(); /** Metodo */ }
package othello; import othello.Miscellaneous.OthelloFun; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import othello.ViewElements.OthelloFieldLabel; import othello.ViewElements.OthelloInfoPanel; import othello.Miscellaneous.OthelloLocation; /** * Die Schnittstelle zwischen der OthelloView.java (Oberfläche) und * OthelloModel.java (Spiellogik). Im Wesentlichen werden die aus der View * kommenden Actions an die Spiellogik weitergereicht. Andererseits werden die * View Elemente anhand der von der Spiellogik entsendeten Notifications * angepasst. * * @author Pascal Weiß (s0544768) * @version 1.0 */ public class OthelloController implements Observer, ActionListener, MouseListener { private static final boolean debug = false; private final OthelloView view; private final OthelloModel model; private final OthelloFun seqFun; private final ArrayList<OthelloLocation> hintBuffer; /** * Erzeugung des Controllers bei gleichzeitiger zuweisung zu View und Model, * @param othelloView Die View welche durch den OthelloController * gesteuert werden soll. * @param othelloModel Die Spiellogik welche verwendet werden soll. */ OthelloController(OthelloView othelloView, OthelloModel othelloModel) { hintBuffer = new ArrayList<>(); view = othelloView; // Verschiedene Maßnahmen zur Vorbereitung der View. initView(); model = othelloModel; model.addObserver(this); seqFun = new OthelloFun(); seqFun.addObserver(this); model.clearBoard(); // Hier wird die Startsequenz abgespielt. seqFun.sequence1(view, 200); // Dem Model wird mitgeteilt, dass ein neues Spiel beginnen soll. model.newGame(); view.gameStatusLabel.setText("Tokens left:"); } /** * View wird vorbereitet. */ private void initView() { view.addBoard(OthelloModel.defaultBoardSize); addInfoListener(); addBoardListener(); view.repaint(); } /** * Fügt den UI Elementen der View sich selbst als Listener hinzu. */ private void addInfoListener() { view.newGameButton.addActionListener(this); view.boardSizeBox.addActionListener(this); } /** * Fügt jedem einzelnen Feld von OthelloboardPanel.java sich selbst als * Listener hinzu. */ private void addBoardListener() { for (int row = 0; row < view.board.length; row++) { for (int column = 0; column < view.board[0].length; column++) { view.board[row][column].addMouseListener(this); } } } /* __ _____ _______ __ ____ ___ _ _ _____ ____ ___ _ \ \ / /_ _| ____\ \ / / / ___/ _ \| \ | |_ _| _ \ / _ \| | \ \ / / | || _| \ \ /\ / / | | | | | | \| | | | | |_) | | | | | \ V / | || |___ \ V V / | |__| |_| | |\ | | | | _ <| |_| | |___ \_/ |___|_____| \_/\_/ \____\___/|_| \_| |_| |_| \_\\___/|_____| */ private void clearBoard() { view.removeBoard(); view.addBoard(model.getBoardSize()); view.repaint(); addBoardListener(); } /** * Anweisung, dass neu belegte Felder im Model nun auch auf der View * angezeigt werden sollen. */ private void addNewToken() { for (int i = 0; i < model.getNewToken().size(); i++) { int row = model.getNewToken().get(i).row; int column = model.getNewToken().get(i).column; view.board[row][column].setFieldIcon(tokenIMGForCurrentPlayer()); } view.repaint(); } /** * Die Felder, welche zuvor in der View einen Hinweis anzeigten, werden nun * wieder zurückgesetzt, sofern sie immernoch nicht von einem Spielstein * belegt sind. */ private void removeOldHints() { for (Iterator<OthelloLocation> it = model.getNewHints().iterator(); it.hasNext();) { OthelloLocation hint = it.next(); if (model.getFieldStatus(hint.row, hint.column) == OthelloModel.EMPTY) { view.board[hint.row][hint.column].setFieldIcon(OthelloFieldLabel.EMPTY); } } } private int tokenIMGForCurrentPlayer() { if (model.getCurrentPlayer() == OthelloModel.PLAYER_1) { return OthelloView.RED_TOKEN; } else if (model.getCurrentPlayer() == OthelloModel.PLAYER_2) { return OthelloView.GREEN_TOKEN; } else { return -1; } } private int hintIMGForNextPlayer() { if (model.getNextPlayer() == OthelloModel.PLAYER_1) { return OthelloView.RED_HINT; } else if (model.getNextPlayer() == OthelloModel.PLAYER_2) { return OthelloView.GREEN_HINT; } else { return -1; } } private int gameSizeForBoxIndex(int boxIndex) { switch (boxIndex) { case 0: return 6; case 1: return 8; case 2: return 10; default: return -1; } } /* __ __ ___ ____ _____ _ _ ___ ____ _____ _____ _ _ _____ ____ | \/ |/ _ \| _ \| ____| | | | |_ _/ ___|_ _| ____| \ | | ____| _ \ | |\/| | | | | | | | _| | | | | | |\___ \ | | | _| | \| | _| | |_) | | | | | |_| | |_| | |___| |___ | |___ | | ___) || | | |___| |\ | |___| _ < |_| |_|\___/|____/|_____|_____| |_____|___|____/ |_| |_____|_| \_|_____|_| \_\ */ /** * Die Schnittstelle zwischen Controller und Model (OthelloModel.java). Hier * werden die Notifications des Models angenommen, anhand derer verschiedene * Befehle zur Anpassung der View vorgenommen werden können * @param o Das Model selbst. * @param arg die "Nachricht" */ @Override public void update(Observable o, Object arg) { // Neue Hinweise sollen angezeigt werden. if (arg == OthelloModel.POSSIBLE_MOVES) { for (Iterator<OthelloLocation> it = model.getNewHints().iterator(); it.hasNext();) { OthelloLocation hint = it.next(); view.board[hint.row][hint.column].setFieldIcon(hintIMGForNextPlayer()); } view.repaint(); // Alte Hinweise sollen entfernt werden. } else if (arg == OthelloModel.HINTS_REMOVED) { removeOldHints(); // Neuer Spielstein soll angezeigt werden. } else if (arg == OthelloModel.NEW_TOKEN) { addNewToken(); view.tokensLeftLabel.setText(String.valueOf(model.getTokensLeft())); view.player1ScoreLabel.setText(String.valueOf(model.getPlayerOneCount())); view.player2ScoreLabel.setText(String.valueOf(model.getPlayerTwoCount())); // Ein leeres Spielbrett soll angezeigt werden. } else if (arg == OthelloModel.NEW_BOARD) { hintBuffer.clear(); clearBoard(); // Der andere Spieler ist dran. } else if (arg == OthelloModel.PLAYER_CHANGED) { if (model.getCurrentPlayer() == OthelloModel.PLAYER_1) { view.player1StatusLabel.setVisible(true); view.player2StatusLabel.setVisible(false); } else { view.player1StatusLabel.setVisible(false); view.player2StatusLabel.setVisible(true); } // Ein Spieler hat gewonnen. } else if (arg == OthelloModel.OVER_AND_OUT) { if (model.whoIsBetter() == OthelloModel.PLAYER_1) { view.gameStatusLabel.setText("First player wins!"); } else if (model.whoIsBetter() == OthelloModel.PLAYER_2) { view.gameStatusLabel.setText("Second player wins!"); } else { view.gameStatusLabel.setText("Draw!"); } } } /* __ _____ _______ __ _ ___ ____ _____ _____ _ _ _____ ____ \ \ / /_ _| ____\ \ / / | | |_ _/ ___|_ _| ____| \ | | ____| _ \ \ \ / / | || _| \ \ /\ / / | | | |\___ \ | | | _| | \| | _| | |_) | \ V / | || |___ \ V V / | |___ | | ___) || | | |___| |\ | |___| _ < \_/ |___|_____| \_/\_/ |_____|___|____/ |_| |_____|_| \_|_____|_| \_\ */ /** * Schnittstelle zwischen dem Spielbrett (OthelloBoardPanel.java) und dem * Controller. Hier wird dem Controller mitgeteilt, welches Feld angeklickt * wurde. * @param e Das Event Objekt, welches das angeklickte OthelloField enthält. */ @Override public void mouseClicked(MouseEvent e) { OthelloFieldLabel field = (OthelloFieldLabel) e.getComponent(); if (debug) { model.debugMove(field.getCoordinate().row, field.getCoordinate().column); } else { model.newMove(field.getCoordinate().row, field.getCoordinate().column); } } /** * Unbenutzt. Muss aber implementiert sein. Sonst Fehler. * @param e */ @Override public void mousePressed(MouseEvent e) { } /** * Unbenutzt. Muss aber implementiert sein. Sonst Fehler. * @param e */ @Override public void mouseReleased(MouseEvent e) { } /** * Unbenutzt. Muss aber implementiert sein. Sonst Fehler. * @param e */ @Override public void mouseEntered(MouseEvent e) { } /** * Unbenutzt. Muss aber implementiert sein. Sonst Fehler. * @param e */ @Override public void mouseExited(MouseEvent e) { } /** * Schnittstelle zwischen Controller und den UI Elementen. Wird aufgerufen, * wenn der "New Game" Button geklickt wurde. * @param e ActionEvent mit ActionCommand (NEW_GAME) */ @Override public void actionPerformed(ActionEvent e) { /*Da nur ein Button verwendet wird, könnte auf den ActionCommand verzichtet werden. Allerdings ist so gewährleistet, dass in zukünftigen Versionen weitere Buttons verwendet werden können.) */ switch (e.getActionCommand()) { case OthelloInfoPanel.NEW_GAME: int boardSize = gameSizeForBoxIndex(view.boardSizeBox.getSelectedIndex()); model.newGame(boardSize, debug); if (!"Tokens left:".equals(view.gameStatusLabel.getText())) { view.gameStatusLabel.setText("Tokens left:"); } break; } } }
package com.redink.app.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "author") public class Authors { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int authorId; private String name; private Posts post; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAuthorId() { return authorId; } public void setAuthorId(int authorId) { this.authorId = authorId; } public Posts getPost() { return post; } public void setPost(Posts post) { this.post = post; } }
package com.pas.mall.controller; import com.pas.mall.entity.RespBean; import com.pas.mall.pojo.TbGoods; import com.pas.mall.pojo.TbItemCat; import com.pas.mall.pojogroup.Goods; import com.pas.mall.service.GoodsService; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/goods-ms") public class GoodsController { @Autowired private GoodsService goodsService; @GetMapping("/findAll") public List<TbGoods> findAll(){ return goodsService.findAll(); } @PostMapping("/add") public void addGoods(@RequestBody Goods goods){ goodsService.add(goods); } @GetMapping("/findByParentId/{parentId}") public List<TbItemCat> findByParentId(@PathVariable Long parentId){ System.out.println(parentId); return goodsService.findByCateGoryId(parentId); } @GetMapping("/findTemplateId/{id}") public TbItemCat findTemplateId(@PathVariable Long id){ return goodsService.findTemplateId(id); } @ApiOperation("查询所有ItemCat") @GetMapping("/findItemCat") public List<TbItemCat> findItemCat(){ return goodsService.findItemCat(); } @ApiOperation("根据id删除商品") @GetMapping("/delete") public RespBean delete(Long[] ids){ goodsService.delete(ids); return RespBean.ok("删除成功"); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bd_avanzada; import java.awt.Color; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; /** * * @author Usuario */ public class recuperar_contra extends javax.swing.JFrame { ManejadorSQL m; Archivos a; String[] lineas; /** * Creates new form recuperar_contra */ public recuperar_contra() { try { initComponents(); this.setLocationRelativeTo(null); acept.setVisible(false); jLabel2.setVisible(false); jButton2.setVisible(false); a = new Archivos(); lineas = new String[9]; lineas = a.Leer(); m = new ManejadorSQL(lineas[2], lineas[1], lineas[3], lineas[4], lineas[5], lineas[7], lineas[6]); m.setLineas(lineas); rellenar_pregunta(); } catch (Exception ex) { Logger.getLogger(recuperar_contra.class.getName()).log(Level.SEVERE, null, ex); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); selec = new javax.swing.JComboBox(); acep = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); acept = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); most_e = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Recuperar Contraseña"); selec.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N selec.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione", "Mejor Amigo de la Infancia", "Nombre de tu Mascota", "Comida Favorita", "Genero Musical Favorito", "Color Favorito", "Nombre de tu Madre" })); selec.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selecActionPerformed(evt); } }); jButton1.setText("Confirmar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N jLabel2.setText("Codigo Alternativo"); acept.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { aceptActionPerformed(evt); } }); jButton2.setText("Confirmar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); most_e.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(selec, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 239, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jPanel1Layout.createSequentialGroup() .add(11, 11, 11) .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 154, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 73, Short.MAX_VALUE) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, acep, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 214, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(org.jdesktop.layout.GroupLayout.TRAILING, acept, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 213, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(61, 61, 61)) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup() .add(0, 0, Short.MAX_VALUE) .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(115, 115, 115)))) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup() .add(0, 0, Short.MAX_VALUE) .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 83, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(109, 109, 109)) .add(jPanel1Layout.createSequentialGroup() .add(159, 159, 159) .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 263, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .add(jPanel1Layout.createSequentialGroup() .add(most_e, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(30, 30, 30) .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 32, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(18, 18, 18) .add(most_e, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(32, 32, 32) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(selec, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(acep, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(39, 39, 39) .add(jButton1) .add(35, 35, 35) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jLabel2) .add(acept, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(32, 32, 32) .add(jButton2) .addContainerGap(69, Short.MAX_VALUE)) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void aceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptActionPerformed // TODO add your handling code here: }//GEN-LAST:event_aceptActionPerformed public void rellenar_pregunta(){ try{ DefaultComboBoxModel modeloCombo = new DefaultComboBoxModel(); //DriverManager.getConnection("jdbc:postgresql://localhost/dbsitxian", "importadoraxian", "sitvenpfi"); ResultSet rs =m.Select("pregunta", "id_pregunta,tx_pregunta"); selec.removeAllItems(); modeloCombo.addElement("Seleccione"); while (rs.next()) { modeloCombo.addElement(rs.getObject("tx_pregunta")); } rs.close(); selec.setModel(modeloCombo); } catch (SQLException ex) { Logger.getLogger(recuperar_contra.class.getName()).log(Level.SEVERE, null, ex); } } private void selecActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selecActionPerformed // TODO add your handling code here: }//GEN-LAST:event_selecActionPerformed public void mostrar_e(String e){ most_e.setAlignmentY(CENTER_ALIGNMENT); most_e.setHorizontalAlignment(WIDTH / 2); most_e.setAlignmentX(CENTER_ALIGNMENT); most_e.setText(e); most_e.setForeground(Color.red); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String most,ace,ac; most=selec.getSelectedItem().toString(); ace=acep.getText(); ac=acept.getText(); if(ace.equals("")){ mostrar_e("Debe llenar El campo Respuesta"); } else{ } // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(recuperar_contra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(recuperar_contra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(recuperar_contra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(recuperar_contra.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new recuperar_contra().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField acep; private javax.swing.JTextField acept; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JLabel most_e; private javax.swing.JComboBox selec; // End of variables declaration//GEN-END:variables }
package com.xzj.lerning.controller; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @Author: XuZhiJun * @Description: * @Date: Created in 10:40 2019/5/15 */ @RestController public class CurrencyTest { @RequestMapping("currencyTest") public String test(){ RestTemplate restTemplate = new RestTemplate(); ThreadPoolExecutor service = new ThreadPoolExecutor(10, 100, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); Runnable thread=new Runnable(){ @Override public void run() { //1.返回responseEntity ResponseEntity<String> response = restTemplate.getForEntity("http://192.168.5.151:10001/role/test", String.class); } }; for (int i = 0; i <30 ; i++) { service.execute(thread); } return "ok"; } public static void main(String[] args) { System.out.println((double)1/1000/1000); } }
package uk.gov.glasgow.msglasgow; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; //AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> public class LoginTask extends AsyncTask<String, Integer, String> { private String session_token; private String username, password, api_key; protected String doInBackground(String... params) { // TypeOfVarArgParams // TODO String url = "http://ec2-54-201-229-55.us-west-2.compute.amazonaws.com:8000/user"; HttpClient httpclient = new DefaultHttpClient(); HttpPut httpput = new HttpPut(url); StringBuilder sb = null; try { httpput.setEntity(new UrlEncodedFormEntity(Util.authenticate( username, password, api_key))); HttpResponse response = httpclient.execute(httpput); HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream, "UTF-8"), 8); sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } inputStream.close(); JSONObject answer = new JSONObject(toString()); Session.logIn(answer.getString("session_token"), true); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return session_token; } @Override protected void onPostExecute(String response) { // TODO do something with response } @Override protected void onCancelled() { } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Integer... progress) { } public String getSession_token() { return this.session_token; } public void fillFields(String session_token, String username, String password, String api_key) { this.session_token = session_token; this.username = username; this.password = password; this.api_key = api_key; } }
package com.yc.biz; import java.util.List; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import com.yc.bean.FirstType; import com.yc.bean.SecondType; import com.yc.bean.ThirdType; /** * * @author adeline * @date 2018年8月27日 * @TODO */ @Repository public interface ThirdTypeBiz { /** * 查找所有三级表 * @return */ public List<ThirdType> findAllThirdType(); /** * 根据id查找二级表 * @param typeid * @return */ public ThirdType findThirdTypeById(Integer thirdtype_id); /** * 通过二级id查找 * @Description */ public List<ThirdType> findThirdTypeBySecondTypeId(Integer secondtype_id); /** * 添加二级表信息 * @Description */ public int addThirdtype(ThirdType thirdType); /** * 根据id删除二级表 * @Description */ public int delThirdType(Integer thirdtype_id); /** * 根据id更新二级表 * @Description */ public int updateThirdType(ThirdType thirdType); }
package day38_methods; public class ArrayUtilsTest { public static void main(String[] args) { int[] nums = {5, 23, 1, 543, 90}; ArrayUtils.printArray(nums); ArrayUtils.printArray(new int[]{23, 45, 569, 78, 98}); System.out.println("sum = " + ArrayUtils.sum(nums)); System.out.println("sum = " + ArrayUtils.sum(new int[]{23, 45, 569, 78, 98})); int[] nums2 = {4, 8, 5, 62}; System.out.println("found = " +ArrayUtils.contains(nums2,5)); System.out.println("10 - found = " +ArrayUtils.contains(nums2,10)); // int num = 5; // // boolean found = false; // for (int each : nums2) { // if (each == num) { // found = true; // break; // } // } // System.out.println(); } }
package edunova; import javax.swing.JOptionPane; public class Zadatak3 { //Program prima broj i ispisuje taj broj uvećan za 10 public static void main(String[] args) { int i = Integer.parseInt(JOptionPane.showInputDialog("unesite broj:")); System.out.println(i + 10); } }
/* This file was generated by SableCC (http://www.sablecc.org/). */ package node; import analysis.*; @SuppressWarnings("nls") public final class AFuncFunc extends PFunc { private TCall _call_; private TId _id_; private TLPar _lPar_; private PFuncPara _funcPara_; public AFuncFunc() { // Constructor } public AFuncFunc( @SuppressWarnings("hiding") TCall _call_, @SuppressWarnings("hiding") TId _id_, @SuppressWarnings("hiding") TLPar _lPar_, @SuppressWarnings("hiding") PFuncPara _funcPara_) { // Constructor setCall(_call_); setId(_id_); setLPar(_lPar_); setFuncPara(_funcPara_); } @Override public Object clone() { return new AFuncFunc( cloneNode(this._call_), cloneNode(this._id_), cloneNode(this._lPar_), cloneNode(this._funcPara_)); } @Override public void apply(Switch sw) { ((Analysis) sw).caseAFuncFunc(this); } public TCall getCall() { return this._call_; } public void setCall(TCall node) { if(this._call_ != null) { this._call_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._call_ = node; } public TId getId() { return this._id_; } public void setId(TId node) { if(this._id_ != null) { this._id_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._id_ = node; } public TLPar getLPar() { return this._lPar_; } public void setLPar(TLPar node) { if(this._lPar_ != null) { this._lPar_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._lPar_ = node; } public PFuncPara getFuncPara() { return this._funcPara_; } public void setFuncPara(PFuncPara node) { if(this._funcPara_ != null) { this._funcPara_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._funcPara_ = node; } @Override public String toString() { return "" + toString(this._call_) + toString(this._id_) + toString(this._lPar_) + toString(this._funcPara_); } @Override void removeChild(@SuppressWarnings("unused") Node child) { // Remove child if(this._call_ == child) { this._call_ = null; return; } if(this._id_ == child) { this._id_ = null; return; } if(this._lPar_ == child) { this._lPar_ = null; return; } if(this._funcPara_ == child) { this._funcPara_ = null; return; } throw new RuntimeException("Not a child."); } @Override void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild) { // Replace child if(this._call_ == oldChild) { setCall((TCall) newChild); return; } if(this._id_ == oldChild) { setId((TId) newChild); return; } if(this._lPar_ == oldChild) { setLPar((TLPar) newChild); return; } if(this._funcPara_ == oldChild) { setFuncPara((PFuncPara) newChild); return; } throw new RuntimeException("Not a child."); } }
package ca.antonious.habittracker.todayshabitlist; import android.content.Intent; import android.os.Bundle; 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 java.util.List; import ca.antonious.habittracker.BaseFragment; import ca.antonious.habittracker.Constants; import ca.antonious.habittracker.R; import ca.antonious.habittracker.habitdetails.HabitDetailsActivity; import ca.antonious.habittracker.models.Habit; import ca.antonious.habittracker.viewcells.EmptyViewCell; import ca.antonious.habittracker.viewcells.HabitViewCell; import ca.antonious.viewcelladapter.ViewCellAdapter; import ca.antonious.viewcelladapter.construction.SectionBuilder; import ca.antonious.viewcelladapter.sections.HomogeneousSection; /** * Created by George on 2016-09-30. */ public class TodaysHabitsFragment extends BaseFragment implements ITodaysHabitsView { private RecyclerView habitRecyclerView; private HomogeneousSection<Habit, HabitViewCell> habitsSection; private TodaysHabitsController controller; public static TodaysHabitsFragment newInstance() { return new TodaysHabitsFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.content_todays_habits, container, false); bindViews(view); resolveDependencies(); habitRecyclerView.setAdapter(getViewCellAdapter()); habitRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); return view; } private void bindViews(View view) { habitRecyclerView = (RecyclerView) view.findViewById(R.id.habit_recycler_view); } private void resolveDependencies() { controller = getHabitTrackerApplication().getTodaysHabitsController(); } private ViewCellAdapter getViewCellAdapter() { habitsSection = new HomogeneousSection<>(Habit.class, HabitViewCell.class); return ViewCellAdapter.create() .section( SectionBuilder.wrap(habitsSection) .showIfEmpty(new EmptyViewCell("Seems like you have no habits for today")) .build() ) .listener(new HabitViewCell.OnHabitClickedListener() { @Override public void onHabitClicked(Habit habit, int position) { navigateToDetails(habit.getId()); } }) .listener(new HabitViewCell.OnCompleteClickedListener() { @Override public void onComplete(Habit habit, int position) { controller.markHabitAsCompleted(habit.getId()); } }) .build(); } private void navigateToDetails(String habitID) { Intent intent = new Intent(getActivity(), HabitDetailsActivity.class); intent.putExtra(Constants.EXTRA_HABIT_ID, habitID); startActivity(intent); } @Override public void onResume() { super.onResume(); controller.attachView(this); } @Override public void onPause() { super.onPause(); controller.detachView(); } @Override public void displayTodaysHabits(List<Habit> habits) { habitsSection.setAll(habits); } }
package ru.android.messenger.view.interfaces; import android.content.Context; import android.graphics.Bitmap; public interface NavigationDrawerView { Context getContext(); void setProfileImageToNavigationDrawer(Bitmap bitmap); void setUserDataToNavigationDrawer(String firstName, String surname, String login, String email); }
package org.newdawn.slick.svg.inkscape; import org.newdawn.slick.svg.NonGeometricData; import org.w3c.dom.Element; public class InkscapeNonGeometricData extends NonGeometricData { private Element element; public InkscapeNonGeometricData(String metaData, Element element) { super(metaData); this.element = element; } public String getAttribute(String attribute) { String result = super.getAttribute(attribute); if (result == null) result = this.element.getAttribute(attribute); return result; } public Element getElement() { return this.element; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\svg\inkscape\InkscapeNonGeometricData.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
/** * */ package knowbigdata.anagram; import java.io.IOException; import java.util.Set; import java.util.TreeSet; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; /** * @author Kiran * */ public class AnagramMapper extends Mapper<LongWritable, Text, Text, Text>{ @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{ //my cat name is dog if( null == value){ return; } final String[] words = value.toString().split(" "); if( null == words){ return; } for( int i=0; i < words.length; i++){ context.write(new Text(this.getSortedKey(words[i].trim())), new Text(words[i].trim())); } } private String getSortedKey(final String word){ Set<Character> sortedChars = new TreeSet<Character>(); for( int i=0; i < word.length(); i++){ sortedChars.add(Character.toUpperCase(word.charAt(i))); } return sortedChars.toString(); } }
package com.isslam.kidsquran; import java.util.Random; import com.isslam.kidsquran.controllers.AudioListManager; import com.isslam.kidsquran.controllers.SharedPreferencesManager; import com.isslam.kidsquran.model.DataBaseHelper; import com.isslam.kidsquran.model.DataBaseHelper.DataBaseHelperInterface; import com.isslam.kidsquran.utils.GlobalConfig; import com.isslam.kidsquran.utils.Utils; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.AdapterView.OnItemClickListener; public class SplashScreenActivity extends FragmentActivity implements DataBaseHelperInterface { protected int _splashTime = 15000; // Time before Run App Main Activity private Context context; LinearLayout ly_slogan; LinearLayout ly_app; RelativeLayout ly_ma; RelativeLayout ly_strip; FloatingActionButton btn_rate; FloatingActionButton btn_other; FrameLayout ly_enter; ImageView contentbg; ProgressBar mProgress; RelativeLayout ly_pb_container; private DataBaseHelper myDbHelper; DataBaseHelperInterface dataBaseHelperInterface; private Thread splashTread; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = SplashScreenActivity.this; // remove title bar requestWindowFeature(Window.FEATURE_NO_TITLE); // application full screen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.ly_splash_screen);// Splash Layout SharedPreferencesManager sharedPreferencesManager = SharedPreferencesManager .getInstance(context); GlobalConfig.local = sharedPreferencesManager.GetStringPreferences( SharedPreferencesManager._local, GlobalConfig.local); GlobalConfig.lang_id = sharedPreferencesManager.GetStringPreferences( SharedPreferencesManager._lang_id, GlobalConfig.lang_id); Utils.updateLocal(context, GlobalConfig.local, GlobalConfig.lang_id); GlobalConfig._DBcontext = getApplicationContext().getPackageName(); dataBaseHelperInterface = this; ly_pb_container = (RelativeLayout) findViewById(R.id.ly_pb_container); ly_pb_container.setVisibility(View.GONE); ly_slogan = (LinearLayout) findViewById(R.id.ly_slogan); ly_app = (LinearLayout) findViewById(R.id.ly_app); ly_ma = (RelativeLayout) findViewById(R.id.ly_main_splash); ly_strip = (RelativeLayout) findViewById(R.id.ly_strip); contentbg = (ImageView) findViewById(R.id.contentbg); contentbg.setVisibility(View.GONE); ly_enter = (FrameLayout) findViewById(R.id.ly_enter); ly_enter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ly_enter.setVisibility(View.GONE); // TODO Auto-generated method stub Intent i = new Intent(); i.setClass(context, HomeActivity.class); startActivity(i); finish(); } }); ly_enter.setVisibility(View.GONE); btn_other = (FloatingActionButton) findViewById(R.id.btn_other); btn_other.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri .parse("https://play.google.com/store/apps/developer?id=islam+is+the+way+of+life")); startActivity(intent); } catch (ActivityNotFoundException e) { startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName()))); } } }); btn_other.setVisibility(View.GONE); btn_rate = (FloatingActionButton) findViewById(R.id.btn_rate); btn_rate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Uri uri = Uri.parse("market://details?id=" + context.getPackageName()); Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri); goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); try { startActivity(goToMarket); } catch (ActivityNotFoundException e) { startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.getPackageName()))); } } }); btn_rate.setVisibility(View.GONE); Animation anim = AnimationUtils.loadAnimation( SplashScreenActivity.this, R.anim.fade_out); ly_app.startAnimation(anim); ly_slogan.setVisibility(View.GONE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { ly_slogan.setVisibility(View.VISIBLE); ly_app.setVisibility(View.GONE); Animation anim = AnimationUtils.loadAnimation( SplashScreenActivity.this, R.anim.fade_in); ly_slogan.startAnimation(anim); CopyFiles CopyFilesa = new CopyFiles(); CopyFilesa.execute(); } }, 3000); try { if (myDbHelper == null) myDbHelper = new DataBaseHelper(dataBaseHelperInterface); } catch (Exception e) { e.getStackTrace(); } if (!myDbHelper.checkDataBase()) { // TextLoadingFirst.setVisibility(View.VISIBLE); // GlobalConfig.ShowLongToast(this, // "تحميل الكتاي لأول مرة /n الرجاء الانتظار"); // book_txt.setVisibility(book_txt.VISIBLE); } // /wait for 2 seconds and then show the loading image. final long DELAY = 1000; // in ms DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); Display display = getWindowManager().getDefaultDisplay(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); Log.e("width", "w: " + screenWidth + "; H : " + screenHeight); } private void playanim() { Animation animf = AnimationUtils.loadAnimation( SplashScreenActivity.this, R.anim.strip_hide); ly_strip.startAnimation(animf); animf.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { ly_pb_container.setVisibility(View.GONE); ly_strip.setVisibility(View.GONE); btn_rate.setVisibility(View.VISIBLE); btn_other.setVisibility(View.VISIBLE); Animation animb = AnimationUtils.loadAnimation( SplashScreenActivity.this, R.anim.grow_from_bottom); btn_rate.startAnimation(animb); btn_other.startAnimation(animb); ly_enter.setVisibility(View.VISIBLE); Animation animc = AnimationUtils.loadAnimation( SplashScreenActivity.this, R.anim.grow_from_top_speed); ly_enter.startAnimation(animc); Animation myRotation = AnimationUtils.loadAnimation( SplashScreenActivity.this, R.anim.rotator); contentbg.setVisibility(View.VISIBLE); contentbg.startAnimation(myRotation); } }); } @Override public boolean onTouchEvent(MotionEvent event) {// check if user Click on // the splash to start app if (event.getAction() == MotionEvent.ACTION_DOWN) { // synchronized (splashTread) { // splashTread.notifyAll(); // } } return true; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exitByBackKey(); return true; } return super.onKeyDown(keyCode, event); } protected void exitByBackKey() { CloseAppFragment closeAppFragment = new CloseAppFragment(); closeAppFragment.setStyle(DialogFragment.STYLE_NO_FRAME, android.R.style.Theme_Holo_NoActionBar_Fullscreen); closeAppFragment.show(getSupportFragmentManager(), "closeappfragment"); } @Override public void onBackPressed() { } @Override public void onRequestCompleted() { // TODO Auto-generated method stub } public class CopyFiles extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { super.onPreExecute(); } Runnable run; @Override protected void onPostExecute(String x) { super.onPostExecute(""); Log.e("onpost", "onpost"); GlobalConfig.myDbHelper = myDbHelper; SharedPreferencesManager sharedPreferencesManager = SharedPreferencesManager .getInstance(context); sharedPreferencesManager.SetupPreferences(); AudioListManager audioListManager = AudioListManager.getInstance(); int reciterId = sharedPreferencesManager.GetIntegerPreferences( SharedPreferencesManager._reciter_id, 4); audioListManager.updateAllreciters(reciterId, context); audioListManager.updateAllSuras(); // unzipFromAssets(context, "/assets/1.zip", // Environment.getExternalStorageDirectory() + // "/"+GlobalConfig.audioRootPath+"/" // + "1/"); if (!Utils.isFileExist("4", GlobalConfig.filetocheck)) { ly_pb_container.setVisibility(View.VISIBLE); ExtractReciterThread extractReciterThread = new ExtractReciterThread( SplashScreenActivity.this, context, "/assets/4.zip", Environment.getExternalStorageDirectory() + "/" + GlobalConfig.audioRootPath + "/" + "4/"); extractReciterThread.start(); Resources res = getResources(); Drawable drawable = res.getDrawable(R.drawable.progress_green); mProgress = (ProgressBar) findViewById(R.id.progressbar1); mProgress.setProgress(0); // Main Progress mProgress.setSecondaryProgress(0); // Secondary Progress mProgress.setMax(100); // Maximum Progress mProgress.setProgressDrawable(drawable); final Random r = new Random(); final Handler handler = new Handler(); run = new Runnable() { public void run() { int rand = r.nextInt(8); if (mProgress.getProgress() < 100) mProgress.setProgress(mProgress.getProgress() + rand); if (mProgress.getProgress() > 100) mProgress.setProgress(100); handler.postDelayed(run, 900); } }; handler.postDelayed(run, 900); } else { ly_pb_container.setVisibility(View.GONE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { playanim(); // startActivity(i); // finish(); // Actions to do after 10 seconds } }, 2000); } if (sharedPreferencesManager.getBooleanPreferences( SharedPreferencesManager._first_run, true)) { sharedPreferencesManager.savePreferences( SharedPreferencesManager._first_run, false); // showLanguageslist(); } else { } } @Override protected String doInBackground(Void... arg0) { Log.e("int", "int"); myDbHelper.InitDB(); // TODO Auto-generated method stub return ""; } } public void showLanguageslist() { final Dialog dialog = new Dialog(context); dialog.setCancelable(false); dialog.setTitle(context.getResources().getString( R.string.setting_language_title)); ListView modeList = new ListView(context); final Context _context = context; modeList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String[] data = getResources().getStringArray( R.array.arr_languages_locals); String[] lang_ids = getResources().getStringArray( R.array.arr_languages_ids); Utils.updateLocal(_context, data[position], lang_ids[position]); dialog.cancel(); Intent i = new Intent(); i.setClass(_context, HomeActivity.class); startActivity(i); finish(); } }); String[] languages = getResources().getStringArray( R.array.arr_languages_items); LanguagesAdapter adapter1 = new LanguagesAdapter(context, languages); modeList.setAdapter(adapter1); dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); dialog.setContentView(modeList); dialog.show(); } private Runnable Timer_Tick = new Runnable() { public void run() { showLanguageslist(); } }; public Handler activityHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { /* * Handling MESSAGE_UPDATE_PROGRESS_BAR: 1. Get the current * progress, as indicated in the arg1 field of the Message. 2. * Update the progress bar. */ case 100: Log.e("start", "start"); break; case 200: Log.e("END", "END"); mProgress.setProgress(100); playanim(); break; } } }; }
/* * 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 cliente; import calculadoraBasica.DivisionPorCeroException_Exception; /** * * @author crist_000 */ public class CalculadoraBasica { public static Float division(java.lang.Float dividendo, java.lang.Float divisor) throws DivisionPorCeroException_Exception { calculadoraBasica.CalculadoraBasica_Service service = new calculadoraBasica.CalculadoraBasica_Service(); calculadoraBasica.CalculadoraBasica port = service.getCalculadoraBasicaPort(); return port.division(dividendo, divisor); } public static Float multiplicacion(java.lang.Float factor1, java.lang.Float factor2) { calculadoraBasica.CalculadoraBasica_Service service = new calculadoraBasica.CalculadoraBasica_Service(); calculadoraBasica.CalculadoraBasica port = service.getCalculadoraBasicaPort(); return port.multiplicacion(factor1, factor2); } public static Float resta(java.lang.Float minuendo, java.lang.Float sustraendo) { calculadoraBasica.CalculadoraBasica_Service service = new calculadoraBasica.CalculadoraBasica_Service(); calculadoraBasica.CalculadoraBasica port = service.getCalculadoraBasicaPort(); return port.resta(minuendo, sustraendo); } public static Float suma(java.lang.Float sumando1, java.lang.Float sumando2) { calculadoraBasica.CalculadoraBasica_Service service = new calculadoraBasica.CalculadoraBasica_Service(); calculadoraBasica.CalculadoraBasica port = service.getCalculadoraBasicaPort(); return port.suma(sumando1, sumando2); } }
package com.kovko.dictionary; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Locale; public class EngRuCsvFileDictionary implements Dictionary { private static final String DELIMITER = ","; private final HashMap<String, String> translations; public EngRuCsvFileDictionary(String fileName) { Charset charset = Charset.forName("UTF-8"); Locale sourceLocale = new Locale("us"); Locale targetLocale = new Locale("ru"); translations = new HashMap<>(); try (InputStream stream = getClass().getClassLoader().getResourceAsStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(stream, charset); BufferedReader reader = new BufferedReader(inputStreamReader)) { for (String line = reader.readLine(); line != null; line = reader.readLine()) { String[] words = line.split(DELIMITER); if (words.length == 2) { String word = words[0].toLowerCase(sourceLocale).trim(); String translation = words[1].toLowerCase(targetLocale).trim(); translations.put(word, translation); } } } catch (IOException e) { throw new RuntimeException(e); } } @Override public String lookUp(String text) { return translations.get(text.toLowerCase(Locale.US).trim()); } }
package com.worker.shared; //primary for testing scenarios when handling control message fails public class FailedControlMessage extends ControlMessage { private String failureReason; public FailedControlMessage() { } public FailedControlMessage(String failureReason) { this.failureReason = failureReason; } @Override public void accept(ControlMessageVisitor controlMessageVisitor) { controlMessageVisitor.visit(this); } public String getFailureReason() { return failureReason; } public void setFailureReason(String failureReason) { this.failureReason = failureReason; } @Override public String toString() { return "FailedControlMessage [failureReason=" + failureReason + "]"; } @Override public String toShortFormat() { return toString(); } }
package Lab01.Zad5; public class Main { public static void main(String[] args) { TaxDe td = new TaxDe(); TaxGB tg = new TaxGB(); TaxPl tp = new TaxPl(); Shop onlineShop = new Shop(tp); System.out.println(onlineShop.tax.countTax(100.0D)); onlineShop.setTax(td); System.out.println(onlineShop.tax.countTax(100.0D)); onlineShop.setTax(tg); System.out.println(onlineShop.tax.countTax(100.0D)); } }
package android.huyhuynh.orderapp.retrofit2; import android.huyhuynh.orderapp.model.Ban; import android.huyhuynh.orderapp.model.Menu; import android.huyhuynh.orderapp.model.Message; import android.huyhuynh.orderapp.model.Order; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * Created by Huy Huynh on 16-09-2019. */ public interface DataClient { @FormUrlEncoded @POST("menu/get") Call<List<Menu>> getListMenu(@Field("maBan") String maBan); @FormUrlEncoded @POST("ban/find") Call<Ban> loginWithQR(@Field("maBan") String maBan); @POST("order/addlist") Call<Message> sendOrder(@Body List<Order> maBan); }
package com.smallproject.dominicparks.pages; import java.util.List; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class RoomsPage { WebDriver webdriver; public RoomsPage(WebDriver webdriver) { this.webdriver = webdriver; PageFactory.initElements(webdriver, this); } @FindBy(id = "price_ftr") private WebElement sortprice; @FindBy(className = "sort_result") private List<WebElement> highestprice; @FindBy(xpath = "//a[.='Price : Lowest First']") private List<WebElement> lowestprice; @FindBy(className = "rm_heading") private List<WebElement> roomName; @FindBy(xpath = "//span[.='Book Now']") private List<WebElement> bookNow; public void clickPrice() { sortprice.click(); } public void clickHighestPrice(int index) { highestprice.get(index).click(); } public void clickLowestPrice(int index) { lowestprice.get(index).click(); } public String getRoomName(int index) { return roomName.get(index).getText(); } public void clickBookNow(int index) { bookNow.get(index).click(); } public void switchFrame() { webdriver.getWindowHandle(); } public boolean isDisplayed() { return true; } }
package earth.eu.jtzipi.jbat.ui; import earth.eu.jtzipi.jbat.JBatGlobal; import earth.eu.jtzipi.modules.node.path.IPathNode; import javafx.beans.property.*; import javafx.geometry.Insets; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.effect.Glow; import javafx.scene.image.ImageView; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.FlowPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.stream.Collectors; public class TilePane extends FlowPane { private static final String FX_PATH_NODE_FILTER_PROP = "FX_PATH_NODE_FILTER"; private static final String FX_BACKGROUND_COLOR_PROP = "FX_BACKGROUND_COLOR"; private static final Logger LOG = LoggerFactory.getLogger( TilePane.class ); // view of all nodes //private FlowPane tileP; // wrapper for flow pane private ScrollPane tileScrP; /** * */ TilePane() { createTilePane(); gadi(); // set first dir pathChanged( JBatGlobal.FX_CURRENT_DIR_PATH.getValue() ); } /** * Create pane. */ private void createTilePane() { //tileOL = FXCollections.observableArrayList(); //tileP = new FlowPane(); //tileP.setPrefWrapLength(PREF_HWRAP); //setCenter(tileScrP); Color colorBG = Color.rgb( 7, 7, 77, 1D ); // DEBUG setBackground( new Background( new BackgroundFill( colorBG, CornerRadii.EMPTY, Insets.EMPTY ) ) ); } /** * Init Property Listener. */ private void gadi() { // If dir node change JBatGlobal.FX_CURRENT_DIR_PATH.addListener( ( obs, oldPath, newPath ) -> { LOG.warn( "gysi : " + oldPath + " > " + newPath ); // real change if ( null != newPath && oldPath != newPath ) { pathChanged( newPath ); } } ); } /** * Directory changed. * * @param path path */ private void pathChanged( IPathNode path ) { //tileOL.clear(); // Get sub nodes and map them to tiles List<Tile> tileL = path.getSubnodes() .stream() .map( Tile::new ) .collect( Collectors.toList() ); getChildren().setAll( tileL ); } private void onFilterChanged() { } /** * A tile of flow pane. */ private static final class Tile extends Label { // background if not mouse over private static final Background MOUSE_NOT_OVER_BACKGROUND = Background.EMPTY; // background if mouse over private Background mouseOverBG; // Border stroke of tile // private BorderStroke borderStroke; private Color textCol = Color.rgb( 47, 127, 247, 1D ); // file icon private ImageView iconIV; private Glow hoverGlow; private Glow selectGlow; // Tile size FX Property private ObjectProperty<Size> fxPropSize = new SimpleObjectProperty<>( this, "FX_PROP_TILE_SIZE", Size.MEDIUM ); /** * Tile size. */ enum Size { DEFAULT( 128D, true ), LARGE( 106D, true ), MEDIUM( 56D, false ), SMALL( 49D, false ), TINY( 41D, false ); private final double size; private final boolean drawText; private DoubleProperty fxSizeProp; private BooleanProperty fxDrawTextProp; /** * @param size * @param drawTextProp */ Size( final double size, final boolean drawTextProp ) { this.size = size; this.drawText = drawTextProp; } /** * @return */ DoubleProperty fxSizeProp() { if ( null == fxSizeProp ) { fxSizeProp = new SimpleDoubleProperty( this, "", getSize() ); } return fxSizeProp; } BooleanProperty fxDrawTextProp() { if ( null == fxDrawTextProp ) { fxDrawTextProp = new SimpleBooleanProperty( this, "", isDrawText() ); } return fxDrawTextProp; } /** * Size of tile. * * @return size */ double getSize() { return this.size; } /** * Draw text. * * @return draw text */ boolean isDrawText() { return this.drawText; } } // path to wrap private final IPathNode pathNode; private Tile( IPathNode pn ) { this.pathNode = pn; createTile(); } private void createTile() { // create image view for tile and set width iconIV = new ImageView(); iconIV.fitWidthProperty().bind( fxPropSize.getValue().fxSizeProp() ); iconIV.setPreserveRatio( true ); Font f = Font.getDefault(); setFont( f ); // Font.font( 24D ) setText( pathNode.getName() ); setGraphic( iconIV ); setTextFill( textCol ); setContentDisplay( ContentDisplay.TOP ); setPadding( new Insets( 10 ) ); Size s = fxPropSize.getValue(); setPrefSize( s.getSize(), s.getSize() ); selectGlow = new Glow( 0.7D ); setOnMouseExited( me -> setEffect( null ) ); setOnMouseEntered( me -> setEffect( selectGlow ) ); setOnMouseClicked( mousE -> { // on } ); } public String toString() { return "TPath { " + pathNode + " }"; } } }
package net.cupmouse.minecraft.eplugin.data.user; import net.cupmouse.minecraft.eplugin.EPlugin; import net.cupmouse.minecraft.eplugin.data.EID; import net.cupmouse.minecraft.eplugin.data.HaveEIDManager; import net.cupmouse.minecraft.eplugin.data.wallet.Wallet; import net.cupmouse.minecraft.eplugin.database.DatabaseManager; import net.cupmouse.minecraft.eplugin.database.ResultCallable; import net.cupmouse.minecraft.eplugin.database.ResultConsumer; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.entity.Entity; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.action.SleepingEvent; import org.spongepowered.api.event.block.ChangeBlockEvent; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; import org.spongepowered.api.event.cause.entity.damage.source.EntityDamageSource; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.command.TabCompleteEvent; import org.spongepowered.api.event.entity.DestructEntityEvent; import org.spongepowered.api.event.entity.DisplaceEntityEvent; import org.spongepowered.api.event.entity.HarvestEntityEvent; import org.spongepowered.api.event.entity.TameEntityEvent; import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent; import org.spongepowered.api.event.message.MessageChannelEvent; import org.spongepowered.api.event.network.ClientConnectionEvent; import org.spongepowered.api.item.Enchantments; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.ItemTypes; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.text.Text; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static net.cupmouse.minecraft.eplugin.language.LanguageManager.lt; /** * ユーザー管理コンポーネント * * @author sssanma * @since 2014/09/10 */ public final class UserManager extends HaveEIDManager<User> { private final Map<UUID, User> onlineUsers = new HashMap<>(); private final Map<UUID, User> trackedUsers = new WeakHashMap<>(); public UserManager(EPlugin session) { super(session, "ユーザー"); } @Override public void onEnable() { plugin.eidManager.registerPrefix(this, 'p'); } @Override public void registerListeners() { // TODO Owner Sponge.getEventManager().registerListeners(plugin, this); } /** * 現在のスレッドで{@code consumer}が呼ばれます。 * * @param uuid * @param consumer */ private void get(UUID uuid, ResultConsumer<Optional<User>> consumer) { synchronized (trackedUsers) { Optional<User> searchTracking = searchTracking(uuid); if (searchTracking.isPresent()) { consumer.accept(searchTracking); } } final Integer[] userId = new Integer[1]; Future<Boolean> booleanFuture = plugin.db.createSession().prepareResult("SELECT user_id FROM users WHERE uuid = ?", preparedStatement -> { preparedStatement.setBytes(1, DatabaseManager.uuidToBytes(uuid)); }, resultSet -> { if (resultSet.next()) { userId[0] = resultSet.getInt(1); } else { userId[0] = null; } }).executeAll(); try { if (booleanFuture.get()) { if (userId[0] == null) { consumer.accept(Optional.empty()); } else { Wallet.getWallet(plugin, userId[0], uuid, new ResultConsumer<Optional<Wallet>>() { @Override public void accept(Optional<Wallet> wallet) { User user = new User(UserManager.this, userId[0], uuid, wallet.get()); trackedUsers.put(uuid, user); consumer.accept(Optional.of(user)); } @Override public void failed() { consumer.failed(); } }); } } else { consumer.failed(); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } /** * 現在のスレッドで{@code consumer}が呼ばれます。 * * @param uuid * @param consumer */ private void getOrCreate(UUID uuid, ResultConsumer<User> consumer) { Optional<User> searchTracking = searchTracking(uuid); if (searchTracking.isPresent()) { consumer.accept(searchTracking.get()); } get(uuid, new ResultConsumer<Optional<User>>() { @Override public void accept(Optional<User> userOptional) { if (userOptional.isPresent()) { consumer.accept(userOptional.get()); } else { // 存在しないので作成 plugin.getLogger().info("ユーザーを作成します。[" + uuid + "]"); byte[] uuidBytes = DatabaseManager.uuidToBytes(uuid); final int[] userId = new int[1]; final int[] walletId = new int[1]; Future<Boolean> booleanFuture = plugin.db.createSession().prepareUpdate("INSERT INTO users VALUES(null, ?, ?)", preparedStatement -> { preparedStatement.setBytes(1, uuidBytes); preparedStatement.setString(2, EID.fromUUID(uuid).code); }).result("SELECT LAST_INSERT_ID()", resultSet -> { resultSet.next(); userId[0] = resultSet.getInt(1); }).prepareUpdate("INSERT INTO wallets VALUES(NULL, ?, ?, 0)", preparedStatement -> { preparedStatement.setInt(1, userId[0]); preparedStatement.setBytes(2, DatabaseManager.uuidToBytes(uuid)); }).result("SELECT LAST_INSERT_ID()", resultSet -> { resultSet.next(); walletId[0] = resultSet.getInt(1); }).executeAll(); try { if (booleanFuture.get()) { Wallet wallet = new Wallet(plugin, walletId[0], userId[0], uuid); User user = new User(UserManager.this, userId[0], uuid, wallet); trackedUsers.put(uuid, user); consumer.accept(user); } else { consumer.failed(); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } @Override public void failed() { consumer.failed(); } }); } private Optional<User> searchTracking(UUID uuid) { synchronized (trackedUsers) { for (User user : trackedUsers.values()) { if (user.uuid == uuid) { return Optional.of(user); } } plugin.getLogger().info("ユーザーがキャッシュされていません。[" + uuid + "]"); return Optional.empty(); } } private Optional<User> searchTracking(int userId) { synchronized (trackedUsers) { for (User user : trackedUsers.values()) { if (user.userId == userId) { return Optional.of(user); } } plugin.getLogger().info("ユーザーがキャッシュされていません。[" + userId + "]"); return Optional.empty(); } } /** * このスレッドで{@code consumer}が呼ばれます。 * * @param userId * @param consumer */ public void get(int userId, ResultConsumer<Optional<User>> consumer) { Optional<User> searchTracking = searchTracking(userId); if (searchTracking.isPresent()) { consumer.accept(searchTracking); } final UUID[] uuid = new UUID[1]; Future<Boolean> booleanFuture = plugin.db.createSession().prepareResult("SELECT uuid FROM users WHERE user_id = ?", preparedStatement -> { preparedStatement.setInt(1, userId); }, resultSet -> { if (resultSet.next()) { uuid[0] = DatabaseManager.bytesToUUID(resultSet.getBytes(1)); } else { uuid[0] = null; } }).executeAll(); try { if (booleanFuture.get()) { if (uuid[0] == null) { consumer.accept(Optional.empty()); } Wallet.getWallet(plugin, userId, uuid[0], new ResultConsumer<Optional<Wallet>>() { @Override public void accept(Optional<Wallet> wallet) { User user = new User(UserManager.this, userId, uuid[0], wallet.get()); trackedUsers.put(uuid[0], user); consumer.accept(Optional.of(user)); } @Override public void failed() { consumer.failed(); } }); } else { consumer.failed(); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } public UserSession getUS(Player player) { return onlineUsers.get(player.getUniqueId()).getUserSession().get(); } public Collection<User> getOnlines() { return Collections.unmodifiableCollection(onlineUsers.values()); } public User getOnline(Player player) { return onlineUsers.get(player.getUniqueId()); } @Override public void getByName(String playerName, ResultConsumer<Set<User>> consumer) { final Integer[] userId = new Integer[1]; Future<Boolean> booleanFuture = plugin.db.createSession().prepareResult("SELECT user_id FROM user_connection_history WHERE name = ? ORDER BY time DESC LIMIT 1", preparedStatement -> { preparedStatement.setString(1, playerName); }, resultSet -> { if (resultSet.next()) { userId[0] = resultSet.getInt(1); } else { userId[0] = null; } }).executeAll(); Sponge.getScheduler().createTaskBuilder().async().execute(() -> { try { if (booleanFuture.get()) { get(userId[0], new ResultConsumer<Optional<User>>() { @Override public void accept(Optional<User> userOptional) { HashSet<User> users = new HashSet<>(); if (userOptional.isPresent()) { users.add(userOptional.get()); } Sponge.getScheduler().createTaskBuilder().execute(() -> consumer.accept(users)).submit(plugin); } @Override public void failed() { Sponge.getScheduler().createTaskBuilder().execute(consumer::failed).submit(plugin); } }); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }).submit(plugin); } @Listener public void onClientConnectionAuth(ClientConnectionEvent.Auth auth) { try { UUID uniqueId = auth.getProfile().getUniqueId(); getOrCreate(uniqueId, new ResultConsumer<User>() { @Override public void accept(User user) { onlineUsers.put(uniqueId, user); } @Override public void failed() { auth.setCancelled(true); } }); } catch (Exception e) { auth.setCancelled(true); } } @Listener(order = Order.PRE) public void onClientConnectionJoin(ClientConnectionEvent.Join event) { Player player = event.getTargetEntity(); try { User user = searchTracking(player.getUniqueId()).get(); user.createNewSession(player); user.recordConnection(UserConnectionRecord.Type.JOIN); } catch (Exception e) { player.kick(Text.of(lt("message.login.deniedfor.errorininitialization"))); e.printStackTrace(); } } @Listener(order = Order.POST) public void onPlayerDisconnect(ClientConnectionEvent.Disconnect event) { if (!this.onlineUsers.containsKey(event.getTargetEntity().getUniqueId())) { plugin.getLogger().warn(event.getTargetEntity().getUniqueId() + "がログインしていないのにログアウトしました。"); return; } Player player = event.getTargetEntity(); UUID uniqueId = player.getUniqueId(); User user = this.onlineUsers.get(uniqueId); user.recordConnection(UserConnectionRecord.Type.DISCONNECT); user.closeSession(); this.onlineUsers.remove(uniqueId); } @Listener(order = Order.LAST) public void onPlayerDisplace(DisplaceEntityEvent.TargetPlayer event) { UserSession us = getUS(event.getTargetEntity()); us.setLastMoveTime(); us.unAfk(); } @Listener(order = Order.LAST) public void onTabComplete(TabCompleteEvent event) { Optional<Player> firstPlayer = event.getCause().first(Player.class); if (firstPlayer.isPresent()) { UserSession us = getUS(firstPlayer.get()); us.setLastActionTime(); us.unAfk(); } } @Listener(order = Order.LAST) public void onSendCommand(SendCommandEvent event) { Optional<Player> first = event.getCause().first(Player.class); if (first.isPresent()) { UserSession userSession = plugin.userManager.getUS(first.get()); userSession.setLastActionTime(); userSession.unAfk(); } } @Listener(order = Order.LAST) public void onMessageChannel(MessageChannelEvent event) { Optional<Player> playerOptional = event.getCause().first(Player.class); if (playerOptional.isPresent()) { UserSession us = getUS(playerOptional.get()); us.setLastActionTime(); us.unAfk(); } } @Listener(order = Order.LAST) public void onTame(TameEntityEvent event) { Optional<Player> first = event.getCause().first(Player.class); if (first.isPresent()) { plugin.userManager.getOnline(first.get()).giveBadgeAndNotify(Badges.HAVE_A_PET); } } @Listener(order = Order.LAST) public void onPreSleeping(SleepingEvent.Pre event) { if (!(event.getTargetEntity() instanceof Player)) { return; } Player player = (Player) event.getTargetEntity(); plugin.userManager.getOnline(player).giveBadgeAndNotify(Badges.GOOD_NIGHT); } @Listener(order = Order.LAST) public void onPlayerChat(MessageChannelEvent.Chat event) { Optional<Player> firstOptional = event.getCause().first(Player.class); if (firstOptional.isPresent()) { User online = getOnline(firstOptional.get()); online.giveBadgeAndNotify(Badges.FIRST_CHAT); } } @Listener(order = Order.LAST) public void onPlayerDeath(DestructEntityEvent.Death event) { if (!(event.getTargetEntity() instanceof Player)) { return; } Player died = (Player) event.getTargetEntity(); Location<World> location = died.getLocation(); // TODO DamageSource firstDamageSource = event.getCause().first(DamageSource.class).get(); UserDeathHistorySnapshot.Type type; Entity entity = null; if (firstDamageSource instanceof EntityDamageSource) { entity = ((EntityDamageSource) firstDamageSource).getSource(); if (entity instanceof Player) { type = UserDeathHistorySnapshot.Type.PLAYER; } else { plugin.getLogger().info(entity.getType().getId()); type = UserDeathHistorySnapshot.Type.getByEntityId(entity.getType().getId()); } } else { BlockType blockType = location.getBlockType(); if (firstDamageSource.getType() == DamageTypes.CONTACT && (blockType == BlockTypes.LAVA || blockType == BlockTypes.FLOWING_LAVA)) { type = UserDeathHistorySnapshot.Type.LAVA; } else { type = UserDeathHistorySnapshot.Type.OTHER; } } User user = getOnline(died); user.recordDeathHistory(type, entity == null ? null : entity.getUniqueId(), location, new ResultCallable() { @Override public void call() { // 実績 user.getNumberOfDeath(new ResultConsumer<Integer>() { @Override public void accept(Integer integer) { if (integer >= 100) { user.giveBadgeAndNotify(Badges.CRAFTER); } } }); user.getNumberOfDeathBy(UserDeathHistorySnapshot.Type.LAVA, new ResultConsumer<Integer>() { @Override public void accept(Integer integer) { if (integer >= 40) { user.giveBadgeAndNotify(Badges.MAGMADIVER); } } }); } }); } @Listener(order = Order.LAST) public void onPlayerPickupItem(ChangeInventoryEvent.Pickup event) { Optional<Player> firstPlayer = event.getCause().first(Player.class); if (firstPlayer.isPresent()) { Player player = firstPlayer.get(); ItemType type = event.getTransactions().get(0).getFinal().getType(); User user = plugin.userManager.getOnline(player); if (type == ItemTypes.MONSTER_EGG) user.giveBadgeAndNotify(Badges.EGGS); } } @Listener(order = Order.LAST) public void onBreakBlock(ChangeBlockEvent.Break event) { Optional<Player> firstPlayer = event.getCause().first(Player.class); if (firstPlayer.isPresent()) { Player player = firstPlayer.get(); User user = getOnline(player); BlockType blockType = event.getTransactions().get(0).getOriginal().getState().getType(); if (blockType == BlockTypes.MOB_SPAWNER) { user.giveBadgeAndNotify(Badges.SPAWNER); } else if (blockType == BlockTypes.DIAMOND_ORE) { Optional<ItemStack> itemInHandOptional = player.getItemInHand(); if (itemInHandOptional.isPresent() && itemInHandOptional.get().getItem() == ItemTypes.DIAMOND_PICKAXE && !itemInHandOptional.get().get(Keys.ITEM_ENCHANTMENTS).get().stream() .anyMatch(itemEnchantment -> itemEnchantment.getEnchantment() == Enchantments.SILK_TOUCH)) { user.giveBadgeAndNotify(Badges.DIAMOND_DIAMOND); } } } } }
package com.prayas.repository; import org.springframework.data.cassandra.repository.CassandraRepository; import org.springframework.stereotype.Repository; import com.prayas.model.Book; @Repository public interface BookRepository extends CassandraRepository<Book> { // TODO : Try Out Custom CQL Queries }
package com.example.sect; import android.content.Intent; import android.database.Cursor; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class msgsd extends AppCompatActivity { ListView lv; EditText un; database db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_msgsd); db=new database(this); lv=findViewById(R.id.lvd); un=findViewById(R.id.unid); ArrayList<String> arrl=new ArrayList<>(); Cursor c=db.gt_allmsgs(); while (c.moveToNext()){ if(c.getString(22).substring(0,5).equals("Admin")){ arrl.add(c.getString(12)+"\n"); }else { arrl.add(c.getString(12)+" Message "+"\n"); } } ArrayAdapter<String> arrad=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1,arrl); lv.setAdapter(arrad); } public void ms(View v){ if (un.getText().toString().equals("")){ Toast.makeText(this,"Empty",Toast.LENGTH_LONG).show(); }else { Cursor c=db.gt_allmsgs(); while (c.moveToNext()){ if (un.getText().toString().equals(c.getString(12))){ Intent intent=new Intent(msgsd.this,messageadmin.class); intent.putExtra("k","i"); intent.putExtra("unam",un.getText().toString()); startActivity(intent); return; } } Toast.makeText(msgsd.this,"Not Found",Toast.LENGTH_LONG).show(); } } }
package rent.api.utils; public interface Constants { String PRODUCES_TEXT_HTML_UTF8 = "text/html;charset=UTF-8"; String REQUEST_PARAM_FILE = "file"; String HEADER_CONTENT_FILE_NAME = "content-file-name"; String HEADER_CONTENT_DISPOSITION = "content-disposition"; String HEADER_AUTHORIZATION = "Authorization"; /** * точность расчетов, округление до 8-ми знаков после запятой */ int CALCULATION_ROUND_SCALE = 8; interface Url { String CONTENT = "/content"; } interface Report { String UNIVERSAL_PAYMENT_DOCUMENT = "UniversalPaymentDocument.jrxml"; String UNIVERSAL_PAYMENT_DOCUMENT_SECTION_3 = "UniversalPaymentDocumentSection3.jrxml"; String UNIVERSAL_PAYMENT_DOCUMENT_SECTION_4 = "UniversalPaymentDocumentSection4.jrxml"; String UNIVERSAL_PAYMENT_DOCUMENT_SECTION_5 = "UniversalPaymentDocumentSection5.jrxml"; } }
package com.tencent.mm.plugin.chatroom.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.model.c; import com.tencent.mm.plugin.chatroom.ui.SeeAccessVerifyInfoUI.a; import com.tencent.mm.plugin.chatroom.ui.SeeAccessVerifyInfoUI.b; import com.tencent.mm.sdk.platformtools.bi; class SeeAccessVerifyInfoUI$b$1 implements OnClickListener { final /* synthetic */ b hOD; final /* synthetic */ int hW; SeeAccessVerifyInfoUI$b$1(b bVar, int i) { this.hOD = bVar; this.hW = i; } public final void onClick(View view) { String BL; String str = ((a) this.hOD.hoC.get(this.hW)).nickname; String str2 = null; if (SeeAccessVerifyInfoUI.c(this.hOD.hOz) != null) { str2 = SeeAccessVerifyInfoUI.c(this.hOD.hOz).gT(((a) this.hOD.hoC.get(this.hW)).username); } if (bi.oW(str2)) { SeeAccessVerifyInfoUI.b(this.hOD.hOz); BL = c.FR().Yg(bi.oV(((a) this.hOD.hoC.get(this.hW)).username)).BL(); } else { BL = str2; } SeeAccessVerifyInfoUI.a(this.hOD.hOz, ((a) this.hOD.hoC.get(this.hW)).username, BL, str, true); } }
/* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.Freetalk; import freenet.keys.FreenetURI; import freenet.support.Base64; import freenet.support.IllegalBase64Exception; public interface Identity { public String getID(); /** * @return The requestURI ({@link FreenetURI}) to fetch this Identity */ public FreenetURI getRequestURI(); public String getNickname(); public String getShortestUniqueName(); public String getFreetalkAddress(); /** * A class for representing and especially verifying identity IDs. * We do not use it as a type for storing IDs in the database because that would make the queries significantly slower. * We store the IDs as String. */ public static final class IdentityID { public static final int MAX_IDENTITY_ID_LENGTH = 64; private final String mID; private IdentityID(final String id) { mID = id; } public static final IdentityID construct(final String id) { if(id.length() > MAX_IDENTITY_ID_LENGTH) throw new IllegalArgumentException("ID is too long, length: " + id.length()); try { final byte[] routingKey = Base64.decode(id); // TODO: Implement, its not important right now: FreenetURI.throwIfInvalidRoutingKey(routingKey) } catch (IllegalBase64Exception e) { throw new IllegalArgumentException("Invalid Base64 in ID: " + id); } return new IdentityID(id); } public static final IdentityID constructFromURI(final FreenetURI requestURI) { if(!requestURI.isUSK() && !requestURI.isSSK()) throw new IllegalArgumentException("URI is no SSK/USK: " + requestURI); return new IdentityID(Base64.encode(requestURI.getRoutingKey())); } @Override public final String toString() { return mID; } @Override public final boolean equals(final Object o) { if(o instanceof IdentityID) return mID.equals(((IdentityID)o).mID); if(o instanceof String) return mID.equals((String)o); return false; } } }
package com.vilio.nlbs.bps.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.vilio.nlbs.bps.service.InquiryService; import com.vilio.nlbs.common.service.CommonService; import com.vilio.nlbs.commonMapper.dao.*; import com.vilio.nlbs.commonMapper.pojo.*; import com.vilio.nlbs.remote.service.RemoteBpsService; import com.vilio.nlbs.todo.service.NlbsTODOService; import com.vilio.nlbs.util.*; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by dell on 2017/6/15/0015. */ @Service public class InquiryServiceImpl implements InquiryService { @Resource RemoteBpsService remoteBpsService; @Resource NlbsInquiryApplyMapper nlbsInquiryApplyMapper; @Resource NlbsOperationHistoryMapper nlbsOperationHistoryMapper; @Resource NlbsDistributorMapper nlbsDistributorMapper; @Resource CommonService commonService; @Resource NlbsCityMapper nlbsCityMapper; @Resource NlbsPendingUserDistributorMapper nlbsPendingUserDistributorMapper; @Resource NlbsTODOService nlbsTODOService; /** * 公寓估价 * * @param paramMap * @return * @throws Exception */ @Override public Map apartmentInquiry(Map paramMap) throws Exception { //Step 1 解析入参 Map<String, Object> headMap = new HashMap<String, Object>(); Map<String, Object> bodyMap = new HashMap<String, Object>(); headMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_HEAD); bodyMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_BODY); //Step 1.1 整理参数存储本地库--NlbsInquiryApply、 List<Map> paramList = (List<Map>) bodyMap.get(Fields.PARAM_COMPANY_PARAM_LIST); String userNo = (String) bodyMap.get(Fields.PARAM_USER_ID); String cityCode = (String) bodyMap.get(Fields.PARAM_CITY_CODE); String houseTypeCode = (String) bodyMap.get(Fields.PARAM_HOUSE_TYPE_CODE); String inquiryCode = CommonUtil.getCurrentTimeStr("NLBS-",""); String address = ""; NlbsInquiryApply nlbsInquiryApply = new NlbsInquiryApply(); nlbsInquiryApply.setCode(inquiryCode); nlbsInquiryApply.setUserNo(userNo); nlbsInquiryApply.setCityCode(cityCode); nlbsInquiryApply.setHouseType(houseTypeCode); nlbsInquiryApply.setAutoPrice(Constants.INQUIRY_TYPE_AUTO_PRICE); nlbsInquiryApply.setStatus(Constants.BPS_ORDER_STATUS_EVALUATING); if (paramList != null) { for (Map map : paramList) { String companyCode = (String) map.get(Fields.PARAM_COMPANY_CODE); if(AppraisalCompanys.WORLD_UNION.getCode().equals(companyCode)){ String plotsName = (String) map.get(Fields.PARAM_PLOTS_NAME); String unitName = (String) map.get(Fields.PARAM_UNIT_NAME); String houseName = (String) map.get(Fields.PARAM_HOUSE_NAME); String area = (String) map.get(Fields.PARAM_AREA); address = (plotsName == null ? "" : plotsName) + (unitName == null ? "" : unitName) + (houseName == null ? "" : houseName); nlbsInquiryApply.setAddress(address); nlbsInquiryApply.setArea(new BigDecimal(area == null ? "0" : area)); bodyMap.put(Fields.PARAM_ADDRESS, address);//整理address给bps使用 } if(AppraisalCompanys.SH_CHENGSHI.getCode().equals(companyCode)){ String unitName = (String) map.get(Fields.PARAM_UNIT_NAME); String houseName = (String) map.get(Fields.PARAM_HOUSE_NAME); String area = (String) map.get(Fields.PARAM_AREA); address = (unitName == null ? "" : unitName) + (houseName == null ? "" : houseName); nlbsInquiryApply.setAddress(address); nlbsInquiryApply.setArea(new BigDecimal(area == null ? "0" : area)); bodyMap.put(Fields.PARAM_ADDRESS, address);//整理address给bps使用 } break;//只取默认的第一个估价公司的地址 } } nlbsInquiryApplyMapper.getInsert(nlbsInquiryApply); //Step 2 调用BPS,询价 Map remoteParamMap = new HashMap(); headMap.remove(Fields.PARAM_CLIENTTIMESTAMP); headMap.remove(Fields.PARAM_USER_NO); bodyMap.put(Fields.PARAM_SOURCE_SYSTEM, "nlbs"); remoteParamMap.put(Fields.PARAM_MESSAGE_HEAD, headMap); remoteParamMap.put(Fields.PARAM_MESSAGE_BODY, bodyMap); Map remoteReturnMap = remoteBpsService.callService(remoteParamMap); Map<String, Object> remoteHeadMap = new HashMap<String, Object>(); Map<String, Object> remoteBodyMap = new HashMap<String, Object>(); remoteHeadMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_HEAD); remoteBodyMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_BODY); String remoteReturnCode = (String) remoteHeadMap.get(Fields.PARAM_MESSAGE_ERR_CODE); //Step 3 调用BPS返回,更新本地库,保存操作历史,修改出参 if(ReturnCode.SUCCESS_CODE.equals(remoteReturnCode)){ //判断当前用户是不是超管或者风控等内部用户 List<String> roleList = new ArrayList<String>(); roleList.add(Constants.ROLE_SUPPER_MANAGER); roleList.add(Constants.ROLE_SYSTEM_MANAGER); roleList.add(Constants.ROLE_BUSINESS_MANAGER); boolean isAdmin = commonService.isAdministrator(userNo, roleList); if(!isAdmin) { NlbsDistributor nlbsDistributor = nlbsDistributorMapper.selectDistributorByUserNo(userNo); if (nlbsDistributor != null && Constants.DISTRIBUTOR_VILIO_CODE.equals(nlbsDistributor.getCode())) { isAdmin = true; } } //整理BPS返回的关键参数 String bpsCode = remoteBodyMap.get(Fields.PARAM_SERIAL_NO) == null ? "" : remoteBodyMap.get(Fields.PARAM_SERIAL_NO).toString(); String status = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS).toString(); String price = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE).toString(); String priceTime = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME).toString(); //更新询价记录表 nlbsInquiryApply.setBpsCode(bpsCode); nlbsInquiryApply.setStatus(status); nlbsInquiryApply.setPrice(new BigDecimal(price)); nlbsInquiryApply.setPriceTime(DateUtil.parseDateTime3(priceTime)); nlbsInquiryApplyMapper.getUpdate(nlbsInquiryApply); //插入询价操作历史表 NlbsOperationHistory nlbsOperationHistory = new NlbsOperationHistory(); nlbsOperationHistory.setOperater(userNo); nlbsOperationHistory.setSerialNo(bpsCode); nlbsOperationHistory.setSystemCode("bps"); nlbsOperationHistory.setOperateType(Constants.OPERATION_SUBMIT_INQUIRY); nlbsOperationHistoryMapper.getInsert(nlbsOperationHistory); //如果返回的状态是待评估,则生成待办任务 if(Constants.BPS_ORDER_STATUS_PENDING_EVALUATION.equals(status)){ nlbsTODOService.insertTodoTask(bpsCode, userNo, address); } List<Map> priceList = (List<Map>) remoteBodyMap.get(Fields.PARAM_COMPANY_PARAM_LIST); if(priceList != null){ List<Map> priceWihtHandleList = new ArrayList<Map>(); for(Map map : priceList){ String companyPriceStatus = (String) map.get(Fields.PARAM_STATUS); //如果是人工的估价或者为风控或者管理员,则保留价格,否则对前端不显示单个估价公司的评估价格,只显示评估状态; if(!isAdmin){ map.remove(Fields.PARAM_PRICE);//对前端不显示单个估价公司的评估价格,只显示评估状态; } map.put(Fields.PARAM_STATUS, BPSStatus.getNameByCode(companyPriceStatus)); priceWihtHandleList.add(map); } remoteBodyMap.put(Fields.PARAM_COMPANY_PARAM_LIST, priceWihtHandleList); } remoteBodyMap.put(Fields.PARAM_ASSESSMENT_STATUS, BPSStatus.getNameByCode(status)); } return remoteReturnMap; } /** * 别墅估价 * @param paramMap * @return * @throws Exception */ @Override public Map villaInquiry(Map paramMap) throws Exception { //Step 1 解析入参 Map<String, Object> headMap = new HashMap<String, Object>(); Map<String, Object> bodyMap = new HashMap<String, Object>(); headMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_HEAD); bodyMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_BODY); //Step 1.1 整理参数存储本地库--NlbsInquiryApply、 List<Map> paramList = (List<Map>) bodyMap.get(Fields.PARAM_COMPANY_PARAM_LIST); String userNo = (String) bodyMap.get(Fields.PARAM_USER_ID); String cityCode = (String) bodyMap.get(Fields.PARAM_CITY_CODE); String houseTypeCode = (String) bodyMap.get(Fields.PARAM_HOUSE_TYPE_CODE); String inquiryCode = CommonUtil.getCurrentTimeStr("NLBS-",""); String address = ""; NlbsInquiryApply nlbsInquiryApply = new NlbsInquiryApply(); nlbsInquiryApply.setCode(inquiryCode); nlbsInquiryApply.setUserNo(userNo); nlbsInquiryApply.setCityCode(cityCode); nlbsInquiryApply.setHouseType(houseTypeCode); nlbsInquiryApply.setAutoPrice(Constants.INQUIRY_TYPE_AUTO_PRICE); nlbsInquiryApply.setStatus(Constants.BPS_ORDER_STATUS_EVALUATING); if (paramList != null) { for (Map map : paramList) { String companyCode = (String) map.get(Fields.PARAM_COMPANY_CODE); if(AppraisalCompanys.WORLD_UNION.getCode().equals(companyCode)){ String paramAddress = (String) map.get(Fields.PARAM_ADDRESS); String area = (String) map.get(Fields.PARAM_AREA); address = paramAddress == null ? "" : paramAddress; nlbsInquiryApply.setAddress(address); nlbsInquiryApply.setArea(new BigDecimal(area == null ? "0" : area)); } } } nlbsInquiryApplyMapper.getInsert(nlbsInquiryApply); //Step 2 调用BPS,询价 Map remoteParamMap = new HashMap(); headMap.remove(Fields.PARAM_CLIENTTIMESTAMP); headMap.remove(Fields.PARAM_USER_NO); bodyMap.put(Fields.PARAM_SOURCE_SYSTEM, "nlbs"); remoteParamMap.put(Fields.PARAM_MESSAGE_HEAD, headMap); remoteParamMap.put(Fields.PARAM_MESSAGE_BODY, bodyMap); Map remoteReturnMap = remoteBpsService.callService(remoteParamMap); Map<String, Object> remoteHeadMap = new HashMap<String, Object>(); Map<String, Object> remoteBodyMap = new HashMap<String, Object>(); remoteHeadMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_HEAD); remoteBodyMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_BODY); String remoteReturnCode = (String) remoteHeadMap.get(Fields.PARAM_MESSAGE_ERR_CODE); //Step 3 调用BPS返回,更新本地库,保存操作历史,修改出参 if(ReturnCode.SUCCESS_CODE.equals(remoteReturnCode)){ //判断当前用户是不是超管或者风控等内部用户 List<String> roleList = new ArrayList<String>(); roleList.add(Constants.ROLE_SUPPER_MANAGER); roleList.add(Constants.ROLE_SYSTEM_MANAGER); roleList.add(Constants.ROLE_BUSINESS_MANAGER); boolean isAdmin = commonService.isAdministrator(userNo, roleList); if(!isAdmin) { NlbsDistributor nlbsDistributor = nlbsDistributorMapper.selectDistributorByUserNo(userNo); if (nlbsDistributor != null && Constants.DISTRIBUTOR_VILIO_CODE.equals(nlbsDistributor.getCode())) { isAdmin = true; } } String bpsCode = remoteBodyMap.get(Fields.PARAM_SERIAL_NO) == null ? "" : remoteBodyMap.get(Fields.PARAM_SERIAL_NO).toString(); String status = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS).toString(); String price = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE) == null ? "0" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE).toString(); String priceTime = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME).toString(); nlbsInquiryApply.setBpsCode(bpsCode); nlbsInquiryApply.setStatus(status); nlbsInquiryApply.setPrice(new BigDecimal(price)); nlbsInquiryApply.setPriceTime(DateUtil.parseDateTime3(priceTime)); nlbsInquiryApplyMapper.getUpdate(nlbsInquiryApply); NlbsOperationHistory nlbsOperationHistory = new NlbsOperationHistory(); nlbsOperationHistory.setOperater(userNo); nlbsOperationHistory.setSerialNo(bpsCode); nlbsOperationHistory.setSystemCode("bps"); nlbsOperationHistory.setOperateType(Constants.OPERATION_SUBMIT_INQUIRY); nlbsOperationHistoryMapper.getInsert(nlbsOperationHistory); //如果返回的状态是待评估,则生成待办任务 if(Constants.BPS_ORDER_STATUS_PENDING_EVALUATION.equals(status)){ nlbsTODOService.insertTodoTask(bpsCode, userNo, address); } List<Map> priceList = (List<Map>) remoteBodyMap.get(Fields.PARAM_COMPANY_PARAM_LIST); if(priceList != null){ List<Map> priceWihtHandleList = new ArrayList<Map>(); for(Map map : priceList){ String companyPriceStatus = (String) map.get(Fields.PARAM_STATUS); //如果是人工的估价或者为风控或者管理员,则保留价格,否则对前端不显示单个估价公司的评估价格,只显示评估状态; if(!isAdmin){ map.remove(Fields.PARAM_PRICE);//对前端不显示单个估价公司的评估价格,只显示评估状态; } map.put(Fields.PARAM_STATUS, BPSStatus.getNameByCode(companyPriceStatus)); priceWihtHandleList.add(map); } remoteBodyMap.put(Fields.PARAM_COMPANY_PARAM_LIST, priceWihtHandleList); } remoteBodyMap.put(Fields.PARAM_ASSESSMENT_STATUS, BPSStatus.getNameByCode(status)); } return remoteReturnMap; } /** * 人工询价 * @param paramMap * @return * @throws Exception */ @Override public Map manualInquiry(Map paramMap) throws Exception { //Step 1 解析入参 Map<String, Object> headMap = new HashMap<String, Object>(); Map<String, Object> bodyMap = new HashMap<String, Object>(); headMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_HEAD); bodyMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_BODY); //Step 1.1 整理参数存储本地库--NlbsInquiryApply、 String userNo = (String) bodyMap.get(Fields.PARAM_USER_ID); String cityCode = (String) bodyMap.get(Fields.PARAM_CITY_CODE); String address = (String) bodyMap.get(Fields.PARAM_ADDRESS); String inquiryCode = CommonUtil.getCurrentTimeStr("NLBS-",""); NlbsInquiryApply nlbsInquiryApply = new NlbsInquiryApply(); nlbsInquiryApply.setCode(inquiryCode); nlbsInquiryApply.setUserNo(userNo); nlbsInquiryApply.setCityCode(cityCode); nlbsInquiryApply.setAutoPrice(Constants.INQUIRY_TYPE_MANNAL_PRICE); nlbsInquiryApply.setAddress(address); nlbsInquiryApply.setStatus(Constants.BPS_ORDER_STATUS_EVALUATING); nlbsInquiryApplyMapper.getInsert(nlbsInquiryApply); //Step 2 调用BPS,询价 Map remoteParamMap = new HashMap(); headMap.remove(Fields.PARAM_CLIENTTIMESTAMP); headMap.remove(Fields.PARAM_USER_NO); bodyMap.put(Fields.PARAM_SOURCE_SYSTEM, "nlbs"); remoteParamMap.put(Fields.PARAM_MESSAGE_HEAD, headMap); remoteParamMap.put(Fields.PARAM_MESSAGE_BODY, bodyMap); Map remoteReturnMap = remoteBpsService.callService(remoteParamMap); Map<String, Object> remoteHeadMap = new HashMap<String, Object>(); Map<String, Object> remoteBodyMap = new HashMap<String, Object>(); remoteHeadMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_HEAD); remoteBodyMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_BODY); String remoteReturnCode = (String) remoteHeadMap.get(Fields.PARAM_MESSAGE_ERR_CODE); //Step 3 调用BPS返回,更新本地库,保存操作历史,修改出参 if(ReturnCode.SUCCESS_CODE.equals(remoteReturnCode)){ //整理BPS返回的关键参数 String bpsCode = remoteBodyMap.get(Fields.PARAM_SERIAL_NO) == null ? "0" : remoteBodyMap.get(Fields.PARAM_SERIAL_NO).toString(); String status = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS) == null ? "0" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS).toString(); String price = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE) == null ? "0" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE).toString(); String priceTime = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME) == null ? "0" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME).toString(); //更新询价记录 nlbsInquiryApply.setBpsCode(bpsCode); nlbsInquiryApply.setStatus(status); nlbsInquiryApply.setPrice(new BigDecimal(price)); nlbsInquiryApply.setPriceTime(DateUtil.parseDateTime3(priceTime)); nlbsInquiryApplyMapper.getUpdate(nlbsInquiryApply); //插入询价历史操作记录 NlbsOperationHistory nlbsOperationHistory = new NlbsOperationHistory(); nlbsOperationHistory.setOperater(userNo); nlbsOperationHistory.setSerialNo(bpsCode); nlbsOperationHistory.setSystemCode("bps"); nlbsOperationHistory.setOperateType(Constants.OPERATION_SUBMIT_INQUIRY); nlbsOperationHistoryMapper.getInsert(nlbsOperationHistory); //如果返回的状态是待评估,则生成待办任务 if(Constants.BPS_ORDER_STATUS_PENDING_EVALUATION.equals(status)){ nlbsTODOService.insertTodoTask(bpsCode, userNo, address); } remoteBodyMap.put(Fields.PARAM_ASSESSMENT_STATUS, BPSStatus.getNameByCode(status)); } return remoteReturnMap; } /** * 查询询价记录列表 * @param paramMap--只接受bodyMap即可 * @return * @throws Exception */ @Override public Map queryInquiryList(Map paramMap) throws Exception { Map returnMap = new HashMap(); List<Map> inquiryApplyList = new ArrayList<Map>(); String userNo = null != paramMap.get(Fields.PARAM_USER_NO) ? paramMap.get(Fields.PARAM_USER_NO).toString() : ""; Integer pageNo = null != paramMap.get(Fields.PARAM_PAGE_NO) ? new Integer(paramMap.get(Fields.PARAM_PAGE_NO).toString()) : 1; Integer pageSize = null != paramMap.get(Fields.PARAM_PAGE_SIZE) ? new Integer(paramMap.get(Fields.PARAM_PAGE_SIZE).toString()) : 10; //Step 1判断当前用户是不是超管 List<String> roleList = new ArrayList<String>(); roleList.add(Constants.ROLE_SUPPER_MANAGER); roleList.add(Constants.ROLE_SYSTEM_MANAGER); roleList.add(Constants.ROLE_BUSINESS_MANAGER); boolean isAdmin = commonService.isAdministrator(userNo, roleList); //Step2 获取分页查询结果 if(isAdmin){ //Step 2.1如果是管理员,则所有询价记录可见 PageHelper.startPage(pageNo, pageSize); inquiryApplyList = nlbsInquiryApplyMapper.getAllList(paramMap); } else { //Step 2.2如果不是管理员,则按需查找 //Step 2.2.1查找当前用户所有下属用户 List<String> userNoList = new ArrayList<String>(); userNoList.add(""); List<NlbsUser> nlbsUserList = commonService.selectChildrenListUser(userNo); if(nlbsUserList != null){ for(NlbsUser nu : nlbsUserList){ userNoList.add(nu.getUserNo()); } } paramMap.put(Fields.PARAM_USER_LIST, userNoList); //Step 2.2.2查询列表 PageHelper.startPage(pageNo, pageSize); inquiryApplyList = nlbsInquiryApplyMapper.getInquiryApplyList(paramMap); } PageInfo pageInfo = new PageInfo(inquiryApplyList); //Step 3 查看当前用户是否具备录入询价结果权限 NlbsPendingUserDistributor nlbsPendingUserDistributor = new NlbsPendingUserDistributor(); nlbsPendingUserDistributor.setUserNo(userNo); List<NlbsPendingUserDistributor> distributorList = nlbsPendingUserDistributorMapper.getList(nlbsPendingUserDistributor); boolean displayInquiry = true; if (distributorList == null || distributorList.size() == 0) { displayInquiry = false; } List<Map> returnInquiryApplyList = new ArrayList<Map>(); if (inquiryApplyList != null) { for (Map map : inquiryApplyList) { //转换状态码,更改price类型。 String price = ""; BigDecimal priceBigD = (BigDecimal) map.get(Fields.PARAM_PRICE); if(priceBigD.compareTo(BigDecimal.ZERO) == 1){ price = priceBigD.toString(); } String status = map.get(Fields.PARAM_STATUS) != null ? (map.get(Fields.PARAM_STATUS).toString()) : ""; String pendingUserNo = map.get(Fields.PARAM_PENDING_USER_NO) != null ? (map.get(Fields.PARAM_PENDING_USER_NO).toString()) : ""; map.put(Fields.PARAM_STATUS, BPSStatus.getNameByCode(status)); if(BPSStatus.ORDER_STATUS_EVALUATED.getCode().equals(status)){ map.put(Fields.PARAM_PRICE, price); } else { map.put(Fields.PARAM_PRICE, "");//如果不是以评估状态,价格显示- } if(displayInquiry && ("".equals(pendingUserNo) || userNo.equals(pendingUserNo)) && BPSStatus.ORDER_STATUS_PENDING_EVALUATION.getCode().equals(status)){ map.put(Fields.PARAM_DISPLAY_INQUIRY, "Y"); } else { map.put(Fields.PARAM_DISPLAY_INQUIRY, "N"); } returnInquiryApplyList.add(map); } } returnMap.put(Fields.PARAM_INQUIRY_APPLY_LIST,returnInquiryApplyList); returnMap.put(Fields.PARAM_PAGES,pageInfo.getPages()); returnMap.put(Fields.PARAM_TOTAL,pageInfo.getTotal()); returnMap.put(Fields.PARAM_CURRENT_PAGE,pageInfo.getPageNum()); returnMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); returnMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "获取询价记录列表成功!"); return returnMap; } /** * 查询询价记录详情 * @param paramMap * @return * @throws Exception */ @Override public Map queryInquiryInfo(Map paramMap) throws Exception { Map<String, Object> headMap = new HashMap<String, Object>(); Map<String, Object> bodyMap = new HashMap<String, Object>(); headMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_HEAD); bodyMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_BODY); String userNo = null != headMap.get(Fields.PARAM_USER_NO) ? headMap.get(Fields.PARAM_USER_NO).toString() : ""; Map remoteParamMap = new HashMap(); headMap.remove(Fields.PARAM_CLIENTTIMESTAMP); headMap.remove(Fields.PARAM_USER_NO); bodyMap.put(Fields.PARAM_SOURCE_SYSTEM, "nlbs"); remoteParamMap.put(Fields.PARAM_MESSAGE_HEAD, headMap); remoteParamMap.put(Fields.PARAM_MESSAGE_BODY, bodyMap); Map remoteReturnMap = remoteBpsService.callService(remoteParamMap); Map<String, Object> remoteHeadMap = new HashMap<String, Object>(); Map<String, Object> remoteBodyMap = new HashMap<String, Object>(); remoteHeadMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_HEAD); remoteBodyMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_BODY); String remoteReturnCode = (String) remoteHeadMap.get(Fields.PARAM_MESSAGE_ERR_CODE); //调用BPS返回,更新本地库,保存操作历史,修改出参 if(ReturnCode.SUCCESS_CODE.equals(remoteReturnCode)){ //判断当前用户是不是超管或者风控等内部用户 List<String> roleList = new ArrayList<String>(); roleList.add(Constants.ROLE_SUPPER_MANAGER); roleList.add(Constants.ROLE_SYSTEM_MANAGER); roleList.add(Constants.ROLE_BUSINESS_MANAGER); boolean isAdmin = commonService.isAdministrator(userNo, roleList); if(!isAdmin) { NlbsDistributor nlbsDistributor = nlbsDistributorMapper.selectDistributorByUserNo(userNo); if (nlbsDistributor != null && Constants.DISTRIBUTOR_VILIO_CODE.equals(nlbsDistributor.getCode())) { isAdmin = true; } } String status = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS).toString(); List<Map> priceList = (List<Map>) remoteBodyMap.get(Fields.PARAM_COMPANY_PARAM_LIST); if(priceList != null){ for(Map map : priceList){ String companyPriceStatus = (String) map.get(Fields.PARAM_STATUS); String autoPrice = (String) map.get(Fields.PARAM_AUTO_PRICE); //如果是人工的估价或者为风控或者管理员,则保留价格,否则对前端不显示单个估价公司的评估价格,只显示评估状态; if(!Constants.INQUIRY_TYPE_MANNAL_PRICE.equals(autoPrice) && !isAdmin){ map.remove(Fields.PARAM_PRICE); } map.put(Fields.PARAM_STATUS, BPSStatus.getNameByCode(companyPriceStatus)); } } remoteBodyMap.put(Fields.PARAM_ASSESSMENT_STATUS, BPSStatus.getNameByCode(status)); } return remoteReturnMap; } /** * 查询操作历史列表--只接受bodyMap * @param paramMap * @return * @throws Exception */ @Override public Map queryOperateHistory(Map paramMap) throws Exception { Map returnMap = new HashMap(); String serialNo = (String) paramMap.get(Fields.PARAM_SERIAL_NO); List<Map<String, Object>> historyList = nlbsOperationHistoryMapper.getListBySerialNo(serialNo); if(historyList == null){ historyList = new ArrayList<Map<String, Object>>(); } returnMap.put(Fields.PARAM_OPERATION_HISTORY_LIST, historyList); returnMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); returnMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "成功查询询价历史操作列表!"); return returnMap; } /** * 更新询价结果,包括状态,价格,时间等 -- 只传bodyMap即可 * @param paramMap * @return * @throws Exception */ @Override public Map updateInquiryResult(Map paramMap) throws Exception { //Step 1 入参检查 List<String> requiredFieldList = new ArrayList<String>(); requiredFieldList.add(Fields.PARAM_SERIAL_NO); requiredFieldList.add(Fields.PARAM_ASSESSMENT_STATUS); CommonUtil.checkRequiredFields(paramMap, requiredFieldList); Map returnMap = new HashMap(); String bpsCode = paramMap.get(Fields.PARAM_SERIAL_NO) == null ? "" : paramMap.get(Fields.PARAM_SERIAL_NO).toString(); String status = paramMap.get(Fields.PARAM_ASSESSMENT_STATUS) == null ? "" : paramMap.get(Fields.PARAM_ASSESSMENT_STATUS).toString(); String price = paramMap.get(Fields.PARAM_ASSESSMENT_PRICE) == null ? "-1" : paramMap.get(Fields.PARAM_ASSESSMENT_PRICE).toString(); String priceTime = paramMap.get(Fields.PARAM_ASSESSMENT_TIME) == null ? "" : paramMap.get(Fields.PARAM_ASSESSMENT_TIME).toString(); String autoPrice = paramMap.get(Fields.PARAM_AUTO_PRICE) == null ? "" : paramMap.get(Fields.PARAM_AUTO_PRICE).toString(); NlbsInquiryApply nlbsInquiryApply = new NlbsInquiryApply(); nlbsInquiryApply.setBpsCode(bpsCode); nlbsInquiryApply.setStatus(status); nlbsInquiryApply.setPrice(new BigDecimal(price)); nlbsInquiryApply.setPriceTime(DateUtil.parseDateTime3(priceTime)); nlbsInquiryApply.setAutoPrice(autoPrice); nlbsInquiryApplyMapper.getUpdateByBPSCode(nlbsInquiryApply); //如果返回的状态是待评估,则生成待办任务 if(Constants.BPS_ORDER_STATUS_PENDING_EVALUATION.equals(status) && StringUtils.isNotBlank(bpsCode)){ nlbsInquiryApply = nlbsInquiryApplyMapper.getBeanBySerialNo(bpsCode); nlbsTODOService.insertTodoTask(bpsCode, nlbsInquiryApply.getUserNo(), nlbsInquiryApply.getAddress()); } returnMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); returnMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "成功查询询价历史操作列表!"); return returnMap; } /** * 录入评估价---提交 * @param paramMap * @return * @throws Exception */ @Override public Map inputInquiryPrice(Map paramMap) throws Exception { //Step 1 解析入参 Map<String, Object> headMap = new HashMap<String, Object>(); Map<String, Object> bodyMap = new HashMap<String, Object>(); headMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_HEAD); bodyMap = (Map<String, Object>) paramMap.get(Fields.PARAM_MESSAGE_BODY); String userNo = (String) bodyMap.get(Fields.PARAM_USER_ID); String serialNo = (String) bodyMap.get(Fields.PARAM_SERIAL_NO); NlbsInquiryApply nlbsInquiryApply = nlbsInquiryApplyMapper.getBeanBySerialNo(serialNo); String pendingUserNo = nlbsInquiryApply == null ? null : nlbsInquiryApply.getPendingUserNo(); if (StringUtils.isNotBlank(pendingUserNo) && !(pendingUserNo.equals(userNo))) { NlbsUser nlbsUser = commonService.queryNlbsUserByUserNoIgnoreStatus(pendingUserNo); throw new HHBizException(ReturnCode.DUPLICATE_INPUT_PRICE, "该笔查询已由用户" + nlbsUser.getFullName() + "评估。"); } //Step 2 调用BPS,询价 Map remoteParamMap = new HashMap(); headMap.remove(Fields.PARAM_CLIENTTIMESTAMP); headMap.remove(Fields.PARAM_USER_NO); bodyMap.put(Fields.PARAM_SOURCE_SYSTEM, "nlbs"); remoteParamMap.put(Fields.PARAM_MESSAGE_HEAD, headMap); remoteParamMap.put(Fields.PARAM_MESSAGE_BODY, bodyMap); Map remoteReturnMap = remoteBpsService.callService(remoteParamMap); Map<String, Object> remoteHeadMap = new HashMap<String, Object>(); Map<String, Object> remoteBodyMap = new HashMap<String, Object>(); remoteHeadMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_HEAD); remoteBodyMap = (Map<String, Object>) remoteReturnMap.get(Fields.PARAM_MESSAGE_BODY); String remoteReturnCode = (String) remoteHeadMap.get(Fields.PARAM_MESSAGE_ERR_CODE); //Step 3 调用BPS返回,更新本地库,保存操作历史,修改出参 if(ReturnCode.SUCCESS_CODE.equals(remoteReturnCode)){ //判断当前用户是不是超管或者风控等内部用户 List<String> roleList = new ArrayList<String>(); roleList.add(Constants.ROLE_SUPPER_MANAGER); roleList.add(Constants.ROLE_SYSTEM_MANAGER); roleList.add(Constants.ROLE_BUSINESS_MANAGER); boolean isAdmin = commonService.isAdministrator(userNo, roleList); if(!isAdmin) { NlbsDistributor nlbsDistributor = nlbsDistributorMapper.selectDistributorByUserNo(userNo); if (nlbsDistributor != null && Constants.DISTRIBUTOR_VILIO_CODE.equals(nlbsDistributor.getCode())) { isAdmin = true; } } //整理BPS返回的关键参数 String bpsCode = remoteBodyMap.get(Fields.PARAM_SERIAL_NO) == null ? "" : remoteBodyMap.get(Fields.PARAM_SERIAL_NO).toString(); String status = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_STATUS).toString(); String price = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE) == null ? "-1" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_PRICE).toString(); String autoPrice = remoteBodyMap.get(Fields.PARAM_AUTO_PRICE) == null ? "" : remoteBodyMap.get(Fields.PARAM_AUTO_PRICE).toString(); String priceTime = remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME) == null ? "" : remoteBodyMap.get(Fields.PARAM_ASSESSMENT_TIME).toString(); //更新询价记录表 nlbsInquiryApply = new NlbsInquiryApply(); nlbsInquiryApply.setBpsCode(bpsCode); nlbsInquiryApply.setStatus(status); nlbsInquiryApply.setStatus(status); nlbsInquiryApply.setPrice(new BigDecimal(price)); nlbsInquiryApply.setAutoPrice(autoPrice); nlbsInquiryApply.setPriceTime(DateUtil.parseDateTime3(priceTime)); nlbsInquiryApplyMapper.getUpdateByBPSCode(nlbsInquiryApply); //插入询价操作历史表 NlbsOperationHistory nlbsOperationHistory = new NlbsOperationHistory(); nlbsOperationHistory.setOperater(userNo); nlbsOperationHistory.setSerialNo(bpsCode); nlbsOperationHistory.setSystemCode("bps"); nlbsOperationHistory.setOperateType(Constants.OPERATION_INPUT_INQUIRY_PRICE); nlbsOperationHistoryMapper.getInsert(nlbsOperationHistory); //如果返回的状态是待评估,则生成待办任务 if(Constants.BPS_ORDER_STATUS_PENDING_EVALUATION.equals(status)){ nlbsTODOService.insertTodoTask(nlbsInquiryApply.getBpsCode(), nlbsInquiryApply.getUserNo(), nlbsInquiryApply.getAddress()); } //如果返回的状态为已评估,则可以删除自己的待办任务 if(Constants.BPS_ORDER_STATUS_PENDING_EVALUATION.equals(status)){ nlbsTODOService.deleteTask(nlbsInquiryApply.getBpsCode(), nlbsInquiryApply.getUserNo(), false); } List<Map> priceList = (List<Map>) remoteBodyMap.get(Fields.PARAM_COMPANY_PARAM_LIST); if(priceList != null){ List<Map> priceWihtHandleList = new ArrayList<Map>(); for(Map map : priceList){ String companyPriceStatus = (String) map.get(Fields.PARAM_STATUS); //如果是人工的估价或者为风控或者管理员,则保留价格,否则对前端不显示单个估价公司的评估价格,只显示评估状态; if(!Constants.INQUIRY_TYPE_MANNAL_PRICE.equals(autoPrice) && !isAdmin){ map.remove(Fields.PARAM_PRICE);//对前端不显示单个估价公司的评估价格,只显示评估状态; } map.put(Fields.PARAM_STATUS, BPSStatus.getNameByCode(companyPriceStatus)); priceWihtHandleList.add(map); } remoteBodyMap.put(Fields.PARAM_COMPANY_PARAM_LIST, priceWihtHandleList); } remoteBodyMap.put(Fields.PARAM_ASSESSMENT_STATUS, BPSStatus.getNameByCode(status)); } return remoteReturnMap; } /** * 认领任务 * @param paramMap ---只传bodyMap * @return * @throws Exception */ @Override public Map claimInquiryTask(Map paramMap) throws Exception { //Step 1 入参检查 List<String> requiredFieldList = new ArrayList<String>(); requiredFieldList.add(Fields.PARAM_SERIAL_NO); requiredFieldList.add(Fields.PARAM_USER_NO); CommonUtil.checkRequiredFields(paramMap, requiredFieldList); Map returnMap = new HashMap(); String bpsCode = (String) paramMap.get(Fields.PARAM_SERIAL_NO); String userNo = (String) paramMap.get(Fields.PARAM_USER_NO); NlbsInquiryApply nlbsInquiryApply = nlbsInquiryApplyMapper.getBeanBySerialNo(bpsCode); if(nlbsInquiryApply != null){ String pendingUserNo = nlbsInquiryApply.getPendingUserNo(); if(StringUtils.isBlank(pendingUserNo)){ nlbsInquiryApply.setPendingUserNo(userNo); nlbsInquiryApplyMapper.getUpdateForClaim(nlbsInquiryApply); nlbsTODOService.deleteTask(nlbsInquiryApply.getBpsCode(), nlbsInquiryApply.getUserNo(), true); } // 极端情况下会出现以下情况(决定在列表页是否允许点进详情) if(StringUtils.isNotBlank(pendingUserNo) && !userNo.equals(pendingUserNo)){ //查询究竟是谁先领了任务 NlbsUser nlbsUser = commonService.queryNlbsUserByUserNoIgnoreStatus(pendingUserNo); throw new HHBizException(ReturnCode.DUPLICATE_INPUT_PRICE, "该笔查询已由用户" + nlbsUser.getFullName() + "评估。"); } } else { throw new HHBizException(ReturnCode.INQUIRY_NO_EXIST, "该笔估价单不存在"); } returnMap.put(Fields.PARAM_MESSAGE_ERR_CODE, ReturnCode.SUCCESS_CODE); returnMap.put(Fields.PARAM_MESSAGE_ERR_MESG, "认领成功!"); return returnMap; } }
package com.zengjx.mybatis.utils; import com.zengjx.mybatis.cfg.Configuration; import com.zengjx.mybatis.cfg.Mapper; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; public class XMLConfigBuilder { /** * 解析xml,把所有配置信息封装到Configuration对象 * @param inputStream xml文件的流 * @return Configuration */ public Configuration parse(InputStream inputStream) { //读取核心配置文件里的数据库连接信息,封装到Configuration对象 Configuration configuration = new Configuration(); try { //1. 创建一个解析器对象 SAXReader reader = new SAXReader(); //2. 读取xml,得到Document Document document = reader.read(inputStream); //3. 获取数据库连接信息 Element element = (Element) document.selectSingleNode("//property[@name='driver']"); String value = element.attributeValue("value"); configuration.setDriver(value); element = (Element) document.selectSingleNode("//property[@name='url']"); value = element.attributeValue("value"); configuration.setUrl(value); element = (Element) document.selectSingleNode("//property[@name='username']"); value = element.attributeValue("value"); configuration.setUsername(value); element = (Element) document.selectSingleNode("//property[@name='password']"); value = element.attributeValue("value"); configuration.setPassword(value); //封装每个映射配置文件里的每个statement的信息:SQL语句,结果集封装类型 List<Node> nodes = document.selectNodes("//mappers/mapper"); for (Node node : nodes) { element = (Element) node; //获取每个映射配置文件的路径 String resource = element.attributeValue("resource"); //调用方法,把每个映射配置文件的信息,封装到Configuration里 getMappers(resource, configuration); } } catch (DocumentException e) { e.printStackTrace(); } return configuration; } /** * 封装每个映射配置文件 * @param resource xml配置文件的路径 * @param configuration 配置信息对象 */ private void getMappers(String resource, Configuration configuration) { SAXReader reader = new SAXReader(); InputStream inputStream = Resources.getResourceAsStream(resource); try { Document document = reader.read(inputStream); Element rootElement = document.getRootElement(); //获取映射器的全限定类名 String mapperInterfaceClassName = rootElement.attributeValue("namespace"); //获取这个映射器里所有的statement List<Element> elements = rootElement.elements(); for (Element element : elements) { //获取方法名 String methodName = element.attributeValue("id"); //获取SQL语句 String sql = element.getText(); //获取结果集封装类型 String resultType = element.attributeValue("resultType"); //把sql和结果集类型封装成Mapper对象 Mapper mapper = new Mapper(); mapper.setSql(sql); mapper.setResultType(resultType); //把Mapper对象放到Configuration里 String key = mapperInterfaceClassName + "." +methodName; Map<String, Mapper> mappers = configuration.getMappers(); mappers.put(key, mapper); } } catch (DocumentException e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
package temakereso.service; import temakereso.entity.Account; import temakereso.helper.AccountDto; import temakereso.helper.AccountInputDto; import temakereso.helper.ForgotPasswordDto; import temakereso.helper.PasswordChangeDto; import temakereso.helper.PasswordResetDto; import java.util.Date; import java.util.List; public interface AccountService { /** * Saves a new account * * @param account account to be saved */ void createAccount(Account account); /** * Finds an account by its identifier. * * @param id identifier * @return the account with the given identifier */ Account getById(Long id); /** * Finds an account by its identifier. * * @param id identifier * @return the account data with the given identifier */ AccountDto findById(Long id); /** * After a successful login, last successful login date should be changed. * * @param id id of account */ void setSuccessfulLoginById(Long id); /** * Finds the accounts with administrator roles. * * @return list of accounts */ List<Account> findAdministrators(); List<Account> findStudentsToRemind(Date time); void archiveAccount(Account account); void generateForgotPasswordToken(ForgotPasswordDto forgotPasswordDto); void changePassword(PasswordResetDto passwordResetDto); void changePassword(Long id, PasswordChangeDto passwordChangeDto); void modifyAccount(Long id, AccountInputDto accountInputDto); }
package com.example.demo25; import androidx.appcompat.app.AppCompatActivity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; public class MainActivity extends AppCompatActivity { Intent serviceIntent; ServiceConnection serviceConnection; boolean isBound = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); serviceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName cName, IBinder service) { isBound = true; } public void onServiceDisconnected(ComponentName cName) { isBound = false; } }; serviceIntent = new Intent(this, MyService.class); serviceIntent.putExtra("MyData", "TEST SERVICE"); } public void onClickStart(View v) { startService(serviceIntent); } public void onClickStop(View v) { stopService(serviceIntent); } public void onBindService(View v) { Log.i("myLogs", "onDestroy"); bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE); } public void onUnbindService(View v) { Log.i("myLogs", "onDestroy"); unbindService(serviceConnection); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BEWB01PlanungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BOWB01PlanungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BRGW01PlanungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BRWB01PlanungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BandbeschichtungPlanungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.LokalerIdentType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGH1; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGH2; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGH3; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGN1; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGN2; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BEHGN3; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BENW01; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BRHGC1; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BRHGH1; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BRHGH2; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BRHGN1; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.BRNW01; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.CFO; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.DOCG01; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.DSNW01; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.EIIA01; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.EIQA01; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammzeileType.RegelverletzungListe; import java.io.StringWriter; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; public class ProgrammzeileTypeBuilder { public static String marshal(ProgrammzeileType programmzeileType) throws JAXBException { JAXBElement<ProgrammzeileType> jaxbElement = new JAXBElement<>(new QName("TESTING"), ProgrammzeileType.class , programmzeileType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private LokalerIdentType flsIdent; private Double ruestzeit; private XMLGregorianCalendar startzeitpunkt; private XMLGregorianCalendar endzeitpunkt; private Double laufzeit; private String bemerkungPlanung; private RegelverletzungListe regelverletzungListe; private CFO cFO; private BandbeschichtungPlanungType bEBB01; private BandbeschichtungPlanungType bEBB02; private BEHGH1 bEHGH1; private BEHGH2 bEHGH2; private BEHGH3 bEHGH3; private BEHGN1 bEHGN1; private BEHGN2 bEHGN2; private BEHGN3 bEHGN3; private BENW01 bENW01; private BEWB01PlanungType bEWB01; private BOWB01PlanungType bOWB01; private BRGW01PlanungType bRGW01; private BRHGC1 bRHGC1; private BRHGH1 bRHGH1; private BRHGH2 bRHGH2; private BRHGN1 bRHGN1; private BRNW01 bRNW01; private BRWB01PlanungType bRWB01; private DOCG01 dOCG01; private DSNW01 dSNW01; private BandbeschichtungPlanungType eIBB01; private EIIA01 eIIA01; private EIQA01 eIQA01; private BandbeschichtungPlanungType fEBB01; private BigInteger lfdNr; private BigInteger sequenzNr; private String tksIdent; public ProgrammzeileTypeBuilder setFlsIdent(LokalerIdentType value) { this.flsIdent = value; return this; } public ProgrammzeileTypeBuilder setRuestzeit(Double value) { this.ruestzeit = value; return this; } public ProgrammzeileTypeBuilder setStartzeitpunkt(XMLGregorianCalendar value) { this.startzeitpunkt = value; return this; } public ProgrammzeileTypeBuilder setEndzeitpunkt(XMLGregorianCalendar value) { this.endzeitpunkt = value; return this; } public ProgrammzeileTypeBuilder setLaufzeit(Double value) { this.laufzeit = value; return this; } public ProgrammzeileTypeBuilder setBemerkungPlanung(String value) { this.bemerkungPlanung = value; return this; } public ProgrammzeileTypeBuilder setRegelverletzungListe(RegelverletzungListe value) { this.regelverletzungListe = value; return this; } public ProgrammzeileTypeBuilder setCFO(CFO value) { this.cFO = value; return this; } public ProgrammzeileTypeBuilder setBEBB01(BandbeschichtungPlanungType value) { this.bEBB01 = value; return this; } public ProgrammzeileTypeBuilder setBEBB02(BandbeschichtungPlanungType value) { this.bEBB02 = value; return this; } public ProgrammzeileTypeBuilder setBEHGH1(BEHGH1 value) { this.bEHGH1 = value; return this; } public ProgrammzeileTypeBuilder setBEHGH2(BEHGH2 value) { this.bEHGH2 = value; return this; } public ProgrammzeileTypeBuilder setBEHGH3(BEHGH3 value) { this.bEHGH3 = value; return this; } public ProgrammzeileTypeBuilder setBEHGN1(BEHGN1 value) { this.bEHGN1 = value; return this; } public ProgrammzeileTypeBuilder setBEHGN2(BEHGN2 value) { this.bEHGN2 = value; return this; } public ProgrammzeileTypeBuilder setBEHGN3(BEHGN3 value) { this.bEHGN3 = value; return this; } public ProgrammzeileTypeBuilder setBENW01(BENW01 value) { this.bENW01 = value; return this; } public ProgrammzeileTypeBuilder setBEWB01(BEWB01PlanungType value) { this.bEWB01 = value; return this; } public ProgrammzeileTypeBuilder setBOWB01(BOWB01PlanungType value) { this.bOWB01 = value; return this; } public ProgrammzeileTypeBuilder setBRGW01(BRGW01PlanungType value) { this.bRGW01 = value; return this; } public ProgrammzeileTypeBuilder setBRHGC1(BRHGC1 value) { this.bRHGC1 = value; return this; } public ProgrammzeileTypeBuilder setBRHGH1(BRHGH1 value) { this.bRHGH1 = value; return this; } public ProgrammzeileTypeBuilder setBRHGH2(BRHGH2 value) { this.bRHGH2 = value; return this; } public ProgrammzeileTypeBuilder setBRHGN1(BRHGN1 value) { this.bRHGN1 = value; return this; } public ProgrammzeileTypeBuilder setBRNW01(BRNW01 value) { this.bRNW01 = value; return this; } public ProgrammzeileTypeBuilder setBRWB01(BRWB01PlanungType value) { this.bRWB01 = value; return this; } public ProgrammzeileTypeBuilder setDOCG01(DOCG01 value) { this.dOCG01 = value; return this; } public ProgrammzeileTypeBuilder setDSNW01(DSNW01 value) { this.dSNW01 = value; return this; } public ProgrammzeileTypeBuilder setEIBB01(BandbeschichtungPlanungType value) { this.eIBB01 = value; return this; } public ProgrammzeileTypeBuilder setEIIA01(EIIA01 value) { this.eIIA01 = value; return this; } public ProgrammzeileTypeBuilder setEIQA01(EIQA01 value) { this.eIQA01 = value; return this; } public ProgrammzeileTypeBuilder setFEBB01(BandbeschichtungPlanungType value) { this.fEBB01 = value; return this; } public ProgrammzeileTypeBuilder setLfdNr(BigInteger value) { this.lfdNr = value; return this; } public ProgrammzeileTypeBuilder setSequenzNr(BigInteger value) { this.sequenzNr = value; return this; } public ProgrammzeileTypeBuilder setTksIdent(String value) { this.tksIdent = value; return this; } public ProgrammzeileType build() { ProgrammzeileType result = new ProgrammzeileType(); result.setFlsIdent(flsIdent); result.setRuestzeit(ruestzeit); result.setStartzeitpunkt(startzeitpunkt); result.setEndzeitpunkt(endzeitpunkt); result.setLaufzeit(laufzeit); result.setBemerkungPlanung(bemerkungPlanung); result.setRegelverletzungListe(regelverletzungListe); result.setCFO(cFO); result.setBEBB01(bEBB01); result.setBEBB02(bEBB02); result.setBEHGH1(bEHGH1); result.setBEHGH2(bEHGH2); result.setBEHGH3(bEHGH3); result.setBEHGN1(bEHGN1); result.setBEHGN2(bEHGN2); result.setBEHGN3(bEHGN3); result.setBENW01(bENW01); result.setBEWB01(bEWB01); result.setBOWB01(bOWB01); result.setBRGW01(bRGW01); result.setBRHGC1(bRHGC1); result.setBRHGH1(bRHGH1); result.setBRHGH2(bRHGH2); result.setBRHGN1(bRHGN1); result.setBRNW01(bRNW01); result.setBRWB01(bRWB01); result.setDOCG01(dOCG01); result.setDSNW01(dSNW01); result.setEIBB01(eIBB01); result.setEIIA01(eIIA01); result.setEIQA01(eIQA01); result.setFEBB01(fEBB01); result.setLfdNr(lfdNr); result.setSequenzNr(sequenzNr); result.setTksIdent(tksIdent); return result; } }
package com.example.user.myapplication.Menu.Navigation; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.media.Image; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.util.Base64; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.example.user.myapplication.Game.FiveDiceGame; import com.example.user.myapplication.R; import java.io.File; import java.util.ArrayList; import static com.example.user.myapplication.R.id.Screenshot; import static com.example.user.myapplication.R.id.imageView; public class RecordsActivity extends AppCompatActivity { ImageView imageview; FiveDiceGame fiveDiceGame; boolean whichGame; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; private static final String PREFS_NAME = "PREFS_NAME"; private static final String PREFS_SCORE = "PREFS_SCORE"; // List<Score> scoreStrings = new ArrayList<Score>(); // String[] exScores = scores.split("\\|"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_records); // highscore_headers = String.format("%7s","rank") + // String.format("%11s","name") + // String.format("%10s","score") + // String.format("%5s","lvl"); String nickname; sharedPreferences = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE); TextView shownickname = (TextView) findViewById(R.id.nicknameOne); nickname = shownickname.getText().toString(); nickname = sharedPreferences.getString(PREFS_NAME, nickname); shownickname.setText(nickname); // for(String eSc : exScores){ // String[] parts = eSc.split(" - "); // scoreStrings.add(new Score(parts[0], Integer.parseInt(parts[1]))); // } // Score newScore = new Score(exScore); // scoreStrings.add(newScore); sharedPreferences = this.getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE); editor = sharedPreferences.edit(); int scoreOne = sharedPreferences.getInt("PREFS_SCORE", 0); editor.putInt("PREFS_SCORE", scoreOne); editor.apply(); TextView showscore = (TextView) findViewById(R.id.ScoreOne); showscore.setText("" + scoreOne); Toast.makeText(RecordsActivity.this, "Score Total " + scoreOne, Toast.LENGTH_SHORT).show(); whichGame = sharedPreferences.getBoolean("WHICH_GAME", true); if (whichGame) { TextView whichGame = (TextView) findViewById(R.id.TitleScore1); whichGame.setText("5 Game"); } else { TextView whichGame = (TextView) findViewById(R.id.TitleScore1); whichGame.setText("6 Game"); } FloatingActionButton ScoreOnePlus1 = (FloatingActionButton) findViewById(R.id.ScoreOnePlus1); ScoreOnePlus1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final LayoutInflater inflater = getLayoutInflater(); final View layout = inflater.inflate(R.layout.screenshot, (ViewGroup) findViewById(R.id.Screenshot)); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_LONG); toast.setView(layout); toast.show(); } }); } // Intent i = new Intent(getApplicationContext(), ChoiceGame.class); // startActivity(i); public Bitmap decodeBase64(String input) { byte[] decodedByte = Base64.decode(input, 0); return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); } private void openScreenshot(File imageFile) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(imageFile); intent.setDataAndType(uri, "image/*"); startActivity(intent); } }
package sun.institute.model; import java.time.LocalDate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; @Entity public class AITRecord { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer recordId; private Integer studId; private Integer logicalMarks; private Integer quantMarks; private Integer gkMarks; private Integer totalMarks; private String mockTest; private LocalDate dateOfExam; @Transient public Integer totalStudents; @Transient public Integer totalStudBehind; public AITRecord() { super(); } public AITRecord(Integer studId, Integer logicalMarks, Integer quantMarks, Integer gkMarks, String mockTest, LocalDate dateOfExam) { super(); this.studId = studId; this.logicalMarks = logicalMarks; this.quantMarks = quantMarks; this.gkMarks = gkMarks; this.mockTest = mockTest; this.dateOfExam = dateOfExam; this.totalMarks = logicalMarks + quantMarks + gkMarks; } public Integer getRecordId() { return recordId; } public void setRecordId(Integer recordId) { this.recordId = recordId; } public Integer getStudId() { return studId; } public void setStudId(Integer studId) { this.studId = studId; } public Integer getLogicalMarks() { return logicalMarks; } public void setLogicalMarks(Integer logicalMarks) { this.logicalMarks = logicalMarks; } public Integer getQuantMarks() { return quantMarks; } public void setQuantMarks(Integer quantMarks) { this.quantMarks = quantMarks; } public Integer getGkMarks() { return gkMarks; } public void setGkMarks(Integer gkMarks) { this.gkMarks = gkMarks; } public LocalDate getDateOfExam() { return dateOfExam; } public void setDateOfExam(LocalDate dateOfExam) { this.dateOfExam = dateOfExam; } public Integer getTotalMarks() { return totalMarks; } public void setTotalMarks(Integer totalMarks) { this.totalMarks = totalMarks; } public String getMockTest() { return mockTest; } public void setMockTest(String mockTest) { this.mockTest = mockTest; } public Integer getTotalStudents() { return totalStudents; } public void setTotalStudents(Integer totalStudents) { this.totalStudents = totalStudents; } public Integer getTotalStudBehind() { return totalStudBehind; } public void setTotalStudBehind(Integer totalStudBehind) { this.totalStudBehind = totalStudBehind; } @Override public String toString() { return "AITRecord [recordId=" + recordId + ", studId=" + studId + ", logicalMarks=" + logicalMarks + ", quantMarks=" + quantMarks + ", gkMarks=" + gkMarks + ", totalMarks=" + totalMarks + ", mockTest=" + mockTest + ", dateOfExam=" + dateOfExam + ", totalStudents=" + totalStudents + ", totalStudBehind=" + totalStudBehind + "]"; } }
package be.thomaswinters.gag.valuesgenerator.filter; import be.thomaswinters.goofer.data.TemplateValues; import be.thomaswinters.goofer.generators.ITemplateValuesGenerator; public class SameWordsFilter extends ATemplateValuesGeneratorFilter { public SameWordsFilter(ITemplateValuesGenerator generator) { super(generator); } /** * Checks if all elements are distinct */ @Override protected boolean isAllowed(TemplateValues values) { return values.getValues().stream().distinct().count() == values.getArity(); } }
package cn.wolfcode.crm.web.controller; import cn.wolfcode.crm.domain.Customer; import cn.wolfcode.crm.domain.CustomerTransferHistory; import cn.wolfcode.crm.query.CustomerTransferHistoryQueryObject; import cn.wolfcode.crm.service.ICustomerService; import cn.wolfcode.crm.service.ICustomerTransferHistoryService; import cn.wolfcode.crm.util.JsonResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/customerTransferHistory") public class CustomerTransferHistoryController { @Autowired private ICustomerTransferHistoryService customerTransferHistoryService; @Autowired private ICustomerService customerService; @RequestMapping("/list") public String list(Model model, @ModelAttribute("qo") CustomerTransferHistoryQueryObject qo) { model.addAttribute("pageInfo", customerTransferHistoryService.query(qo)); return "customerTransferHistory/list"; } @RequestMapping("/save") @ResponseBody public JsonResult save(CustomerTransferHistory entry) { JsonResult json = new JsonResult(); //保存移交信息 customerTransferHistoryService.save(entry); //移交后客户的营销人员发生改变 customerService.updateSellerAndStatusById(entry.getCustomer(), entry.getNewSeller()); return json; } }
package kosesorulari; import java.util.Scanner; public class Soru03 { public static void main(String[] args) { // 3-)Bir sayının Mükemmel bir sayı olup olmadığını bulan metod yaz. /*MÜKEMMEL SAYI NEDİR? Kendisi hariç bütün pozitif bölenlerinin toplamı kendisine eşit olan sayılara mükemmel sayı denir. 6 bir mükemmel sayıdır. Çünkü 6’nın pozitif bölenleri 1,2,3 ve 6’dır. Kendisi hariç diğer bölenlerini toplarsak 1+2+3=6 eder. Bunun gibi 28 de mükemmel sayıdır. 28 = 1 + 2 + 4 + 7 + 14 Mükemmel sayı bulma formülü = 2p−1(2p−1)*/ Scanner scan= new Scanner(System.in); System.out.println("Bir sayi giriniz"); int num = scan.nextInt(); int sum = 0; for (int i = 1; i < num; i++) { if(num%i==0) { sum= sum+i; }if(num==sum) { System.out.println("Mukemmel Sayi"); }else { System.out.println("Mukemmel sayi degil"); } } scan.close(); } }
package kalkulator; import java.util.Locale; import java.util.Scanner; public class Main { public static void main(String[] args) { Locale.setDefault(Locale.US); Calculator calculator = new Calculator(); Scanner scan = new Scanner(System.in); calculator.hello(); while (scan.hasNextLine()) { calculator.set(scan.nextLine()); double ans = calculator.calculate(); System.out.printf("Answer: %.2f\n", ans); } scan.close(); } }
package com.app.shubhamjhunjhunwala.thebakingapp.Utils; import android.content.Context; import android.net.Uri; import android.util.Log; import com.app.shubhamjhunjhunwala.thebakingapp.Objects.Dish; import com.app.shubhamjhunjhunwala.thebakingapp.Objects.Ingredient; import com.app.shubhamjhunjhunwala.thebakingapp.Objects.Step; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Scanner; /** * Created by shubham on 13/03/18. */ public class JSONUtils { public String JSON; public ArrayList<Dish> dishes = new ArrayList<>(); public static String SOURCE_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json"; public static String getResponseFromHTTPUrl(Context context) throws IOException { URL url = new URL(SOURCE_URL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); try { InputStream inputStream = httpURLConnection.getInputStream(); Scanner scanner = new Scanner(inputStream); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); if (hasInput) { String data = scanner.next(); return data; } else { return null; } } finally { httpURLConnection.disconnect(); } } public ArrayList<Dish> getJSONResponce(Context context) throws JSONException { try { InputStream inputStream = context.getAssets().open("data.json"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); JSON = new String(buffer, "UTF-8"); } catch (IOException e) { e.printStackTrace(); return null; } JSONArray dishesJSONArray = new JSONArray(JSON); for (int i = 0, n = dishesJSONArray.length(); i < n; i++) { JSONObject dishJSONObject = dishesJSONArray.getJSONObject(i); Dish dish = new Dish(dishJSONObject.getString("id"), dishJSONObject.getString("name"), getIngredientsFromJSONObject(dishJSONObject), getStepsFromJSONObject(dishJSONObject), Integer.parseInt(dishJSONObject.getString("servings")), dishJSONObject.getString("image")); dishes.add(i, dish); } return dishes; } public ArrayList<Dish> getJSONResponceFromURL(String responce) throws JSONException { JSON = responce; JSONArray dishesJSONArray = new JSONArray(JSON); for (int i = 0, n = dishesJSONArray.length(); i < n; i++) { JSONObject dishJSONObject = dishesJSONArray.getJSONObject(i); Dish dish = new Dish(dishJSONObject.getString("id"), dishJSONObject.getString("name"), getIngredientsFromJSONObject(dishJSONObject), getStepsFromJSONObject(dishJSONObject), Integer.parseInt(dishJSONObject.getString("servings")), dishJSONObject.getString("image")); Log.d("Dish", dish.toString()); dishes.add(i, dish); } return dishes; } public Ingredient[] getIngredientsFromJSONObject (JSONObject dishJSONObject) throws JSONException { JSONArray ingredientsJSONArray = dishJSONObject.getJSONArray("ingredients"); Ingredient[] ingredients = new Ingredient[ingredientsJSONArray.length()]; for (int i = 0, n = ingredients.length; i < n; i++) { JSONObject ingredientJSONObject = ingredientsJSONArray.getJSONObject(i); Ingredient ingredient = new Ingredient(ingredientJSONObject.getString("quantity"), ingredientJSONObject.getString("measure"), ingredientJSONObject.getString("ingredient")); ingredients[i] = ingredient; } return ingredients; } public Step[] getStepsFromJSONObject (JSONObject dishJSONObject) throws JSONException { JSONArray stepsJSONArray = dishJSONObject.getJSONArray("steps"); Step[] steps = new Step[stepsJSONArray.length()]; for (int i = 0, n = steps.length; i < n; i++) { JSONObject stepJSONObject = stepsJSONArray.getJSONObject(i); Step step = new Step(stepJSONObject.getString("id"), stepJSONObject.getString("shortDescription"), stepJSONObject.getString("description"), stepJSONObject.getString("thumbnailURL"), stepJSONObject.getString("videoURL")); steps[i] = step; } return steps; } }
import java.io.*; public class FileExam { public static void main(String[] args) { try { FileReader fr= new FileReader("datar.txt"); FileWriter fw = new FileWriter("dataw.txt"); int c; while((c=fr.read())!=-1) { fw.write(c); } }catch(Exception e) { System.out.println(e.toString()); } } }
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}.model.persitent; import java.io.Serializable; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; /** * The persistent class for the habilidade database table. * */ @Entity @XmlRootElement @NamedQuery(name="Habilidade.findAll", query="SELECT h FROM Habilidade h") public class Habilidade implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="HABILIDADE_NUHABILIDADE_GENERATOR", sequenceName="SEQ_NUHABILIDADE") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="HABILIDADE_NUHABILIDADE_GENERATOR") private long nuhabilidade; private Boolean ativo; private String cohabilidade; private String nome; //bi-directional many-to-many association to Empregado @ManyToMany @JoinTable( name="empregadohabilidade" , joinColumns={ @JoinColumn(name="nuhabilidade") } , inverseJoinColumns={ @JoinColumn(name="nuempregado") } ) private List<Empregado> empregados; public Habilidade() { } public long getNuhabilidade() { return this.nuhabilidade; } public void setNuhabilidade(long nuhabilidade) { this.nuhabilidade = nuhabilidade; } public Boolean getAtivo() { return this.ativo; } public void setAtivo(Boolean ativo) { this.ativo = ativo; } public String getCohabilidade() { return this.cohabilidade; } public void setCohabilidade(String cohabilidade) { this.cohabilidade = cohabilidade; } public String getNome() { return this.nome; } public void setNome(String nome) { this.nome = nome; } public List<Empregado> getEmpregados() { return this.empregados; } public void setEmpregados(List<Empregado> empregados) { this.empregados = empregados; } }
package mini.market.minimarket.repo; import mini.market.minimarket.model.vente; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; import java.util.Optional; public interface VenteRepo extends JpaRepository<vente, String> { @Query("SELECT u FROM vente u WHERE u.annee = ?1") Optional<List<vente>> findVenteByAnnee(Long annee); // @Query(value = "SELECT SUM(price) FROM VENTE_VIEW WHERE (productids= ?1)") // Optional<vente> }
package pl.ark.chr.buginator.ext.service.impl; import net.pieroxy.ua.detection.UserAgentDetector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pl.ark.chr.buginator.data.ExternalData; import pl.ark.chr.buginator.domain.core.Application; import pl.ark.chr.buginator.domain.core.Error; import pl.ark.chr.buginator.domain.core.ErrorStackTrace; import pl.ark.chr.buginator.domain.core.UserAgentData; import pl.ark.chr.buginator.domain.core.ErrorSeverity; import pl.ark.chr.buginator.domain.core.ErrorStatus; import pl.ark.chr.buginator.ext.service.ErrorResolver; import pl.ark.chr.buginator.repository.core.ErrorRepository; import pl.ark.chr.buginator.repository.core.UserAgentDataRepository; import pl.ark.chr.buginator.util.ValidationUtil; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * Created by Arek on 2017-04-03. */ @Service @Transactional public class ErrorResolverImpl implements ErrorResolver { public static final Logger logger = LoggerFactory.getLogger(ErrorResolverImpl.class); private static final ErrorSeverity DEFAULT_SEVERITY = ErrorSeverity.ERROR; private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Autowired private ErrorRepository errorRepository; @Autowired private UserAgentDataRepository userAgentDataRepository; @Override public Error resolveError(ExternalData externalData, Application application) { validateEmptyString(externalData.getErrorTitle(), "Title"); validateEmptyString(externalData.getErrorDescription(), "Description"); if (externalData.getErrorSeverity() == null) { logger.warn("No severity found for external data: " + externalData.toString() + " and application: " + application.getId() + ". Setting default: " + DEFAULT_SEVERITY.name()); externalData.setErrorSeverity(DEFAULT_SEVERITY); } List<Error> foundDuplicates = errorRepository.findDuplicateError(externalData.getErrorTitle(), externalData.getErrorDescription(), externalData.getErrorSeverity(), externalData.getRequestMethod(), externalData.getRequestUrl(), application); if (foundDuplicates.isEmpty()) { return createNewError(externalData, application); } else { return checkDuplicateOrCreate(externalData, application, foundDuplicates); } } private void validateEmptyString(String predicate, String key) { if (ValidationUtil.isBlank(predicate)) { logger.error(key + " is empty"); throw new IllegalArgumentException(key + " is empty"); } } private Error createNewError(ExternalData externalData, Application application) { Error error = Error.builder(externalData.getErrorTitle(), externalData.getErrorSeverity(), ErrorStatus.CREATED, externalData.getDateTimeString(),application).build(); // error.setTitle(externalData.getErrorTitle()); error.setDescription(externalData.getErrorDescription()); // error.setStatus(ErrorStatus.CREATED); // error.setSeverity(externalData.getErrorSeverity()); // error.setLastOccurrence(LocalDate.parse(externalData.getDateString(), dateFormatter)); // error.setDateTime(LocalDateTime.parse(externalData.getDateTimeString(), dateTimeFormatter)); // error.setApplication(application); // error.setCount(1); updatePossibleNullValues(error, externalData); error.setStackTrace(generateStackTrace(error, externalData.getStackTrace())); return errorRepository.save(error); } private void updatePossibleNullValues(Error error, ExternalData externalData) { if (shouldSetField(error.getQueryParams(), externalData.getQueryParams())) { error.setQueryParams(externalData.getQueryParams()); } if (shouldSetField(error.getRequestUrl(), externalData.getRequestUrl())) { error.setRequestUrl(externalData.getRequestUrl()); } if (shouldSetField(error.getUserAgent(), externalData.getUserAgentString())) { UserAgentDetector userAgentDetector = new UserAgentDetector(); UserAgentData savedUAD = userAgentDataRepository.save(new UserAgentData(userAgentDetector.parseUserAgent(externalData.getUserAgentString()))); error.setUserAgent(savedUAD); } if (shouldSetField(error.getRequestParams(), externalData.getRequestParams())) { error.setRequestParams(externalData.getRequestParams().stream().collect(Collectors.joining("\n"))); } if (shouldSetField(error.getRequestHeaders(), externalData.getRequestHeaders())) { error.setRequestParams(externalData.getRequestHeaders().stream().collect(Collectors.joining("\n"))); } if(shouldSetField(error.getRequestMethod(), externalData.getRequestMethod())) { error.setRequestMethod(externalData.getRequestMethod()); } } private boolean shouldSetField(String oldValue, String newValue) { return ValidationUtil.isBlank(oldValue) && !ValidationUtil.isBlank(newValue); } private boolean shouldSetField(Object oldValue, Object newValue) { return ValidationUtil.isNull(oldValue) && ValidationUtil.isNotNull(newValue); } private boolean shouldSetField(String oldValue, List<String> newValues) { return ValidationUtil.isNull(oldValue) && ValidationUtil.isNotNull(newValues) && !newValues.isEmpty(); } private List<ErrorStackTrace> generateStackTrace(Error error, List<ExternalData.ExternalStackTrace> extStackTraces) { List<ErrorStackTrace> stackTraces = new ArrayList<>(); extStackTraces.forEach(externalStackTrace -> { ErrorStackTrace errorStackTrace = new ErrorStackTrace(error, externalStackTrace.getOrder(), externalStackTrace.getDescription()); // errorStackTrace.setError(error); // errorStackTrace.setStackTrace(externalStackTrace.getDescription()); // errorStackTrace.setStackTraceOrder(externalStackTrace.getOrder()); stackTraces.add(errorStackTrace); }); return stackTraces; } private boolean stackTracesAreEqual(List<ExternalData.ExternalStackTrace> extStackTraces, List<ErrorStackTrace> stackTraces) { for (int i = 0; i < stackTraces.size(); i++) { if (stackTraceNotEqual(extStackTraces.get(i), stackTraces.get(i))) { return false; } } return true; } private boolean stackTraceNotEqual(ExternalData.ExternalStackTrace extStackTrace, ErrorStackTrace stackTrace) { return !extStackTrace.getDescription().equals(stackTrace.getStackTrace()); } private Error checkDuplicateOrCreate(ExternalData externalData, Application application, List<Error> foundDuplicates) { if (foundDuplicates.size() > 1) { logger.warn("More than one duplicate found. Algorithm should be improved."); } for (Error possibleDuplicate : foundDuplicates) { if (checkStackTrace(externalData, possibleDuplicate)) { // possibleDuplicate.setLastOccurrence(LocalDate.parse(externalData.getDateString(), dateFormatter)); possibleDuplicate.parseAndSetLastOccurrence(externalData.getDateString()); possibleDuplicate.incrementCount(); if (possibleDuplicate.getStatus().equals(ErrorStatus.RESOLVED)) { possibleDuplicate.setStatus(ErrorStatus.REOPENED); } updatePossibleNullValues(possibleDuplicate, externalData); return errorRepository.save(possibleDuplicate); } } return createNewError(externalData, application); } private boolean checkStackTrace(ExternalData externalData, Error possibleDuplicate) { List<ExternalData.ExternalStackTrace> stackTraces = externalData.getStackTrace().stream() .sorted(Comparator.comparingInt(ExternalData.ExternalStackTrace::getOrder)) .collect(Collectors.toList()); if (stackTraces.size() != possibleDuplicate.getStackTrace().size()) { logger.debug("Stack traces have different length."); return false; } return stackTracesAreEqual(stackTraces, possibleDuplicate.getStackTrace()); } }
package pp_fp06.pizza_restaurant; import pp_fp06.pizza_restaurant.enums.Ingredient_Type; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static pp_fp06.pizza_restaurant.enums.Ingredient_Type.VEGETAL; public class Ementa { /** * MAX_PIZZAS varivel que define o numero maximo de pizzas de uma ementa * dataInicio data de inicio da ementa * dataFim data final da ementa * pizzas vetor de pizzas da ementa * numberOfPizzas numero de pizzas presentes na ementa * valida atributo que determina se a ementa é valida ou nao */ private final int MAX_PIZZAS = 10; //private Date dataInicio; private LocalDateTime dataInicio; private LocalDateTime dataFim; private Pizza[] pizzas; private int numberOfPizzas = 0; private boolean valida; /** * * @param dataFim data final da ementa * dataInicio é inicializada com a data de criação da ementa * A ementa não é valida por pre-definição */ public Ementa(LocalDateTime dataFim) { this.dataFim = dataFim; this.dataInicio = this.dataInicio.now(); this.pizzas = new Pizza[MAX_PIZZAS]; this.valida = false; } /** * * @return o vetor das pizzas */ public Pizza[] getPizzas() { return pizzas; } /** * coloca o vetor de pizzas na ementa * @param pizzas - vetor de pizzas */ public void setPizzas(Pizza[] pizzas) { this.pizzas = pizzas; } /** * * @return o numero de pizzas */ public int getNumberOfPizzas() { return numberOfPizzas; } /** * coloca o numero de pizzas na ementa * @param numberOfPizzas - numero de pizzas */ public void setNumberOfPizzas(int numberOfPizzas) { this.numberOfPizzas = numberOfPizzas; } /** * * @return uma string com a dataInicial da ementa */ public String getDataInicio() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formattedDateTime = this.dataInicio.format(formatter); return formattedDateTime; } /** * coloca a data inicial da ementa * @param dataInicio - dataInicial da ementa */ public void setDataInicio(LocalDateTime dataInicio) { this.dataInicio = dataInicio; } /** * * @return uma string com a dataFinal da ementa */ public String getDataFim() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formattedDateTime = this.dataFim.format(formatter); return formattedDateTime; } /** * coloca a dataFinal da ementa * @param dataFim - dat final da ementa */ public void setDataFim(LocalDateTime dataFim) { this.dataFim = dataFim; } /** * * @return se é válida ou não */ public boolean isValida() { return valida; } /** * Este metodo adiciona uma pizza à ementa * @param pizza pizza para adicionar à ementa * verifica a validação da ementa */ public void addPizza(Pizza pizza){ if(this.numberOfPizzas < MAX_PIZZAS){ this.pizzas[numberOfPizzas] = pizza; this.numberOfPizzas++; this.validaEmenta(); } else{ System.out.println("ja nao cabe mais gordo!"); } } /** * Este metodo remove uma pizza da ementa * @param id Id da pizza a remover * @pos é inicializada a -1 * primeiro for vai percorrer o vetor das pizzas da ementa * primeiro if vai verificar se o id da pizza na posição i é igual ao id recebido * caso seja, a variavel pos vai guardar o indice i * segundo for vai percorrer o vetor das pizzas da ementa e vai passar a pizza na posição j+1 para a posição j, até ao fim do vetor * a ultima posição do vetor passa a null * o numero de pizzas é decrementado * verifica a validação da ementa */ public void removePizza(int id){ int pos = -1; for(int i=0; i<this.numberOfPizzas; i++){ if(this.pizzas[i].getId() == id){ pos = i; } } for(int j=pos; j<this.numberOfPizzas; j++){ this.pizzas[j] = this.pizzas[j+1]; } this.pizzas[this.numberOfPizzas] = null; this.numberOfPizzas--; this.validaEmenta(); } /** * Este método vai verificar se a ementa é válida ou não, e caso seja o atributo válida passa a true * @contAnimal - contador que vai guardar o numero de ingredientes de origem animal de cada pizza * primeiro for vai percorrer o vetor de pizzas da ementa * segundo for vai percorrer os ingredientes de cada pizza * primeiro if vai verificar se a origem do ingrediente na posição j da pizza na posição i, é animal * se for de origem animal, incrementa a variavel contAnimal * segundo if vai verificar se o contAnimal for igual a 0, entao é porque existe uma pizza vegetariana, validando a ementa * @contAnimal volta a 0 */ public void validaEmenta(){ int contAnimal = 0; for(int i=0; i<this.numberOfPizzas; i++){ for(int j=0; j<this.pizzas[i].getNumberOfIngredients(); j++){ if(this.pizzas[i].getIngredients()[j].getOrigem() == Ingredient_Type.ANIMAL){ contAnimal++; } } if(contAnimal == 0){ this.valida = true; } else{ this.valida = false; } contAnimal = 0; } } /** * metodo toString() vai imprimir todos os dados da ementa na tela * @return uma string com todas as informações da ementa */ @Override public String toString() { String s = ""; s+="Data inicial: " + this.getDataInicio() + "\n"; s+="Data Final: " + this.getDataFim() + "\n"; s+="Nº de pizzas: " + this.getNumberOfPizzas() + "\n"; for(int i=0; i<numberOfPizzas; i++){ s+="Pizza: " + pizzas[i].toString(); } return s; } }
package com.tencent.mm.plugin.chatroom.ui; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.l.a; import com.tencent.mm.model.au; import com.tencent.mm.model.c; import com.tencent.mm.model.q; import com.tencent.mm.pluginsdk.f.h; import com.tencent.mm.pluginsdk.ui.a.b; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.bd; import com.tencent.mm.storage.bq; import com.tencent.mm.storage.u; import com.tencent.mm.ui.r; public class SelectMemberChattingRecordUI$a extends r<bd> { int edl = -1; String gBf; final /* synthetic */ SelectMemberChattingRecordUI hPm; String hPn; int hPo = -1; private u hPp; Context mContext; public SelectMemberChattingRecordUI$a(SelectMemberChattingRecordUI selectMemberChattingRecordUI, Context context, String str, String str2, int i) { this.hPm = selectMemberChattingRecordUI; super(context, new bd()); this.mContext = context; this.edl = i; this.gBf = str; this.hPn = str2; au.HU(); this.hPp = c.Ga().ii(SelectMemberChattingRecordUI.b(selectMemberChattingRecordUI)); } public final void WT() { if (this.hPo < 0 || this.hPo > this.edl) { this.hPo = this.edl - 16; } if (!bi.oW(SelectMemberChattingRecordUI.c(this.hPm)) && q.gQ(SelectMemberChattingRecordUI.c(this.hPm))) { au.HU(); setCursor(c.FT().bG(this.gBf, this.edl - this.hPo)); } else if (!q.gQ(SelectMemberChattingRecordUI.c(this.hPm))) { au.HU(); setCursor(c.FT().E(this.gBf, this.hPn, this.edl - this.hPo)); } } protected final void WS() { WT(); } public final View getView(int i, View view, ViewGroup viewGroup) { SelectMemberChattingRecordUI$b selectMemberChattingRecordUI$b; if (view == null) { view = LayoutInflater.from(this.context).inflate(R.i.member_record_item, null, false); selectMemberChattingRecordUI$b = new SelectMemberChattingRecordUI$b(); selectMemberChattingRecordUI$b.eCl = (ImageView) view.findViewById(R.h.avatar_iv); selectMemberChattingRecordUI$b.eTm = (TextView) view.findViewById(R.h.nickname_tv); selectMemberChattingRecordUI$b.hPq = (TextView) view.findViewById(R.h.msg_tv); selectMemberChattingRecordUI$b.hrs = (TextView) view.findViewById(R.h.update_time_tv); view.setTag(selectMemberChattingRecordUI$b); } bd bdVar = (bd) getItem(i); selectMemberChattingRecordUI$b = (SelectMemberChattingRecordUI$b) view.getTag(); b.a(selectMemberChattingRecordUI$b.eCl, this.hPn); String str = this.hPn; au.HU(); ab Yg = c.FR().Yg(str); CharSequence a = !bi.oW(Yg.field_conRemark) ? Yg.field_conRemark : SelectMemberChattingRecordUI.a(this.hPp, Yg.field_username); if (bi.oW(a)) { a = Yg.BK(); } if (!a.gd(Yg.field_type)) { au.HU(); bq Hh = c.FS().Hh(Yg.field_username); if (!(Hh == null || bi.oW(Hh.field_conRemark))) { a = Hh.field_conRemark; } } a(a, selectMemberChattingRecordUI$b.eTm); a(SelectMemberChattingRecordUI.a(ad.getContext(), bdVar.getType(), bdVar.field_content, this.hPn, bdVar.field_isSend).trim(), selectMemberChattingRecordUI$b.hPq); a(h.c(this.hPm, bdVar.field_createTime, true), selectMemberChattingRecordUI$b.hrs); return view; } private static boolean a(CharSequence charSequence, TextView textView) { if (charSequence == null || charSequence.length() == 0) { textView.setVisibility(8); return false; } textView.setText(j.a(textView.getContext(), charSequence)); textView.setVisibility(0); return true; } }
package vantoan.blog_security.service; import vantoan.blog_security.model.Blog; import java.util.List; public interface IBlogService { List<Blog> findAll(); Blog findById(Long id); Blog save(Blog blog); void delete(Long id); }
package CssSelectorRule; import java.util.Date; /** * Author: fangxueshun * Description: * Date: 2017/3/30 * Time: 17:02 */ public abstract class CssContentRule { public abstract ContentType getContentType(); public abstract String getSite(); public abstract void setCreateTime(Date date); public abstract void setUpdateTime(Date date); @Override public final int hashCode() { final int prime = 512; int result = super.hashCode(); result = prime * result + ((getContentType() == null) ? 0 : getContentType().hashCode()); result = prime * result + ((getSite() == null) ? 0 : getSite().hashCode()); return result; } @Override public final boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof CssContentRule)) { return false; } CssContentRule other = (CssContentRule) obj; if (getContentType() != other.getContentType()) { return false; } if (getSite() == null) { if (other.getContentType() != null) { return false; } } else if (!getSite().equals(other.getSite())) { return false; } return true; } }
package com.tencent.mm.wallet_core.ui; import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.EditText; import com.tencent.mm.ab.l; import com.tencent.mm.bp.a; import com.tencent.mm.model.q; import com.tencent.mm.pluginsdk.wallet.PayInfo; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; import com.tencent.mm.wallet_core.c; import com.tencent.mm.wallet_core.c.e; import com.tencent.mm.wallet_core.c.i; import com.tencent.mm.wallet_core.c.o; import com.tencent.mm.wallet_core.d.f; import com.tencent.mm.wallet_core.d.g; import com.tencent.mm.wallet_core.e.a.b; import com.tencent.mm.wallet_core.tenpay.model.m; import com.tencent.smtt.utils.TbsLog; import com.tenpay.android.wechat.MyKeyboardWindow; import com.tenpay.android.wechat.TenpaySecureEditText; public abstract class WalletBaseUI extends MMActivity implements f { public static final int eCE = a.fromDPToPix(ad.getContext(), 270); private static i uYQ = null; private Dialog jhd; public View kMk; public a kTx; public MyKeyboardWindow mKeyboard; public Bundle sy = new Bundle(); private OnMenuItemClickListener tQp; private c uYN = null; public com.tencent.mm.wallet_core.d.i uYO = null; private g uYP = null; private OnMenuItemClickListener uYR; public boolean uYS = false; public abstract boolean d(int i, int i2, String str, l lVar); public final String bNs() { if (this.sy == null) { return ""; } PayInfo payInfo = (PayInfo) this.sy.getParcelable("key_pay_info"); if (payInfo != null) { return payInfo.bOd; } return ""; } public void baT() { x.d("MicroMsg.WalletBaseUI", "cancelforceScene"); this.uYO.baT(); finish(); } public void onCreate(Bundle bundle) { super.onCreate(bundle); if (!com.tencent.mm.kernel.g.Eg().Dx()) { x.e("MicroMsg.WalletBaseUI", "hy: account not ready. finish now"); h.a(this, getString(com.tencent.mm.plugin.wxpay.a.i.wallet_account_not_ready), "", false, new 1(this)); } this.uYO = new com.tencent.mm.wallet_core.d.i(this, this); this.uYO.jr(385); this.uYO.jr(1518); x.d("MicroMsg.WalletBaseUI", "current process:" + getIntent().getIntExtra("process_id", 0)); c af = com.tencent.mm.wallet_core.a.af(this); if (af != null) { this.uYO.dox = af.aNK(); } x.d("MicroMsg.WalletBaseUI", "proc " + af); this.sy = com.tencent.mm.wallet_core.a.ae(this); if (this.sy == null) { this.sy = new Bundle(); } this.uYO.sy = this.sy; if (bbU() && !com.tencent.mm.wallet_core.a.ad(this)) { x.e("MicroMsg.WalletBaseUI", "Activity extends WalletBaseUI but not in process!!!"); } if (getLayoutId() > 0) { String str = ""; if (!bi.oW(str)) { setMMSubTitle(str); } } setBackBtn(new 3(this)); this.uYP = cDL(); if (this.uYP != null && this.uYP.r(new Object[0])) { ux(4); } else if (getLayoutId() <= 0) { ux(4); } else if (bbR()) { ux(4); } else { ux(0); } } public final void setBackBtn(OnMenuItemClickListener onMenuItemClickListener) { this.tQp = onMenuItemClickListener; super.setBackBtn(onMenuItemClickListener); } public final void addTextOptionMenu(int i, String str, OnMenuItemClickListener onMenuItemClickListener) { this.uYR = onMenuItemClickListener; super.addTextOptionMenu(i, str, onMenuItemClickListener); } public final void a(String str, OnMenuItemClickListener onMenuItemClickListener, int i) { this.uYR = onMenuItemClickListener; super.a(0, str, onMenuItemClickListener, i); } public void onResume() { super.onResume(); if (o.cCZ()) { l bVar; if (q.GS()) { bVar = new b(); } else { bVar = new m(); } this.uYO.a(bVar, false); } } public void onPause() { super.onPause(); } public void onDestroy() { super.onDestroy(); this.uYO.js(385); this.uYO.js(1518); } public void b(int i, int i2, String str, l lVar, boolean z) { x.d("MicroMsg.WalletBaseUI", "errType = " + i + ", errCode = " + i2 + ", errMsg = " + str); TenpaySecureEditText.setSalt(o.cDa()); if (lVar instanceof i) { i iVar = (i) lVar; uYQ = iVar; if (this.sy != null) { if (iVar.pmS > 0) { this.sy.putInt("key_is_gen_cert", iVar.pmS); } if (iVar.pmU > 0) { this.sy.putInt("key_is_hint_crt", iVar.pmU); } if (iVar.pmW > 0) { this.sy.putInt("key_is_ignore_cert", iVar.pmW); } if (!bi.oW(iVar.pmT)) { this.sy.putString("key_crt_token", iVar.pmT); } if (!bi.oW(iVar.pmV)) { this.sy.putString("key_crt_wording", iVar.pmV); } } } k(i, i2, str, lVar); f.a(this, i, i2, str, lVar, z); } public void onActivityResult(int i, int i2, Intent intent) { super.onActivityResult(i, i2, intent); cDL().onActivityResult(i, i2, intent); } public void rj(int i) { } public boolean k(int i, int i2, String str, l lVar) { return true; } public boolean bbU() { return true; } public boolean aWj() { return false; } public boolean bbR() { if (getLayoutId() > 0 && !this.uYO.baU()) { return false; } return true; } /* renamed from: bND */ public boolean f() { return false; } public final void cDH() { PayInfo payInfo = (PayInfo) this.sy.getParcelable("key_pay_info"); if (payInfo == null) { payInfo = (PayInfo) getIntent().getParcelableExtra("key_pay_info"); } if (payInfo != null && !bi.oW(payInfo.fMk)) { this.uYO.a(new e(payInfo.fMk, payInfo.bOd), true, 1); payInfo.fMk = null; } } public boolean Wt() { return true; } public boolean onKeyUp(int i, KeyEvent keyEvent) { if (i == 4) { if (this.kMk != null && this.kMk.isShown()) { Wq(); return true; } else if (f()) { YC(); showDialog(TbsLog.TBSLOG_CODE_SDK_BASE); return true; } else if (this.tQp != null && Wt()) { this.tQp.onMenuItemClick(null); return true; } else if (this.uYR != null) { this.uYR.onMenuItemClick(null); return true; } } return super.onKeyUp(i, keyEvent); } public final boolean Xf() { if (this.tQp != null) { this.tQp.onMenuItemClick(null); return true; } else if (this.uYR == null) { return super.Xf(); } else { this.uYR.onMenuItemClick(null); return true; } } public Dialog onCreateDialog(int i) { x.i("MicroMsg.WalletBaseUI", "onCreateDialog id = " + i); switch (i) { case TbsLog.TBSLOG_CODE_SDK_BASE /*1000*/: int a; c af = com.tencent.mm.wallet_core.a.af(this); if (af != null) { a = af.a((MMActivity) this, 1); } else { a = -1; } if (a != -1) { return h.a(this, true, getString(a), "", getString(com.tencent.mm.plugin.wxpay.a.i.app_yes), getString(com.tencent.mm.plugin.wxpay.a.i.app_no), new 4(this), new 5(this)); } if (af != null) { af.b(this, this.sy); } else { finish(); } return super.onCreateDialog(i); default: return super.onCreateDialog(i); } } public final void d(View view, int i, boolean z) { a(view, i, z, true); } public void a(View view, int i, boolean z, boolean z2) { a(view, i, z, true, z2); } @TargetApi(14) public final void a(View view, int i, boolean z, boolean z2, boolean z3) { a(view, null, i, z, z2, z3); } public final void a(View view, EditText editText, int i, boolean z, boolean z2, boolean z3) { EditText editText2; this.mKeyboard = (MyKeyboardWindow) findViewById(com.tencent.mm.plugin.wxpay.a.f.tenpay_num_keyboard); this.kMk = findViewById(com.tencent.mm.plugin.wxpay.a.f.tenpay_keyboard_layout); View findViewById = findViewById(com.tencent.mm.plugin.wxpay.a.f.tenpay_push_down); if (editText == null) { editText2 = (EditText) view.findViewById(com.tencent.mm.plugin.wxpay.a.f.wallet_content); } else { editText2 = editText; } if (this.mKeyboard != null && editText2 != null && this.kMk != null) { OnFocusChangeListener onFocusChangeListener = null; if (z3) { onFocusChangeListener = editText2.getOnFocusChangeListener(); } e.setNoSystemInputOnEditText(editText2); editText2.setOnFocusChangeListener(new 6(this, z, z2, view, editText2, i, onFocusChangeListener)); editText2.setOnClickListener(new 7(this, z, i, editText2)); findViewById.setOnClickListener(new OnClickListener() { public final void onClick(View view) { WalletBaseUI.this.Wq(); } }); } } public final boolean mM(boolean z) { if (uYQ == null || (!uYQ.bkT() && !z)) { return false; } this.uYO.a(uYQ, true); return true; } public static void cDI() { f.cDI(); } public void Wq() { if (this.kMk != null && this.kMk.isShown()) { this.kMk.setVisibility(8); if (this.kTx != null) { this.kTx.fI(false); } } } public final void cDJ() { if (this.kMk != null && !this.kMk.isShown()) { this.kMk.setVisibility(0); if (this.kTx != null) { this.kTx.fI(true); } } } public final void Hb(int i) { this.mKeyboard.setXMode(i); } public final c cDK() { if (this.uYN == null) { this.uYN = com.tencent.mm.wallet_core.a.af(this); } return this.uYN; } public final g cDL() { if (this.uYP == null) { c cDK = cDK(); if (cDK != null) { this.uYP = cDK.a((MMActivity) this, this.uYO); } if (this.uYP == null) { this.uYP = new 9(this, this, this.uYO); } } return this.uYP; } public final CharSequence cDM() { if (this.uYP == null) { return null; } return this.uYP.ui(0); } public void bMZ() { cDK().a((Activity) this, 0, this.sy); } public final void jr(int i) { this.uYO.jr(i); } public final void js(int i) { this.uYO.js(i); } public final void a(l lVar, boolean z, boolean z2) { c cDK = cDK(); if (cDK != null) { this.uYO.sy = cDK.jfZ; } int i = 1; if (!z2) { i = 2; } this.uYO.a(lVar, z, i); } public final void aBy() { if (this.jhd == null || !(this.jhd == null || this.jhd.isShowing())) { if (this.jhd != null) { this.jhd.dismiss(); } this.jhd = g.a(this, false, new 10(this)); } } public final void bfe() { if (this.jhd != null) { this.jhd.dismiss(); } } public void ux(int i) { super.ux(i); } public void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent.getBooleanExtra("key_process_is_end", false) && !intent.getBooleanExtra("key_process_is_stay", true)) { setIntent(intent); Bundle extras = getIntent().getExtras(); int i = (extras == null || !extras.containsKey("key_process_result_code")) ? 0 : extras.getInt("key_process_result_code", 0); if (i == -1) { x.i("MicroMsg.WalletBaseUI", "process end ok!"); setResult(-1, getIntent()); } else { x.i("MicroMsg.WalletBaseUI", "process end with user cancel or err! resultCode : " + i); setResult(0, getIntent()); } finish(); } } public final void a(View view, View view2, int i) { if (view != null) { int[] iArr = new int[2]; view2.getLocationInWindow(iArr); int fl = (a.fl(this) - r0) - a.fromDPToPix(this, i); x.d("MicroMsg.WalletBaseUI", "scrollToFormEditPosAfterShowTenPay, editText locationY: %s, height: %s, diff: %s, hardcodeKeyboardHeight: %s", new Object[]{Integer.valueOf(iArr[1] + view2.getHeight()), Integer.valueOf(a.fl(this)), Integer.valueOf(fl), Integer.valueOf(eCE)}); if (fl > 0 && fl < eCE) { x.d("MicroMsg.WalletBaseUI", "scrollToFormEditPosAfterShowTenPay, scrollDistance: %s", new Object[]{Integer.valueOf(eCE - fl)}); view.post(new 2(this, view, r0)); } } } }
package co.aospa.mandy.view; import android.content.Context; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import co.aospa.mandy.R; import co.aospa.mandy.utils.server.MandyStatus; /** * Created by willi on 16.04.17. */ public class MandyStatusView extends LinearLayoutCompat { public interface MandyStatusViewListener { void onMergePressed(); void onSubmittingPressed(); void onRevertingPressed(); } private AppCompatTextView mManifestTag; private AppCompatTextView mLatestTag; private AppCompatTextView mProgressText; private ProgressBar mProgress; private AppCompatButton mButton1; private AppCompatButton mButton2; private AppCompatTextView mError; private MandyStatus mMandyStatus; private MandyStatusViewListener mMandyStatusViewListener; public MandyStatusView(Context context) { this(context, null); } public MandyStatusView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MandyStatusView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutInflater.from(context).inflate(R.layout.view_mandystatus, this); mManifestTag = (AppCompatTextView) findViewById(R.id.manifest_tag); mLatestTag = (AppCompatTextView) findViewById(R.id.latest_tag); mProgressText = (AppCompatTextView) findViewById(R.id.progress_text); mProgress = (ProgressBar) findViewById(R.id.progress); mButton1 = (AppCompatButton) findViewById(R.id.btn1); mButton2 = (AppCompatButton) findViewById(R.id.btn2); mError = (AppCompatTextView) findViewById(R.id.error); setup(); } public void setStatus(MandyStatus status, MandyStatusViewListener mandyStatusViewListener) { mMandyStatus = status; mMandyStatusViewListener = mandyStatusViewListener; setup(); } private void setup() { if (mMandyStatus == null || mMandyStatusViewListener == null) return; mManifestTag.setText(mMandyStatus.mManifestTag); mLatestTag.setText(mMandyStatus.mLatestTag == null ? "-" : mMandyStatus.mLatestTag); mProgressText.setVisibility(GONE); mProgress.setVisibility(GONE); mProgress.setIndeterminate(true); mError.setVisibility(GONE); mButton1.setVisibility(GONE); mButton2.setVisibility(GONE); mButton1.setEnabled(true); mButton2.setEnabled(true); mButton1.setOnClickListener(null); mButton2.setOnClickListener(null); if (mMandyStatus.mMerging || mMandyStatus.mSubmitting || mMandyStatus.mReverting) { String progressText; if (mMandyStatus.mMerging) { progressText = getContext().getString(R.string.merging) + "\n" + getContext().getString(R.string.executed_by, mMandyStatus.mMerger.mName); } else if (mMandyStatus.mSubmitting) { progressText = getContext().getString(R.string.submitting) + "\n" + getContext().getString(R.string.executed_by, mMandyStatus.mSubmitter.mName); } else { progressText = getContext().getString(R.string.reverting) + "\n" + getContext().getString(R.string.executed_by, mMandyStatus.mReverter.mName); } mProgressText.setText(progressText); mProgressText.setVisibility(VISIBLE); mProgress.setVisibility(VISIBLE); } else if (mMandyStatus.mMerged) { mButton1.setText(getContext().getString(R.string.revert)); mButton2.setText(getContext().getString(R.string.submit)); mButton1.setVisibility(VISIBLE); mButton2.setVisibility(VISIBLE); if (mMandyStatus.mSubmittable) { for (MandyStatus.AospaProject aospaProject : mMandyStatus.mAospaProjects) { if (aospaProject.mConflicted) { mError.setVisibility(VISIBLE); mError.setText(getContext().getString(R.string.repos_conflicted)); mButton2.setEnabled(false); break; } } } else { mError.setVisibility(VISIBLE); mError.setText(getContext().getString(R.string.repos_conflicted)); mButton2.setEnabled(false); } mButton1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMandyStatusViewListener.onRevertingPressed(); } }); mButton2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMandyStatusViewListener.onSubmittingPressed(); } }); } else if (mMandyStatus.mSubmitted) { mError.setVisibility(VISIBLE); mError.setText(getContext().getString(R.string.latest_tag_submitted)); } else { boolean mergeable = true; if (mMandyStatus.mMergeable) { for (MandyStatus.AospaProject project : mMandyStatus.mAospaProjects) { if (!project.mLatestTag.equals(mMandyStatus.mLatestTag)) { mergeable = false; break; } } } if (!mMandyStatus.mManifestTag.equals(mMandyStatus.mLatestTag)) { if (mergeable && mMandyStatus.mMergeable) { mButton1.setText(getContext().getString(R.string.merge)); mButton1.setVisibility(VISIBLE); mButton1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mMandyStatusViewListener.onMergePressed(); } }); } else { mError.setVisibility(VISIBLE); mError.setText(getContext().getString(R.string.repos_wrong_tag)); } } } } }
/* * 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 GuiNetbean; import Storage.Account; import Storage.AccountList; import Storage.Avatar; import java.awt.Image; import java.io.File; import javax.swing.JOptionPane; import java.time.Instant; import java.time.LocalDate; import java.time.Month; import java.time.ZoneId; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileSystemView; /** * * @author Admin */ public class guiProfile extends javax.swing.JFrame { /** * Creates new form guiLogin * * @param login_ */ public guiProfile(Account login_) { this.login = login_; initComponents(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, login.getBirthday_().getYear()); cal.set(Calendar.MONTH, login.getBirthday_().getMonthValue() - 1); cal.set(Calendar.DAY_OF_MONTH, login.getBirthday_().getDayOfMonth()); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date date = cal.getTime(); dateChooser.setDate(date); Image img = Avatar.readPicture(login.getUsername()); if (img != null) { Image resize = img.getScaledInstance(200, 200, Image.SCALE_DEFAULT); pic.setIcon(new ImageIcon(resize)); } else { pic.setIcon(null); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); Btchooserpic = new javax.swing.JToggleButton(); pic = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); fullname = new javax.swing.JTextField(); birthday = new javax.swing.JTextField(); dateChooser = new com.toedter.calendar.JDateChooser(); address = new javax.swing.JTextField(); phone = new javax.swing.JTextField(); fblink = new javax.swing.JTextField(); editProfileButton = new javax.swing.JButton(); agreeButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); work = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); gender = new javax.swing.JComboBox(); sexField = new javax.swing.JTextField(); email = new javax.swing.JTextField(); View = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); changePwMenuItem = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GuiNetbean/Pic/4882066.jpg"))); // NOI18N setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Profile"); setLocation(new java.awt.Point(600, 250)); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); Btchooserpic.setText("Chooser Picturer"); Btchooserpic.setVisible(false); Btchooserpic.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtchooserpicActionPerformed(evt); } }); getContentPane().add(Btchooserpic, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 130, -1, -1)); pic.setForeground(new java.awt.Color(255, 153, 0)); pic.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); pic.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Avatar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tempus Sans ITC", 1, 14), new java.awt.Color(255, 153, 0))); // NOI18N getContentPane().add(pic, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 20, 230, 230)); jLabel3.setForeground(new java.awt.Color(255, 153, 0)); jLabel3.setText("Carrot team @ 2021"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(710, 520, -1, -1)); fullname.setText(login.getFullName()); fullname.setEditable(false); fullname.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N getContentPane().add(fullname, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 50, 280, -1)); birthday.setText(login.getBirthday()); birthday.setEditable(false); getContentPane().add(birthday, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 110, 130, -1)); dateChooser.setVisible(false); getContentPane().add(dateChooser, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 110, 180, -1)); dateChooser.setDateFormatString("dd/MM/yyyy"); address.setText(login.getAddress()); address.setEditable(false); getContentPane().add(address, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 300, 270, 50)); phone.setText(login.getPhoneNum()); phone.setEditable(false); getContentPane().add(phone, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 390, 270, -1)); fblink.setText(login.getFb()); fblink.setEditable(false); getContentPane().add(fblink, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 390, 190, -1)); editProfileButton.setForeground(new java.awt.Color(255, 153, 0)); editProfileButton.setText("Edit profile"); editProfileButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editProfileButtonActionPerformed(evt); } }); getContentPane().add(editProfileButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 480, -1, -1)); agreeButton.setForeground(new java.awt.Color(255, 153, 0)); agreeButton.setText("Agreee"); agreeButton.setVisible(false); agreeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { agreeButtonActionPerformed(evt); } }); getContentPane().add(agreeButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 480, -1, -1)); cancelButton.setForeground(new java.awt.Color(255, 153, 0)); cancelButton.setText("Cancel"); cancelButton.setVisible(false); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); getContentPane().add(cancelButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 480, -1, -1)); work.setText(login.getWork()); work.setEditable(false); getContentPane().add(work, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 450, 270, 60)); jLabel4.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 153, 0)); jLabel4.setText("Facebook"); getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 370, 140, -1)); jLabel5.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 153, 0)); jLabel5.setText("Name"); getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 30, 50, -1)); jLabel6.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 153, 0)); jLabel6.setText("Date of birth"); getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 90, 120, -1)); jLabel7.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 153, 0)); jLabel7.setText("Gender"); getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 140, 100, 20)); jLabel8.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(255, 153, 0)); jLabel8.setText("Address _____________________"); getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 270, 270, -1)); jLabel9.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel9.setForeground(new java.awt.Color(255, 153, 0)); jLabel9.setText("Phone number ________________"); getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 360, 270, -1)); jLabel11.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(255, 153, 0)); jLabel11.setText("Work ________________________"); getContentPane().add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 420, 270, -1)); jLabel12.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel12.setForeground(new java.awt.Color(255, 153, 0)); jLabel12.setText("----------About----------"); getContentPane().add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 270, 160, -1)); jLabel13.setFont(new java.awt.Font("UTM Ambrose", 1, 14)); // NOI18N jLabel13.setForeground(new java.awt.Color(255, 153, 0)); jLabel13.setText("Email"); getContentPane().add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 310, 100, -1)); gender.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Male", "Female" })); gender.setToolTipText(""); gender.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { genderActionPerformed(evt); } }); getContentPane().add(gender, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 160, -1, -1)); gender.setVisible(false); sexField.setEditable(false); sexField.setText("jTextField1"); getContentPane().add(sexField, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 160, -1, -1)); sexField.setText(login.getSex() ? "Male" : "Female"); email.setEditable(false); email.setText(login.getEmail()); getContentPane().add(email, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 340, 190, -1)); View.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GuiNetbean/Pic/background.png"))); // NOI18N getContentPane().add(View, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 820, 540)); jMenu1.setText("Hello "+login.getUsername()); jMenuItem1.setText("Logout"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); changePwMenuItem.setText("Change password"); changePwMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { changePwMenuItemActionPerformed(evt); } }); jMenu1.add(changePwMenuItem); jMenuItem2.setText("Exit"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu1.add(jMenuItem2); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); pack(); }// </editor-fold>//GEN-END:initComponents private void genderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_genderActionPerformed }//GEN-LAST:event_genderActionPerformed private void BtchooserpicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtchooserpicActionPerformed JFileChooser FileChooser = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); String link; FileChooser.setDialogTitle("Select an image"); FileChooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG JPG JPEG and GIF images", "png", "gif", "jpg", "jpeg"); FileChooser.addChoosableFileFilter(filter); FileChooser.setMultiSelectionEnabled(false); int returnValue = FileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File f = FileChooser.getSelectedFile(); link = f.getPath(); pic.setIcon(new ImageIcon(f.getAbsolutePath())); int output = JOptionPane.showConfirmDialog(Btchooserpic, "Do you want to change", "", JOptionPane.YES_NO_OPTION); if (output == 0) { Avatar.updatePicture(login.getUsername(), link); } else { Image img = Avatar.readPicture(login.getUsername()); if (img != null) { Image resize = img.getScaledInstance(200, 200, Image.SCALE_DEFAULT); pic.setIcon(new ImageIcon(resize)); } else { pic.setIcon(null); } } } }//GEN-LAST:event_BtchooserpicActionPerformed private void changePwMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changePwMenuItemActionPerformed javax.swing.JPasswordField field0 = new javax.swing.JPasswordField(); field0.setEchoChar('\u2022'); javax.swing.JPasswordField field1 = new javax.swing.JPasswordField(); field1.setEchoChar('\u2022'); javax.swing.JPasswordField field2 = new javax.swing.JPasswordField(); field2.setEchoChar('\u2022'); Object[] message = {"Old password:", field0, "New password:", field1, "Re-enter new pass:", field2}; int option = JOptionPane.showConfirmDialog(rootPane, message, "Change password", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { char[] value0 = field0.getPassword(); if (login.check(new String(value0))) { char[] value1 = field1.getPassword(); char[] value2 = field2.getPassword(); if ((new String(value1)).equals(new String(value2)) && value1.length != 0) { login.setNewPassword(new String(value1)); JOptionPane.showMessageDialog(rootPane, "Change password successfully", "", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(rootPane, "New password does not match", "Warning", JOptionPane.WARNING_MESSAGE); } } else { JOptionPane.showMessageDialog(rootPane, "Password incorrect", "Warning", JOptionPane.WARNING_MESSAGE); } } }//GEN-LAST:event_changePwMenuItemActionPerformed Date date = new Date(); private void phoneActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_phoneActionPerformed }// GEN-LAST:event_phoneActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem2ActionPerformed int output = JOptionPane.showConfirmDialog(jMenuItem2, "Do you want to exit?", "Logout", JOptionPane.YES_NO_OPTION); if (output == 0) { dispose(); } }// GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem1ActionPerformed int output = JOptionPane.showConfirmDialog(jMenuItem2, "Do you want to sign out?", "Logout", JOptionPane.YES_NO_OPTION); if (output == 0) { guiMain frm1 = new guiMain(); frm1.setVisible(true); dispose(); } }// GEN-LAST:event_jMenuItem1ActionPerformed private void editProfileButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_editProfileButtonActionPerformed agreeButton.setVisible(true); cancelButton.setVisible(true); editProfileButton.setVisible(false); Btchooserpic.setVisible(true); fullname.setEditable(true); phone.setEditable(true); address.setEditable(true); work.setEditable(true); fblink.setEditable(true); email.setEditable(true); gender.setEditable(true); birthday.setVisible(false); dateChooser.setVisible(true); gender.setVisible(true); sexField.setVisible(false); // pic.setVisible(false); }// GEN-LAST:event_editProfileButtonActionPerformed private void agreeButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_agreeButtonActionPerformed agreeButton.setVisible(false); cancelButton.setVisible(false); editProfileButton.setVisible(true); Btchooserpic.setVisible(false); fullname.setEditable(false); phone.setEditable(false); address.setEditable(true); work.setEditable(true); fblink.setEditable(true); email.setEditable(true); birthday.setVisible(true); dateChooser.setVisible(false); gender.setVisible(false); sexField.setVisible(true); String fullName = fullname.getText(); String phone_ = phone.getText(); String address_ = address.getText(); String work_ = work.getText(); String fblink_ = fblink.getText(); String email_ = email.getText(); Date birthday_ = dateChooser.getCalendar().getTime(); if (!isValidPhone(phone_)) { JOptionPane.showMessageDialog(agreeButton, "Not a Vietnamese phone number", "InvalidPhoneNumberError", JOptionPane.WARNING_MESSAGE); } else { if (fullName == null ? login.getFullName() != null : !fullName.equals(login.getFullName())) { login.setFullName(fullName); } if (birthday_ != new Date()) { login.setBirthday(convertToLocalDateViaMilisecond(birthday_)); } if (phone_ == null ? login.getPhoneNum() != null : !phone_.equals(login.getPhoneNum())) { login.setPhoneNum(phone_); } if (address_ == null ? login.getAddress() != null : !address_.equals(login.getAddress())) { login.setAddress(address_); } if (work_ == null ? login.getWork() != null : !work_.equals(login.getWork())) { login.setWork(work_); } if (fblink_ == null ? login.getFb() != null : !fblink_.equals(login.getFb())) { login.setFblink(fblink_); } if (email_ == null ? login.getEmail() != null : !email_.equals(login.getEmail())) { login.setEmail(email_); } login.setSex(gender.getSelectedItem() == "Male"); sexField.setText(login.getSex() ? "Male" : "Female"); AccountList a = new AccountList(); a.editAccount(login); } }// GEN-LAST:event_agreeButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_cancelButtonActionPerformed agreeButton.setVisible(false); cancelButton.setVisible(false); editProfileButton.setVisible(true); Btchooserpic.setVisible(false); fullname.setText(login.getFullName()); phone.setText(login.getPhoneNum()); address.setText(login.getAddress()); work.setText(login.getWork()); fblink.setText(login.getFb()); email.setText(login.getEmail()); birthday.setVisible(true); dateChooser.setVisible(false); gender.setVisible(false); sexField.setVisible(true); Image img = Avatar.readPicture(login.getUsername()); if (img != null) { Image resize = img.getScaledInstance(200, 200, Image.SCALE_DEFAULT); pic.setIcon(new ImageIcon(resize)); } else { pic.setIcon(null); } }// GEN-LAST:event_cancelButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // <editor-fold defaultstate="collapsed" desc=" Look and feel setting code // (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the default * look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(guiProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(guiProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(guiProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(guiProfile.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // </editor-fold> // </editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { Account a = new Account("fudio", "Ng01637202484", "Nguyen Do The Nguyen", LocalDate.of(2001, Month.JANUARY, 1), "0337202484"); new guiProfile(a).setVisible(true); } }); } private boolean isValidPhone(String phoneNum) { String regex = "(84[3|5|7|8|9]|0[3|5|7|8|9])+([0-9]{8})"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(phoneNum); return m.matches(); } public LocalDate convertToLocalDateViaMilisecond(Date dateToConvert) { return Instant.ofEpochMilli(dateToConvert.getTime()).atZone(ZoneId.systemDefault()).toLocalDate(); } private final Account login; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JToggleButton Btchooserpic; private javax.swing.JLabel View; private javax.swing.JTextField address; private javax.swing.JButton agreeButton; private javax.swing.JTextField birthday; private javax.swing.JButton cancelButton; private javax.swing.JMenuItem changePwMenuItem; private com.toedter.calendar.JDateChooser dateChooser; private javax.swing.JButton editProfileButton; private javax.swing.JTextField email; private javax.swing.JTextField fblink; private javax.swing.JTextField fullname; private javax.swing.JComboBox<String> gender; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JTextField phone; private javax.swing.JLabel pic; private javax.swing.JTextField sexField; private javax.swing.JTextField work; // End of variables declaration//GEN-END:variables }
package com.team.controller; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping({"/", "/home"}) public String home(Model model, HttpSession session) { return "/home"; } }
package com.androiddevs.recyclerviewcollapsibletoolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.recycler_view_item, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { } @Override public int getItemCount() { // add 20 items just for demonstration purpose return 20; } public class RecyclerViewHolder extends RecyclerView.ViewHolder { public RecyclerViewHolder(@NonNull View itemView) { super(itemView); } } }
package com.zafodB.ethwalletp5.UI; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Toast; import com.zafodB.ethwalletp5.Crypto.WalletWrapper; import com.zafodB.ethwalletp5.FragmentChangerClass; import com.zafodB.ethwalletp5.R; import java.io.IOException; import java.util.ArrayList; /** * Created by filip on 12/12/2017. */ public class FrontPageFragment extends Fragment { Button createNewWalletBtn; Button restoreWalletBtn; // static String[] walletnames = {"test", "normal", "another test", "yet another test"}; ArrayList<String> wallets; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.front_page_fragment, container, false); createNewWalletBtn = view.findViewById(R.id.create_new_wallet_btn); restoreWalletBtn = view.findViewById(R.id.restore_wallet_button); wallets = WalletWrapper.getWalletNames(getContext()); ListAdapter adapter; if (wallets == null) { System.out.println("No wallets to be shown"); //TODO Handle if there is no wallets. } else { adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, wallets); ListView walletsList = view.findViewById(R.id.list_wallets); walletsList.setAdapter(adapter); walletsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Bundle args = new Bundle(); args.putString("name", wallets.get(i)); Fragment walletOpenFragment = new WalletOpenFragment(); walletOpenFragment.setArguments(args); FragmentChangerClass.FragmentChanger changer = (FragmentChangerClass.FragmentChanger) getActivity(); changer.ChangeFragments(walletOpenFragment); } }); } createNewWalletBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CreateWalletFragment createWalletFrag = new CreateWalletFragment(); FragmentChangerClass.FragmentChanger fragmentChanger = (FragmentChangerClass.FragmentChanger) getActivity(); fragmentChanger.ChangeFragments(createWalletFrag); } }); restoreWalletBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment restoreWalletFragment = new RestoreWalletFragment(); FragmentChangerClass.FragmentChanger changer = (FragmentChangerClass.FragmentChanger) getActivity(); changer.ChangeFragments(restoreWalletFragment); } }); return view; } }
/* * 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 Controller; /** * * @author MBP */ import Database.Database; import Model.Aplikasi; import Model.PreOrder; import View.ViewListPreOrder; import View.ViewPreOrder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class ControllerPreOrder implements ActionListener{ private ViewPreOrder v; private ViewListPreOrder vp; private Database db = new Database(); private Aplikasi app; private Connection Con; public ControllerPreOrder(Aplikasi app) { this.app = app; this.v = new ViewPreOrder(); //this.vp = new ViewListPreOrder(); v.setActionListener(this); v.setVisible(true); //showPreOrder(); } @Override public void actionPerformed(ActionEvent e) { int hargabahan = 0; int tarif = 0; Object source = e.getSource(); Con = db.getConnection(); try{ if (source == v.getCekharga() ){ String namaBahan = v.getNamaBahan(); // String query = "Select harga from daftarBahan where namaBahan = '"+v.getNamaBahan()+"'"; // PreparedStatement ps = Con.prepareStatement(query); ResultSet rs = app.getDb().getHargaBahan(namaBahan); while(rs.next()){ hargabahan = rs.getInt("harga"); } String namaJasa = v.getNamaJasa(); // String query2 = "Select tarif from daftarJasa where namaJasa = '"+v.getNamaJasa()+"'"; // PreparedStatement ps2 = Con.prepareStatement(query2); ResultSet rs2 = app.getDb().getTarifJasa(namaJasa); while(rs2.next()){ tarif = rs2.getInt("tarif"); } int jmlbaju = Integer.valueOf(v.getJumlahBaju().getText()); int total = (hargabahan + tarif); int totalharga = total * jmlbaju; String strtotalharga = String.valueOf(totalharga); v.setTotalHarga(strtotalharga); } else if (source == v.getProses() ){ String nama = v.getNama().getText(); String email = v.getEmail().getText(); String namaBahan = v.getNamaBahan(); String namaJasa = v.getNamaJasa(); String jmlBaju = v.getJumlahBaju().getText(); String totalHarga = v.getTotalHarga().getText(); app.addPreOrder(email, nama, namaBahan, namaJasa, jmlBaju, totalHarga); v.reset(); } else if (source == v.getView()){ new ControllerViewListPO(app); v.setVisible(false); } else if (source == v.getBack()){ new ControllerMainMenu(app); v.setVisible(false); } } catch (Exception ae) { JOptionPane.showMessageDialog(v, ae.getMessage()); ae.printStackTrace(); v.reset(); } } }
package org.slf4j; import static junit.framework.Assert.assertTrue; public class OutputVerifier { static void noProvider(StringPrintStream sps) { dump(sps); int lineCount = sps.stringList.size(); assertTrue("number of lines should be 6 but was " + lineCount, lineCount == 6); // expected output: (version 1.8) // SLF4J: No SLF4J providers were found. // SLF4J: Defaulting to no-operation (NOP) logger implementation // SLF4J: See http://www.slf4j.org/codes.html#noProviders for further details. // SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions prior to 1.8. // SLF4J: Ignoring binding found at // [jar:file:..../slf4j-simple-1.4.2.jar!/org/slf4j/impl/StaticLoggerBinder.class] // SLF4J: See http://www.slf4j.org/codes.html#ignoredBindings for an explanation. { String s = (String) sps.stringList.get(0); assertTrue(s.contains("No SLF4J providers were found.")); } { String s = (String) sps.stringList.get(1); assertTrue(s.contains("Defaulting to no-operation (NOP) logger implementation")); } { String s = (String) sps.stringList.get(2); assertTrue(s.contains("SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.")); } { String s = (String) sps.stringList.get(3); assertTrue(s.contains("SLF4J: Class path contains SLF4J bindings targeting slf4j-api versions 1.7.x or earlier.")); } { String s = (String) sps.stringList.get(4); assertTrue(s.contains("Ignoring binding found at")); } { String s = (String) sps.stringList.get(5); assertTrue(s.contains("See https://www.slf4j.org/codes.html#ignoredBindings for an explanation")); } } public static void dump(StringPrintStream sps) { for (String s : sps.stringList) { System.out.println(s); } } }
package com.literature.repository; import com.literature.entity.Permission; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PermissionRepository extends JpaRepository<Permission,String> { @Query(value = "select * from sys_permissions where name like %:name%",nativeQuery = true) List<Permission> findByName(@Param("name") String name); List<Permission> findAllByAndParentId(String id); Permission findPermissionsById(String id); }
package vn.geekup.utils; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.graphics.Paint; import android.graphics.Rect; import android.support.annotation.DimenRes; import android.support.annotation.NonNull; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; /** * Created by quoctrung on 7/31/2017. */ public class ScreenUtils { private static Context mContext; // Prevent direct instantiation. private ScreenUtils() { throw new IllegalAccessError(ScreenUtils.class.getName()); } public static void init(Context context) { mContext = context; } /** * @return The absolute width of the available display size in pixels. */ public static int getWidthScreen() { return mContext.getResources().getDisplayMetrics().widthPixels; } /** * @return The absolute height of the available display size in pixels. */ public static int getHeightScreen() { return mContext.getResources().getDisplayMetrics().heightPixels; } /** * Check device has soft navigation bar * @return true if has soft navigation bar */ public static boolean hasNavBar() { int id = mContext.getResources().getIdentifier("config_showNavigationBar", "bool", "android"); return id > 0 && mContext.getResources().getBoolean(id); } /** * This method get height of navigation bar * @return 0 if device don't has soft navigation bar */ public static int getNavigationBarHeight() { Resources resources = mContext.getResources(); int id = resources.getIdentifier("navigation_bar_height", "dimen", "android"); return id > 0 ? resources.getDimensionPixelSize(id) : 0; } /** * This method get height of status bar * @return */ public static int getStatusBarHeight() { Resources resources = mContext.getResources(); int id = resources.getIdentifier("status_bar_height", "dimen", "android"); return id > 0 ? resources.getDimensionPixelSize(id) : 0; } /** * This method get height default of action bar * @return */ public static int getActionBarHeight() { TypedValue tv = new TypedValue(); if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { return TypedValue.complexToDimensionPixelSize(tv.data, mContext.getResources().getDisplayMetrics()); } else { return 0; } } /** * This method converts dp unit to equivalent pixels, depending on device density. * * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels * @return A float value to represent px equivalent to dp depending on device density */ public static float convertDpToPixel(float dp) { Resources resources = mContext.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); return dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); } /** * This method converts device specific pixels to density independent pixels. * * @param px A value in px (pixels) unit. Which we need to convert into db * @return A float value to represent dp equivalent to px value */ public static float convertPixelsToDp(float px) { Resources resources = mContext.getResources(); DisplayMetrics metrics = resources.getDisplayMetrics(); return px / ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); } /** * * @param id The desired resource identifier, as generated by the aapt * tool. This integer encodes the package, type, and resource * entry. The value 0 is an invalid identifier. * * @return Resource dimension value multiplied by the appropriate * metric and truncated to integer pixels. * * @throws Resources.NotFoundException Throws NotFoundException if the given ID does not exist. */ public static int getDimensionPixelOffset(@DimenRes int id) { return mContext.getResources().getDimensionPixelOffset(id); } /** * Hides the keyboard */ public static void hideSoftKeyboard(@NonNull Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Activity.INPUT_METHOD_SERVICE); if (inputMethodManager == null) { return; } inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } /** * Show the keyboard */ public static void showKeyBoard() { InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } @SuppressLint("ClickableViewAccessibility") public static void setupViewClickHideKeyBoard(Activity activity, View... views) { // Set up touch listener for non-text box views to hide keyboard. for (View view : views) { if (view instanceof EditText) { continue; } view.setOnTouchListener((v, event) -> { if (activity != null && activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) { hideSoftKeyboard(activity); } return false; }); //If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupViewClickHideKeyBoard(activity, innerView); } } } } }
package com.mod.course_service.document; import com.fasterxml.jackson.annotation.JsonFormat; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; public class Topic { private String name; @JsonFormat private Boolean completed; public Topic() { } public Topic(String name, Boolean completed) { this.name = name; this.completed = completed; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getCompleted() { return completed; } public void setCompleted(Boolean completed) { this.completed = completed; } @Override public String toString() { return "Topic{" + "name='" + name + '\'' + ", completed=" + completed + '}'; } }
package com.tkb.elearning.dao; import java.util.List; import com.tkb.elearning.model.Active; /** * 活動訊息Dao訊息介口 * @author Admin * @version 創建時間:2016-04-26 * */ public interface ActiveDao { /** * 取得活動訊息清單(分頁) * @param pageCount * @param pageStart * @param active * @return List<Active> * */ public List<Active> getList(int pageCount, int pageStart, Active active); /** * 取得活動訊息總筆數 * @param active * @return Active * */ public Integer getCount(Active avtive); /** * 取得單筆活動訊息 * @param active * */ public Active getData(Active active); /** * 新增活動訊息 * @param active * */ public void add(Active active); /** * 修改活動訊息 * @param active * */ public void update(Active active); /** * 刪除活動訊息 * @param id * */ public void delete(Integer id); /** * 檢查屆別(個筆)使用筆數 * @param active * @return Integer */ public Integer checkUsingPeriod(Active active); }
#include<stdio.h> int main() { int n,c,arr[100],d,t; scanf("%d",&n); for(c=0;c<n;c++) scanf("%d",&arr[c]); for(c=0;c<n-1;c++) { for(d=0;d<n-c-1;d++) { if(arr[d]>arr[d+1]) { t=arr[d]; arr[d]=arr[d+1]; arr[d+1]=t; } } } printf("Sorted array is:\n"); for(c=0;c<n;c++) printf("%d\n",arr[c]); return 0; }
/* * 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 tr.com.rah.fe; import static java.awt.Dialog.DEFAULT_MODALITY_TYPE; import java.awt.GridLayout; import java.awt.event.ActionEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import static javax.swing.WindowConstants.HIDE_ON_CLOSE; import tr.com.rah.dal.AccountDAL; import tr.com.rah.dal.PersonelDAL; import tr.com.rah.dal.YetkilerDAL; import tr.com.rah.interfaces.FeInterfaces; import tr.com.rah.types.AccountContract; import tr.com.rah.types.PersonelContract; import tr.com.rah.types.YetkilerContract; /** * * @author rahimgng */ public class SifreBelirleFE extends JDialog implements FeInterfaces { public SifreBelirleFE() { initPencere(); } @Override public void initPencere() { JPanel panel = initPanel(); panel.setBorder(BorderFactory.createTitledBorder("Şifre Belirleme")); add(panel); setTitle("Şifre Belirle"); pack(); setModalityType(DEFAULT_MODALITY_TYPE); setLocationRelativeTo(null); setVisible(true); setDefaultCloseOperation(HIDE_ON_CLOSE); } @Override public JPanel initPanel() { JPanel panel = new JPanel(new GridLayout(5, 2)); JLabel personelLabel = new JLabel("Personel:", JLabel.RIGHT); panel.add(personelLabel); JComboBox personelBox = new JComboBox(new PersonelDAL().GetAll().toArray()); panel.add(personelBox); JLabel yetkiLabel = new JLabel("Yetki:", JLabel.RIGHT); panel.add(yetkiLabel); JComboBox yetkiBox = new JComboBox(new YetkilerDAL().GetAll().toArray()); panel.add(yetkiBox); JLabel passLabel = new JLabel("Şifre:", JLabel.RIGHT); panel.add(passLabel); JPasswordField passField = new JPasswordField(10); panel.add(passField); JLabel passTekrarLabel = new JLabel("Şifre Tekrar:", JLabel.RIGHT); panel.add(passTekrarLabel); JPasswordField passTekrarField = new JPasswordField(10); panel.add(passTekrarField); JButton kaydetButton = new JButton("Kaydet"); panel.add(kaydetButton); JButton iptalButton = new JButton("İptal"); panel.add(iptalButton); kaydetButton.addActionListener((ActionEvent e) -> { SwingUtilities.invokeLater(() -> { AccountContract contract = new AccountContract(); PersonelContract pContract = (PersonelContract) personelBox.getSelectedItem(); YetkilerContract yContract = (YetkilerContract) yetkiBox.getSelectedItem(); if (passField.getText() == null ? passTekrarField.getText() == null : passField.getText().equals(passTekrarField.getText())) { contract.setPersonelId(pContract.getId()); contract.setYetkiId(yContract.getId()); contract.setSifre(passField.getText()); JOptionPane.showMessageDialog(null, pContract.getAdiSoyadi() + " adlı kişiye " + yContract.getAd() + " adlı yetki başarılı bir şekilde atandı!"); JOptionPane.getRootFrame().dispose(); new AccountDAL().Insert(contract); } else { JOptionPane.showMessageDialog(null, "Şifreler Uyuşmuyor!"); } }); }); return panel; } @Override public JMenuBar initBar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public JTabbedPane initTabs() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package com.cs4125.bookingapp.services; import com.google.common.hash.Hashing; import org.springframework.stereotype.Service; import java.nio.charset.StandardCharsets; @Service public class EncryptionServiceImpl implements EncryptionService { @Override public String encryptString(String s) { return Hashing.sha256().hashString(s, StandardCharsets.UTF_8).toString(); } }
package cn.chinaunicom.monitor.http.Response; import cn.chinaunicom.monitor.beans.DataSetCharts; /** * Created by yfYang on 2017/10/11. */ public class DataSetChartsResp extends BaseResp { public DataSetCharts data; }
package hurtlocker; import java.util.regex.Matcher; /** * Created by gregoryfletcher on 6/1/17. */ public class ShoppingListItem { private String itemName; private String itemPrice; private String itemType; private String itemExpirationDate; public static int numberOfMilk, numberOfApple, numberOfBread, numberOfCookie; Matcher matcher; int numberOfItemName; public static int expensiveMilkPriceCount, cheapMilkPriceCount; public static int expensiveApplePriceCount, cheapApplePriceCount; public static int basicCookiePriceCount; public static int basicBreadPriceCount; public static int tariqTrollCount; public ShoppingListItem(String itemName, String itemPrice, String itemType, String itemExpirationDate) { this.itemName = itemName; this.itemPrice = itemPrice; this.itemType = itemType; this.itemExpirationDate = itemExpirationDate; timesItemNameAppears(); timesItemPriceAppears(); setTariqTrollCount(); } @Override public boolean equals(Object shoppingListItem) { ShoppingListItem prototype = (ShoppingListItem)shoppingListItem; return (itemName.equals(prototype.itemName)) && (itemPrice.equals(prototype.itemPrice)) && (itemType.equals(prototype.itemType)) && (itemExpirationDate.equals(prototype.itemExpirationDate)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(itemName); sb.append(" "); sb.append(itemPrice); sb.append(" "); sb.append(itemType); sb.append(" "); sb.append(itemExpirationDate); String shoppingListItem = sb.toString(); return shoppingListItem; } private void timesItemNameAppears() { matcher = JerkSONPatterns.nameApples.matcher(itemName); if (matcher.find()) { numberOfApple++; numberOfItemName = numberOfApple; } matcher = JerkSONPatterns.nameBread.matcher(itemName); if (matcher.find()) { numberOfBread++; numberOfItemName = numberOfBread; } matcher = JerkSONPatterns.nameCookies.matcher(itemName); if (matcher.find()) { numberOfCookie++; numberOfItemName = numberOfCookie; } matcher = JerkSONPatterns.nameMilk.matcher(itemName); if (matcher.find()) { numberOfMilk++; numberOfItemName = numberOfMilk; } } private void timesItemPriceAppears() { if (itemName.equalsIgnoreCase("Apples")) { matcher = JerkSONPatterns.priceValue23.matcher(itemPrice); if (matcher.find()) { cheapApplePriceCount++; } else { expensiveApplePriceCount++; } } if (itemName.equalsIgnoreCase("Bread")) { matcher = JerkSONPatterns.priceValue123.matcher(itemPrice); if (matcher.find()) { basicBreadPriceCount++; } } if (itemName.equalsIgnoreCase("Cookie")) { matcher = JerkSONPatterns.priceValue225.matcher(itemPrice); if (matcher.find()) { basicCookiePriceCount++; } } if(itemName.equalsIgnoreCase("Milk")) { matcher = JerkSONPatterns.priceValue323.matcher(itemPrice); if (matcher.find()) { expensiveMilkPriceCount++; } else { cheapMilkPriceCount++; } } } private void setTariqTrollCount() { if (itemName == "Hell to the no, to the no, no, no.") { tariqTrollCount++; } else if (itemPrice == "Hell to the no, to the no, no, no.") { tariqTrollCount++; } else if (itemType == "Hell to the no, to the no, no, no.") { tariqTrollCount++; } else if (itemExpirationDate == "Hell to the no, to the no, no, no.") { tariqTrollCount++; } } }
package library.dao; import library.entity.Book; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface BookDAO extends CrudRepository<Book, Integer> { Optional<Book> findByTitle(String title); List<Book> findAllByAuthor(String author); List<Book> findAllByGenre(String genre); }
package assignment03; import java.util.ArrayList; import java.util.Scanner; import java.io.BufferedReader; import java.io.InputStreamReader; public class ExecuteShellComand { public static void main(String[] args) { ArrayList<String> commandHystory = new ArrayList<String>(); ExecuteShellComand obj = new ExecuteShellComand(); /*String domainName = "google.com"; //in mac oxs String command = "ping -c 3 " + domainName; */ //in windows //String command = "ping -n 3 " + domainName; System.out.println("Your hystory is empty , First run some command\n then enter the serial no. from back to run the certain command "); Scanner input = new Scanner(System.in); while(true){ System.out.println("Enter command or number of last command to run and q to exit"); String command = input.nextLine(); if(command.equals("q") || command.equals("Q")) break; //if("324".c) //String command = "!-"+commandNo ; commandHystory.add(command); //commandHystory.get(commandHystory.size()-) String output = obj.executeCommand(command); System.out.println(output); } input.close(); } private String executeCommand(String command) { StringBuffer output = new StringBuffer(); Process p; try { p = Runtime.getRuntime().exec(command); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine())!= null) { output.append(line + "\n"); } } catch (Exception e) { e.printStackTrace(); } return output.toString(); } }
import Lap1.Strudent1; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Strudent1 hocSinh1 = new Strudent1 ("Nguyen Van C ", 28, " Nam " ); } }
package com.example.admin.eventdatabinding; import model.Temperature; /** * Created by ADMIN on 10/30/17. */ public class MainActivityPresenter { public MainActivityContact.View view; public MainActivityPresenter(MainActivityContact.View view) { this.view = view; } public void onShowData(Temperature temperature){ this.view.showData(temperature); } }
package com.service.proxy.impl; import java.util.Date; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.proxy.ProxyDao; import com.pojo.CardRecord; import com.pojo.MainProxy; import com.pojo.Proxy; import com.service.customer.CustomerService; import com.service.proxy.ProxyService; @Service public class ProxyServiceImpl implements ProxyService{ @Autowired ProxyDao proxyDao; @Autowired CustomerService customerService; @Override public Proxy findProxyByID(int id) { // TODO Auto-generated method stub return proxyDao.findProxyByID(id); } @Override public String addProxy(Proxy proxy) { // TODO Auto-generated method stub int result=-1; StringBuffer stringBuffer=new StringBuffer(); for (int i = 0; i < 7; i++) { stringBuffer.append((int)(Math.random()*10)); } proxy.setInitPassword(stringBuffer.toString()); proxy.setPassword(stringBuffer.toString()); result=proxyDao.addProxy(proxy); if (result>0) { return "插入成功"; }else{ return "插入失败"; } } @Override public void deleteProxy(String proxyId) { // TODO Auto-generated method stub } @Override public int updateProxy(Proxy proxy) { return proxyDao.updateProxy(proxy); } @Override public List<Proxy> getProxysByRecommendID(int recommendId,int startIndex,int length) { return proxyDao.getProxysByRecommendID(recommendId,startIndex,length); } /** * 根据销售类型,变更代理的房卡数 */ @Override public int updateCardCount(int proxyId, int type,int cardCount,Date cardLTime) { Proxy proxy= proxyDao.findProxyByID(proxyId); int result=-1; if (type==0) { proxy.setCardFCount(proxy.getCardFCount()+cardCount); result=proxyDao.updateFCardCount(proxy); }else if(type==1){ proxy.setCardLTime(cardLTime); proxy.setCardLCount(proxy.getCardLCount()+cardCount); result=proxyDao.updateLCardCount(proxy); } return result; } /** * 根据销售类型,变更代理的房卡数 */ @Override public int updateCardCount(int proxyId, int type,int cardCount) { Proxy proxy= proxyDao.findProxyByID(proxyId); int result=-1; if (type==0) { proxy.setCardFCount(proxy.getCardFCount()+cardCount); result=proxyDao.updateFCardCount(proxy); }else if(type==1){ proxy.setCardLCount(proxy.getCardLCount()+cardCount); result=proxyDao.updateLCardCount(proxy); } return result; } /** * 根据销售类型,变更代理的房卡数 */ public int updateCardCount(Proxy proxy, int type,int cardCount) { int result=-1; if (type==0) { proxy.setCardFCount(proxy.getCardFCount()+cardCount); result=proxyDao.updateFCardCount(proxy); }else if(type==1){ proxy.setCardLCount(proxy.getCardLCount()+cardCount); result=proxyDao.updateLCardCount(proxy); } return result; } @Override public List<Proxy> getAllProxys(int startIndex,int length) { // TODO Auto-generated method stub return proxyDao.getAllProxys(null,null,startIndex, length); } @Override public int sellCardCount(int userId, int edUserId, int type, int toType, int count,int income) { Proxy proxy=findProxyByID(userId); Date cardLTime=proxy.getCardLTime(); int result=-1; if (toType==0) {//处理被操作代理 result=updateCardCount(edUserId,type,count,cardLTime); }else if (toType==1) {//玩家 result=customerService.updateCardCount(edUserId, count); } if(result>=0){ //赠送成功的情况下,修改自身数据 proxy.setIncome(proxy.getIncome()+income); result=updateCardCount(proxy, type,-count); //给自己更新数据失败,扣除之前操作 if (result<=0) { if (toType==0) {//处理被操作代理 result=updateCardCount(edUserId,type,-count); }else if (toType==1) {//玩家 result=customerService.updateCardCount(edUserId,-count); } } } return result; } @Override public int editPassword(Proxy person) { // TODO Auto-generated method stub return proxyDao.editPassword(person); } @Override public List<Integer> getProxyIdsByRecommendID(int recommendPerson) { return proxyDao.getProxyIdsByRecommendID(recommendPerson); } @Override public List<Proxy> getPersonLikeUsername(String username) { return proxyDao.getPersonLikeUsername(username); } @Override public List<Proxy> getProxysByTime(int id, Date crTime, Date enTime) { return proxyDao.getProxys(id, crTime, enTime,-1,-1); } @Override public List<Proxy> getAllProxys(Date startTime, Date endTime) { // TODO Auto-generated method stub return proxyDao.getAllProxys(startTime, endTime, -1, -1); } @Override public int getProxysByRecommendIDCount(int recommendId) { return proxyDao.getProxysByRecommendIDCount(recommendId); } @Override public int getAllProxysCount() { return proxyDao.getAllProxysCount(); } @Override public List<Proxy> getProxysByIndex(int id, int startIndex, int length) { return proxyDao.getProxys(id, null, null,startIndex,length); } }
package com.tencent.mm.plugin.wallet_core.e; import com.tencent.mm.plugin.wallet_core.model.e; import java.util.Map; public interface a$a { void T(Map<String, e> map); }
package com.charith.dailyCoding.productOfArray02; public class Solution { public static int[] solution(int[] array) { int totalSum = 0; int[] productArray = new int[array.length]; for (int i = 0; i < array.length; i++) { totalSum += array[i]; } if (totalSum != 0) { for (int i = 0; i < array.length; i++) { productArray[i] = totalSum / array[i]; } } return productArray; } public static int[] solution2(int[] array) { int[] leftProductArray = new int[array.length + 1]; leftProductArray[0] = 1; for (int i = 1; i <= array.length; i++) { leftProductArray[i + 1] = leftProductArray[i] * array[i]; } int[] rightProductArray = new int[array.length + 1]; rightProductArray[array.length] = 1; for (int i = array.length; i >= 1; i--) { rightProductArray[i - 1] = rightProductArray[i] * array[i]; } int[] productArray = new int[array.length]; for (int i = 1; i <= productArray.length; i++) { productArray[i] = leftProductArray[i + 1] * rightProductArray[i - 1]; } return productArray; } }
package br.com.tdc.javaee.arquillian; import javax.ejb.Stateless; @Stateless public class LeroLero { private final static int ARRAY_SIZE = 100; public Boolean[] doSomethingComplicated() { Boolean booleanArray[] = new Boolean[ARRAY_SIZE]; for (int i = 0; i < ARRAY_SIZE; i++) { booleanArray[i] = (i % 2 == 0) ? Boolean.TRUE : Boolean.FALSE; } return booleanArray; } }
package simple.mvc.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import simple.mvc.app.mapper.UserMapper; import simple.mvc.bean.UserBean; import simple.mvc.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public UserBean getUserByUsernamAndPassword(String userName, String password) { return userMapper.getUserBeanByNameAndPassword(userName, password); } @Override public UserBean createUser(UserBean bean) { return userMapper.createUser(bean); } @Override public List<UserBean> getAllUsers() { return userMapper.getAllUsers(); } @Override public void deleteUser(UserBean bean) { // TODO Auto-generated method stub } @Override public UserBean updateUser(UserBean bean) { // TODO Auto-generated method stub return null; } @Override public UserBean getUserById(Long id) { return userMapper.converUserToBeanByUserId(id); } }
package com.tencent.mm.plugin.exdevice.ui; import com.tencent.mm.g.a.rc; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.x; class ExdeviceAddDataSourceUI$7 implements Runnable { final /* synthetic */ ExdeviceAddDataSourceUI iAm; ExdeviceAddDataSourceUI$7(ExdeviceAddDataSourceUI exdeviceAddDataSourceUI) { this.iAm = exdeviceAddDataSourceUI; } public final void run() { x.d("MicroMsg.ExdeviceAddDataSourceUI", "stopAllChannelEvent! "); a.sFg.m(new rc()); } }
package optmodel; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import application.SampleApplication; import architecture.SampleArchitecture; import control.exceptions.ModelException; import control.exceptions.SolverException; import control.solver.OPPSolver; import control.solver.mp.MPSolver; import model.application.Application; import model.architecture.Architecture; import model.placement.Report; import model.placement.optmodel.OPPModel; import model.placement.optmodel.cplex.OPPRestricted; public class TestRestricted { @Rule public TestName name = new TestName(); @Before public void testInfo() { System.out.println("\n/********************************************************************************"); System.out.println(" * TEST: " + this.getClass().getSimpleName() + " " + name.getMethodName()); System.out.println(" ********************************************************************************/\n"); } @Test public void create() throws ModelException { Architecture arc = SampleArchitecture.uniform(); Application app = SampleApplication.uniform(arc.vertexSet()); OPPModel model = new OPPRestricted(app, arc); System.out.println(model); model.getCPlex().end(); } @Test public void solve() throws ModelException, SolverException { Architecture arc = SampleArchitecture.uniform(); Application app = SampleApplication.uniform(arc.vertexSet()); System.out.println(app.toPrettyString()); System.out.println(arc.toPrettyString()); OPPModel model = new OPPRestricted(app, arc); OPPSolver solver = new MPSolver(); Report report = solver.solveAndReport(model); if (report != null) System.out.println(report.toPrettyString()); else System.out.println(model.getName() + " UNSOLVABLE"); model.getCPlex().end(); } }
package com.operators; public class ShiftOperatorDemo { public static void main(String args[]) { System.out.println(10<<2); // 10*2^2 = 10*4 = 40 System.out.println(10>>2); //10/2^2 = 10/4 = 2 // when 10 is convert into binary } }
package com.eecs493.power_trip; public class AlbumData { String albumId; String albumTitle; String albumTimeStamp; boolean hasThumbnail; String thumbnailUrl; public AlbumData(String id, String title, String timeStamp, boolean thumbnail, String url) { albumId = id; albumTitle = title; albumTimeStamp = timeStamp; hasThumbnail = thumbnail; thumbnailUrl = url; } public AlbumData(String title, String timeStamp, boolean thumbnail, String url) { albumTitle = title; albumTimeStamp = timeStamp; hasThumbnail = thumbnail; thumbnailUrl = url; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.onlineshopping.order; import com.onlineshopping.category.categoryBean; import com.onlineshopping.category.categoryDAO; import com.onlineshopping.customer.customerBean; import com.onlineshopping.customer.customerDAO; import com.onlineshopping.orderdetails.orderdetailsBean; import com.onlineshopping.orderdetails.orderdetailsDAO; import com.onlineshopping.product.productBean; import com.onlineshopping.product.productDAO; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.*; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author deepak */ public class customerAddCart extends HttpServlet { protected ArrayList<MasterOrder> items; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String method = request.getParameter("method"); HttpSession httpSession = request.getSession(true); RequestDispatcher dispatcher = null; double total = 0, grant = 0; int opt = 0; int size = 0; double total1 = 0; opt = Integer.parseInt(request.getParameter("opt")); int qty = 1; try { HttpSession session = request.getSession(); out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); out.println("<head>"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"); out.println("<title>Pink Shop Template</title>"); out.println("<meta name=\"keywords\" content=\"pink shop, store template, ecommerce, online shopping, CSS, HTML\" />"); out.println("<meta name=\"description\" content=\"Pink Shop is a free ecommerce template provided by templatemo.com\" />"); out.println("<link href=\"templatemo_style.css\" rel=\"stylesheet\" type=\"text/css\"/>"); out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"stylesheet/styles.css\" />"); out.println("<script language=\"javascript\" type=\"text/javascript\">"); out.println("function clearText(field)"); { out.println("if (field.defaultValue == field.value) field.value = '';"); out.println("else if (field.value == '') field.value = field.defaultValue;"); } out.println("</script>"); out.println("<script language=\"javascript\" type=\"text/javascript\" src=\"scripts/mootools-1.2.1-core.js\"></script>"); out.println("<script language=\"javascript\" type=\"text/javascript\" src=\"scripts/mootools-1.2-more.js\"></script>"); out.println("<script language=\"javascript\" type=\"text/javascript\" src=\"scripts/slideitmoo-1.1.js\"></script>"); out.println("<script language=\"javascript\" type=\"text/javascript\">"); out.println("window.addEvents({"); out.println("'domready': function(){"); /* thumbnails example , div containers */ out.println("new SlideItMoo({"); out.println("overallContainer: 'SlideItMoo_outer',"); out.println("elementScrolled: 'SlideItMoo_inner',"); out.println("thumbsContainer: 'SlideItMoo_items',"); out.println("itemsVisible: 5,"); out.println("elemsSlide: 3,"); out.println("duration: 200,"); out.println("itemsSelector: '.SlideItMoo_element',"); out.println("itemWidth: 140,"); out.println("showControls:1});"); out.println("}"); out.println("});"); out.println("</script>"); out.println("</head>"); out.println("<body>"); out.println("<div id=\"templatemo_wrapper\">"); out.println("<div id=\"templatemo_menu\">"); dispatcher = request.getRequestDispatcher("/design/menuforCustomer.html"); dispatcher.include(request, response); out.println("<!--menu-->"); out.println("<!--menu-->"); out.println("</div> <!-- end of templatemo_menu -->"); out.println("<div id=\"templatemo_header_bar\">"); dispatcher = request.getRequestDispatcher("/design/header.html"); dispatcher.include(request, response); out.println("<!--header-->"); out.println("<!--header-->"); // dispatcher = request.getRequestDispatcher("/design/search.html"); // dispatcher.include(request, response); // // // out.println("<!--search-->"); // // out.println("<!--search-->"); out.println("</div> <!-- end of templatemo_header_bar -->"); out.println("<div class=\"cleaner\"></div>"); out.println("<div id=\"sidebar\"><div class=\"sidebar_top\"></div><div class=\"sidebar_bottom\"></div>"); // dispatcher = request.getRequestDispatcher("/design/member.html"); // dispatcher.include(request, response); // // // out.println("<!--member-->"); // // out.println("<!--member-->"); dispatcher = request.getRequestDispatcher("/design/databaseCustomer.html"); dispatcher.include(request, response); out.println("<!--database-->"); out.println("<!--database-->"); // dispatcher = request.getRequestDispatcher("/design/discount.html"); // dispatcher.include(request, response); // // out.println("<!--discount-->"); // // out.println("<!--discount-->"); out.println("<!-- end of sidebar -->"); out.println("</div>"); out.println("<div id=\"templatmeo_content\">"); // // dispatcher = request.getRequestDispatcher("/design/feature.html"); // dispatcher.include(request, response); // // out.println("<!--features-->"); // // out.println("<!--features-->"); // out.println("<!-- end of latest_content_gallery -->"); // dispatcher = request.getRequestDispatcher("/design/welcome.html"); // dispatcher.include(request, response); // // out.println("<!--welcome-->"); // // out.println("<!--welcome-->"); out.println("<div class=\"content_section\">"); // dispatcher = request.getRequestDispatcher("/design/content.html"); // dispatcher.include(request, response); // // out.println("<!--content-->"); /* if (method.equals("add")) { MasterOrder bn = new MasterOrder(); int ic = Integer.parseInt(request.getParameter("productid")); bn.setProductid(ic); bn.setProductname(request.getParameter("productname")); bn.setQuantity(qty); double pri = Double.parseDouble(request.getParameter("productprice")); bn.setProductprice(pri); bn.setSubtotal(pri); int qty1 = 0; if (items == null) { items = new ArrayList<MasterOrder>(); } boolean currIndex = items.isEmpty(); if (currIndex) { items.add(bn); System.out.println("items" + items); httpSession.setAttribute("items", items); } else { Boolean itemExists = false; for (Iterator it = items.iterator(); it.hasNext();) { Object o = it.next(); MasterOrder shop = (MasterOrder) o; if (shop.getProductid() == bn.getProductid()) { int qt = shop.getQuantity(); double pr = shop.getProductprice(); qty1 = 1 + qt; total = qty1 * pr; shop.setQuantity(qty1); shop.setSubtotal(total); itemExists = true; } } if (!itemExists) { items.add(bn); httpSession.setAttribute("items", items); } } ArrayList al = (ArrayList) httpSession.getAttribute("items"); Iterator itr = al.iterator(); size = al.size(); while (itr.hasNext()) { MasterOrder scbn = (MasterOrder) itr.next(); double price = 0; price = scbn.getProductprice() * scbn.getQuantity(); total1 = total1 + price; } httpSession.setAttribute("size", size); httpSession.setAttribute("grant", total1); httpSession.setAttribute("pid", ic); httpSession.setAttribute("price", pri); httpSession.setAttribute("qty", qty1); } else if (method.equals("delete")) { int id = Integer.parseInt(request.getParameter("productid")); System.out.println("id delete" + id); for (Iterator it = items.iterator(); it.hasNext();) { Object o = it.next(); MasterOrder shop = (MasterOrder) o; if (shop.getProductid() == id) { items.remove(o); } } httpSession.setAttribute("items", items); httpSession.setAttribute("size", size); httpSession.setAttribute("grant", total1); // dispatcher = request.getRequestDispatcher("/pages/customer/AddToCart.jsp"); out.print("<span style='color: RED'>Item Deleted</span>"); } else if (method.equals("update")) { int id = Integer.parseInt(request.getParameter("productid")); int qty1 = Integer.parseInt(request.getParameter("quantity")); ArrayList<MasterOrder> newItem = new ArrayList<MasterOrder>(); for (Iterator it = items.iterator(); it.hasNext();) { Object o = it.next(); MasterOrder shop = (MasterOrder) o; if (shop.getProductid() == id) { shop.setQuantity(qty1); } newItem.add(shop); } System.out.println("qty " + request.getParameter("quantity")); out.print("<span style='color: green'>Quantity Changed</span>"); } if (opt == 1) { // dispatcher = request.getRequestDispatcher("/pages/customer/BuyNow.jsp"); out.println("hello"); } else { // dispatcher = request.getRequestDispatcher("/pages/customer/AddToCart.jsp"); } dispatcher.forward(request, response); */ ArrayList arl= (ArrayList)session.getAttribute("arl"); int index=-1; if(arl==null){ arl = new ArrayList(); session.setAttribute("arl",arl); } synchronized(arl) { //if(request.getParameter("add")!=null) if(method.equals("add")) { String productname = request.getParameter("productname"); String productprice = request.getParameter("productprice"); String productid=request.getParameter("productid"); MasterOrder m = new MasterOrder(); m.setData1(Integer.parseInt(productid),productname,Float.parseFloat(productprice)); arl.add(m); out.println("<html><head><title>Added Member</title></head>"); out.println("<body><center><h2> Add to Cart :</h2><br>"); //out.println("<ul>"); out.println("<table><tr><th>Product Name</th><th>Product Price</th></tr>"); for(int i =0;i<arl.size();i++) { MasterOrder mem = (MasterOrder)arl.get(i); out.println("<tr><td>"+mem.getProductname()+" </td><td>"+mem.getProductprice()+"</td></tr>"); } out.println("</table>"); customerBean bean = new customerBean(); out.println("<a href=\"/orderList?&opn=add&now()&customerid" + bean.getCustomerid() + "\">Buy</a>"); //out.println("<tr><td>"+m.getProductname()+"</td><td>"+m.getProductprice()+"</td></tr></table>"); out.println("</body></html>"); } } // out.println("<!--content-->"); //// out.println("</div>"); out.println("</div> <!-- end of templatmeo_content -->"); out.println("</div> <!-- end of templatemo_wrapper -->"); out.println("<div id=\"templatemo_footer_wrapper\">"); dispatcher = request.getRequestDispatcher("/design/adminHomeFooter.html"); dispatcher.include(request, response); out.println("<!--footer-->"); out.println("<!--footer-->"); out.println("</div> <!-- end of footer_wrapper -->"); out.println("<!--line below footer-->"); out.println("<!--line below footer-->"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package fr.lteconsulting; import java.io.IOException; import java.security.Key; import java.util.Map; import javax.crypto.spec.SecretKeySpec; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureException; public class JWTFilter implements Filter { static Key key = createKey(); private final static ThreadLocal<Integer> currentClaimsHashCode = new ThreadLocal<>(); @Override public void init(FilterConfig arg0) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { String jwtPayload = Tools.getCookie((HttpServletRequest) request, "JJWTID"); if (jwtPayload != null) { try { Jws<Claims> claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwtPayload); JWTTools.setClaims(claims.getBody()); currentClaimsHashCode.set(claims.getBody().hashCode()); } catch (SignatureException e) { } } } chain.doFilter(request, response); if (response instanceof HttpServletResponse) { Map<String, Object> claims = JWTTools.getClaims(); Integer currentHashCode = claims != null ? claims.hashCode() : 0; if (!currentHashCode.equals(currentClaimsHashCode.get())) { String payload = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, key).compact(); ((HttpServletResponse) response).addCookie(new Cookie("JJWTID", payload)); } JWTTools.setClaims(null); currentClaimsHashCode.set(null); } } @Override public void destroy() { } private static Key createKey() { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; byte[] apiKeySecretBytes = "alja lkejhe kjhdaoiuha oisjlkaj shakhs ius hlajka sjaskhas jhskjhadg kjagy aufygfakhfkjhg" .getBytes(); Key key = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); return key; } }
/* ***************************************** * CSCI205 - Software Engineering and Design * Spring 2015 * * Name: Morgan Eckenroth * Date: Mar 20, 2015 * Time: 10:26:45 AM * * Project: csci205 * Package: hw02 * File: WaveVisView * Description: * Main GUI builder file for Waveform Visualizer * **************************************** */ package hw02.view; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextField; /** * * @author Morgan Eckenroth */ public class WaveVisView extends javax.swing.JFrame { /** * Creates new form MainView */ public WaveVisView() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { channelGroup = new javax.swing.ButtonGroup(); javax.swing.JPanel OptionsPanel = new javax.swing.JPanel(); rdbtnOneChannel = new javax.swing.JRadioButton(); rdbtnTwoChannel = new javax.swing.JRadioButton(); javax.swing.JLabel lblChannels = new javax.swing.JLabel(); javax.swing.JLabel lblViews = new javax.swing.JLabel(); btnPlay = new javax.swing.JButton(); btnPause = new javax.swing.JButton(); btnStop = new javax.swing.JButton(); scrbarZoomBar = new javax.swing.JScrollBar(); javax.swing.JLabel lblZoom = new javax.swing.JLabel(); txtFieldTimeSkip = new javax.swing.JTextField(); javax.swing.JLabel lblTimeJump = new javax.swing.JLabel(); txtfldZoomMin = new javax.swing.JTextField(); javax.swing.JLabel lblZoomMin = new javax.swing.JLabel(); txtfldZoomMax = new javax.swing.JTextField(); javax.swing.JLabel lblZoomMax = new javax.swing.JLabel(); scrollPanel = new javax.swing.JPanel(); javax.swing.JPanel singleScrPanel = new javax.swing.JPanel(); waveScrollPane = new javax.swing.JScrollPane(); javax.swing.JPanel doubleScrPanel = new javax.swing.JPanel(); waveScrollPaneSplit1 = new javax.swing.JScrollPane(); waveScrollPaneSplit2 = new javax.swing.JScrollPane(); javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar(); javax.swing.JMenu menuBarItemFile = new javax.swing.JMenu(); fileMenuItemNew = new javax.swing.JMenu(); newMenuItemSine = new javax.swing.JMenuItem(); newMenuItemSquare = new javax.swing.JMenuItem(); newMenuItemTriangle = new javax.swing.JMenuItem(); newMenuItemSawtooth = new javax.swing.JMenuItem(); fileMenuItemOpen = new javax.swing.JMenuItem(); fileMenuItemExit = new javax.swing.JMenuItem(); viewMenuItemSplitSync = new javax.swing.JMenu(); viewMenuItemSplitSyncChkBox = new javax.swing.JCheckBoxMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Waveform Visualizer"); setResizable(false); OptionsPanel.setPreferredSize(new java.awt.Dimension(150, 350)); OptionsPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); channelGroup.add(rdbtnOneChannel); rdbtnOneChannel.setText("Single"); rdbtnOneChannel.setFocusable(false); OptionsPanel.add(rdbtnOneChannel, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, -1, -1)); channelGroup.add(rdbtnTwoChannel); rdbtnTwoChannel.setText("Double"); rdbtnTwoChannel.setFocusable(false); OptionsPanel.add(rdbtnTwoChannel, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 70, -1, -1)); lblChannels.setText("Channel"); OptionsPanel.add(lblChannels, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 10, -1, -1)); lblViews.setText("View"); OptionsPanel.add(lblViews, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 30, -1, -1)); btnPlay.setText("Play"); btnPlay.setFocusable(false); OptionsPanel.add(btnPlay, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 100, -1, -1)); btnPause.setText("Pause"); btnPause.setFocusable(false); OptionsPanel.add(btnPause, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 140, -1, -1)); btnStop.setText("Stop"); btnStop.setFocusable(false); OptionsPanel.add(btnStop, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, -1, -1)); scrbarZoomBar.setBlockIncrement(2); scrbarZoomBar.setMaximum(10); scrbarZoomBar.setMinimum(-10); scrbarZoomBar.setToolTipText(""); scrbarZoomBar.setVisibleAmount(1); scrbarZoomBar.setAutoscrolls(true); scrbarZoomBar.setFocusable(false); OptionsPanel.add(scrbarZoomBar, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 250, -1, 130)); lblZoom.setText("Zoom"); OptionsPanel.add(lblZoom, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 230, -1, -1)); txtFieldTimeSkip.setColumns(5); txtFieldTimeSkip.setToolTipText("Insert time in seconds in decimal format"); OptionsPanel.add(txtFieldTimeSkip, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 210, -1, -1)); lblTimeJump.setText("Time Jump"); OptionsPanel.add(lblTimeJump, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 190, -1, -1)); txtfldZoomMin.setColumns(4); OptionsPanel.add(txtfldZoomMin, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 340, -1, -1)); lblZoomMin.setText("Zoom Min"); OptionsPanel.add(lblZoomMin, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 320, -1, -1)); txtfldZoomMax.setColumns(4); OptionsPanel.add(txtfldZoomMax, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 280, -1, -1)); lblZoomMax.setText("Zoom Max"); OptionsPanel.add(lblZoomMax, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 260, -1, -1)); getContentPane().add(OptionsPanel, java.awt.BorderLayout.LINE_START); scrollPanel.setPreferredSize(new java.awt.Dimension(800, 380)); scrollPanel.setLayout(new java.awt.CardLayout()); waveScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); waveScrollPane.setAutoscrolls(true); waveScrollPane.setDoubleBuffered(true); waveScrollPane.setVerifyInputWhenFocusTarget(false); javax.swing.GroupLayout singleScrPanelLayout = new javax.swing.GroupLayout(singleScrPanel); singleScrPanel.setLayout(singleScrPanelLayout); singleScrPanelLayout.setHorizontalGroup( singleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 800, Short.MAX_VALUE) .addGroup(singleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(singleScrPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(waveScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 776, Short.MAX_VALUE) .addContainerGap())) ); singleScrPanelLayout.setVerticalGroup( singleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 380, Short.MAX_VALUE) .addGroup(singleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, singleScrPanelLayout.createSequentialGroup() .addComponent(waveScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 368, Short.MAX_VALUE) .addContainerGap())) ); scrollPanel.add(singleScrPanel, "SINGLE"); waveScrollPaneSplit1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); waveScrollPaneSplit1.setAutoscrolls(true); waveScrollPaneSplit1.setDoubleBuffered(true); waveScrollPaneSplit2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); waveScrollPaneSplit2.setAutoscrolls(true); waveScrollPaneSplit2.setDoubleBuffered(true); javax.swing.GroupLayout doubleScrPanelLayout = new javax.swing.GroupLayout(doubleScrPanel); doubleScrPanel.setLayout(doubleScrPanelLayout); doubleScrPanelLayout.setHorizontalGroup( doubleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(doubleScrPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(doubleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(waveScrollPaneSplit1, javax.swing.GroupLayout.DEFAULT_SIZE, 776, Short.MAX_VALUE) .addComponent(waveScrollPaneSplit2)) .addContainerGap()) ); doubleScrPanelLayout.setVerticalGroup( doubleScrPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(doubleScrPanelLayout.createSequentialGroup() .addComponent(waveScrollPaneSplit1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, 0) .addComponent(waveScrollPaneSplit2, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)) ); scrollPanel.add(doubleScrPanel, "DOUBLE"); getContentPane().add(scrollPanel, java.awt.BorderLayout.CENTER); menuBarItemFile.setText("File"); fileMenuItemNew.setText("New"); newMenuItemSine.setText("Sine Wave"); fileMenuItemNew.add(newMenuItemSine); newMenuItemSquare.setText("Square Wave"); fileMenuItemNew.add(newMenuItemSquare); newMenuItemTriangle.setText("Triangle Wave"); fileMenuItemNew.add(newMenuItemTriangle); newMenuItemSawtooth.setText("Sawtooth Wave"); fileMenuItemNew.add(newMenuItemSawtooth); menuBarItemFile.add(fileMenuItemNew); fileMenuItemOpen.setText("Open"); menuBarItemFile.add(fileMenuItemOpen); fileMenuItemExit.setText("Exit"); menuBarItemFile.add(fileMenuItemExit); menuBar.add(menuBarItemFile); viewMenuItemSplitSync.setText("View"); viewMenuItemSplitSyncChkBox.setSelected(true); viewMenuItemSplitSyncChkBox.setText("Split Channel Sync"); viewMenuItemSplitSync.add(viewMenuItemSplitSyncChkBox); menuBar.add(viewMenuItemSplitSync); setJMenuBar(menuBar); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnPause; private javax.swing.JButton btnPlay; private javax.swing.JButton btnStop; private javax.swing.ButtonGroup channelGroup; private javax.swing.JMenuItem fileMenuItemExit; private javax.swing.JMenu fileMenuItemNew; private javax.swing.JMenuItem fileMenuItemOpen; private javax.swing.JMenuItem newMenuItemSawtooth; private javax.swing.JMenuItem newMenuItemSine; private javax.swing.JMenuItem newMenuItemSquare; private javax.swing.JMenuItem newMenuItemTriangle; private javax.swing.JRadioButton rdbtnOneChannel; private javax.swing.JRadioButton rdbtnTwoChannel; private javax.swing.JScrollBar scrbarZoomBar; private javax.swing.JPanel scrollPanel; private javax.swing.JTextField txtFieldTimeSkip; private javax.swing.JTextField txtfldZoomMax; private javax.swing.JTextField txtfldZoomMin; private javax.swing.JMenu viewMenuItemSplitSync; private javax.swing.JCheckBoxMenuItem viewMenuItemSplitSyncChkBox; private javax.swing.JScrollPane waveScrollPane; private javax.swing.JScrollPane waveScrollPaneSplit1; private javax.swing.JScrollPane waveScrollPaneSplit2; // End of variables declaration//GEN-END:variables public JButton getBtnPause() { return btnPause; } public JButton getBtnPlay() { return btnPlay; } public JButton getBtnStop() { return btnStop; } public JMenuItem getFileMenuItemExit() { return fileMenuItemExit; } public JMenuItem getFileMenuItemNew() { return fileMenuItemNew; } public JMenuItem getFileMenuItemOpen() { return fileMenuItemOpen; } public JRadioButton getRdbtnOneChannel() { return rdbtnOneChannel; } public JRadioButton getRdbtnTwoChannel() { return rdbtnTwoChannel; } public JScrollPane getWaveScrollPane() { return waveScrollPane; } public JMenuItem getNewMenuItemSine() { return newMenuItemSine; } public JMenuItem getNewMenuItemSquare() { return newMenuItemSquare; } public JMenuItem getNewMenuItemTriangle() { return newMenuItemTriangle; } public JScrollBar getScrbarZoomBar() { return scrbarZoomBar; } public JScrollPane getWaveScrollPaneSplit1() { return waveScrollPaneSplit1; } public JScrollPane getWaveScrollPaneSplit2() { return waveScrollPaneSplit2; } public JPanel getScrollPanel() { return scrollPanel; } public JMenu getViewMenuItemSplitSync() { return viewMenuItemSplitSync; } public JCheckBoxMenuItem getViewMenuItemSplitSyncChkBox() { return viewMenuItemSplitSyncChkBox; } public JMenuItem getNewMenuItemSawtooth() { return newMenuItemSawtooth; } public JTextField getTxtFieldTimeSkip() { return txtFieldTimeSkip; } public JTextField getTxtfldZoomMax() { return txtfldZoomMax; } public JTextField getTxtfldZoomMin() { return txtfldZoomMin; } }
package com.lingnet.vocs.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import com.lingnet.common.entity.BaseEntity; /** * 工单 * * @ClassName: WorkOrder * @Description: TODO * @author 薛硕 * @date 2017年6月28日 上午8:54:43 * */ @Entity @Table(name = "WORKORDER") public class WorkOrder extends BaseEntity implements Serializable { private static final long serialVersionUID = -4299230960187789412L; // 标题 private String workOrderTitle; // 工单号 private String workOrderCode; // 工单 类型 private String workOrderType; // 故障类别 private String faultType; // 商定维修时间 private String expectDate; // 优先级 private String workOrderLevel; // 状态0.新建 1.已发布 2.指派中 3.待处理 4.待评价 5.已评价 6.已结单 7.转派中 8.已废弃 9.已退回 10.处理中 private String state; // 设备编号 private String equipmentCode; // 工单来源 private String resource; // 创建人 private String createperson; // 客户 private String customer; // 客户 联系人 private String contacts; // 客户 电话 private String customerPhone; // 客户 手机号 private String customerCellphone; // 客户 地址 private String customerAddress; // 地区关联总负责人 private String partner; // 地区关联总负责人 电话 private String partnerPhone; // 地区关联总负责人 手机号 private String partnerCellphone; // 区域责任人 private String replayPerson; // 区域责任人 电话 private String replayPhone; // 区域责任人 手机号 private String replayCellphone; // 销售人 private String sales; // 销售人电话呢 private String salesPhone; // 特殊要求 private String specificReq; // 故障说明 private String faultExplain; // 附件 private String uploadFile; // 工单跟进 private String workOrderFollow; // 接单时间 private Date receive; // 结单时间 private Date checkDate; // 申请转派原因 private String cause; // 应收物料费用 private Double recItemCharges; // 实收物料费用 private Double reaItemCharges; // 应收维护费用 private Double recMainterCharges; // 时候维护费用 private Double reaMainterCharges; // 转工单id private String transferOrdersId; // 实际维修时间 private String actualMaintenanceDate; // 评分 private String score; // 意见 private String opinion; //客户确认签名 private String confirm; //客户确认签字时间 private Date confirmDate; private String province;// 省 private String city;// 市 private String district;// 区 // 临时字段 用于接收转派页面传入的多个维护人员id private String replayPersonList; private String customerName; private String partnerName; private String startTime; private String endTime; // 处理结果 private String hfjg; private String czType; /********************************************************** get set ****************************************************/ @Column(name = "work_order_title") public String getWorkOrderTitle() { return workOrderTitle; } public void setWorkOrderTitle(String workOrderTitle) { this.workOrderTitle = workOrderTitle; } @Column(name = "work_order_code") public String getWorkOrderCode() { return workOrderCode; } public void setWorkOrderCode(String workOrderCode) { this.workOrderCode = workOrderCode; } @Column(name = "work_order_type") public String getWorkOrderType() { return workOrderType; } public void setWorkOrderType(String workOrderType) { this.workOrderType = workOrderType; } @Column(name = "fault_type") public String getFaultType() { return faultType; } public void setFaultType(String faultType) { this.faultType = faultType; } @Column(name = "expect_date") public String getExpectDate() { return expectDate; } public void setExpectDate(String expectDate) { this.expectDate = expectDate; } @Column(name = "work_order_level") public String getWorkOrderLevel() { return workOrderLevel; } public void setWorkOrderLevel(String workOrderlevel) { this.workOrderLevel = workOrderlevel; } @Column(name = "state") public String getState() { return state; } public void setState(String state) { this.state = state; } @Column(name = "equipment_code") public String getEquipmentCode() { return equipmentCode; } public void setEquipmentCode(String equipmentCode) { this.equipmentCode = equipmentCode; } @Column(name = "resource") public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Column(name = "createperson") public String getCreateperson() { return createperson; } public void setCreateperson(String createperson) { this.createperson = createperson; } @Column(name = "customer") public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } @Column(name = "customer_phone") public String getCustomerPhone() { return customerPhone; } public void setCustomerPhone(String customerPhone) { this.customerPhone = customerPhone; } @Column(name = "customer_cell_phone") public String getCustomerCellphone() { return customerCellphone; } public void setCustomerCellphone(String customerCellphone) { this.customerCellphone = customerCellphone; } @Column(name = "partner") public String getPartner() { return partner; } public void setPartner(String partner) { this.partner = partner; } @Column(name = "partner_phone") public String getPartnerPhone() { return partnerPhone; } public void setPartnerPhone(String partnerPhone) { this.partnerPhone = partnerPhone; } @Column(name = "partner_cell_phone") public String getPartnerCellphone() { return partnerCellphone; } public void setPartnerCellphone(String partnerCellphone) { this.partnerCellphone = partnerCellphone; } @Column(name = "replay_person") public String getReplayPerson() { return replayPerson; } public void setReplayPerson(String replayPerson) { this.replayPerson = replayPerson; } @Column(name = "replay_phone") public String getReplayPhone() { return replayPhone; } public void setReplayPhone(String replayPhone) { this.replayPhone = replayPhone; } @Column(name = "replay_cell_phone") public String getReplayCellphone() { return replayCellphone; } public void setReplayCellphone(String replayCellphone) { this.replayCellphone = replayCellphone; } @Column(name = "sales") public String getSales() { return sales; } public void setSales(String sales) { this.sales = sales; } @Column(name = "sales_phone") public String getSalesPhone() { return salesPhone; } public void setSalesPhone(String salesPhone) { this.salesPhone = salesPhone; } @Column(name = "specific_req") public String getSpecificReq() { return specificReq; } public void setSpecificReq(String specificReq) { this.specificReq = specificReq; } @Column(name = "fault_explain") public String getFaultExplain() { return faultExplain; } public void setFaultExplain(String faultExplain) { this.faultExplain = faultExplain; } @Column(name = "upload_file") public String getUploadFile() { return uploadFile; } public void setUploadFile(String uploadFile) { this.uploadFile = uploadFile; } @Column(name = "work_order_follow") public String getWorkOrderFollow() { return workOrderFollow; } public void setWorkOrderFollow(String workOrderFollow) { this.workOrderFollow = workOrderFollow; } @Column(name = "customer_address") public String getCustomerAddress() { return customerAddress; } public void setCustomerAddress(String customerAddress) { this.customerAddress = customerAddress; } @Column(name = "check_date") public Date getCheckDate() { return checkDate; } public void setCheckDate(Date checkDate) { this.checkDate = checkDate; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } @Transient public String getReplayPersonList() { return replayPersonList; } public void setReplayPersonList(String replayPersonList) { this.replayPersonList = replayPersonList; } @Column(name = "rec_item_charges") public Double getRecItemCharges() { return recItemCharges; } public void setRecItemCharges(Double recItemCharges) { this.recItemCharges = recItemCharges; } @Column(name = "rea_item_charges") public Double getReaItemCharges() { return reaItemCharges; } public void setReaItemCharges(Double reaItemCharges) { this.reaItemCharges = reaItemCharges; } @Column(name = "rec_mainter_charges") public Double getRecMainterCharges() { return recMainterCharges; } public void setRecMainterCharges(Double recMainterCharges) { this.recMainterCharges = recMainterCharges; } @Column(name = "rea_mainter_charges") public Double getReaMainterCharges() { return reaMainterCharges; } public void setReaMainterCharges(Double reaMainterCharges) { this.reaMainterCharges = reaMainterCharges; } @Transient public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } @Transient public String getPartnerName() { return partnerName; } public void setPartnerName(String partnerName) { this.partnerName = partnerName; } @Transient public String getHfjg() { return hfjg; } public void setHfjg(String hfjg) { this.hfjg = hfjg; } public Date getReceive() { return receive; } public void setReceive(Date receive) { this.receive = receive; } @Column(name = "transfer_orders_id") public String getTransferOrdersId() { return transferOrdersId; } public void setTransferOrdersId(String transferOrdersId) { this.transferOrdersId = transferOrdersId; } @Column(name = "actual_maintenanceDate") public String getActualMaintenanceDate() { return actualMaintenanceDate; } public void setActualMaintenanceDate(String actualMaintenanceDate) { this.actualMaintenanceDate = actualMaintenanceDate; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getOpinion() { return opinion; } public void setOpinion(String opinion) { this.opinion = opinion; } @Transient public String getCzType() { return czType; } public void setCzType(String czType) { this.czType = czType; } public String getContacts() { return contacts; } public void setContacts(String contacts) { this.contacts = contacts; } @Transient public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } @Transient public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getConfirm() { return confirm; } public void setConfirm(String confirm) { this.confirm = confirm; } @Column(name="confirm_date") public Date getConfirmDate() { return confirmDate; } public void setConfirmDate(Date confirmDate) { this.confirmDate = confirmDate; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district; } }
package day30exeption; public class Sorular2 { public static void main(String[] args) { try { hop(); }catch(Exception e) { e.printStackTrace(); //printStackTrace () methodu Exception'lsrin nerde olustugunun //detayli bilgisini verir //Excdption satirlarini olusum sirasina gore console 'de gosterir. } } private static void hop() { throw new RuntimeException("cannot hop"); } }
package com.example.finalproject; import android.os.AsyncTask; public class MatchProfileTask extends AsyncTask<Void, Void, Void> { MainActivity ma; String matchedId; MatchProfileTask(MainActivity act,String profileId){ ma = act; matchedId = profileId; } @Override protected Void doInBackground(Void... params) { ma.dbit.match(Long.valueOf(matchedId)); return null; } @Override protected void onPostExecute(final Void succ) { } }
package com.hesoyam.pharmacy.appointment.service; import com.hesoyam.pharmacy.appointment.dto.FreeCheckupDTO; import com.hesoyam.pharmacy.appointment.exceptions.CheckupNotFoundException; import com.hesoyam.pharmacy.appointment.model.CheckUp; import com.hesoyam.pharmacy.user.exceptions.DermatologistNotFoundException; import com.hesoyam.pharmacy.user.exceptions.PatientNotFoundException; import com.hesoyam.pharmacy.user.model.Dermatologist; import com.hesoyam.pharmacy.user.model.Patient; import com.hesoyam.pharmacy.user.model.User; import java.time.LocalDateTime; import java.util.List; public interface ICheckUpService { CheckUp createFreeCheckUp(User administrator, FreeCheckupDTO freeCheckupDTO, Long dermatologistId) throws DermatologistNotFoundException, IllegalAccessException; List<CheckUp> getUpcomingFreeCheckupsByEmployeeAndPharmacy(Long dermatologistId, String pharmacyId); List<CheckUp> getUpcomingFreeCheckupsByPharmacy(Long pharmacyId); List<CheckUp> getUpcomingCheckupsByPatient(Long id); List<CheckUp> getAllCompletedCheckupsByPatient(Long id); CheckUp findById(Long id) throws CheckupNotFoundException; CheckUp update(CheckUp checkup) throws CheckupNotFoundException; CheckUp cancelCheckup(Patient patient, LocalDateTime from, Dermatologist user); CheckUp updateCheckupAfterAppointment(Patient patient, LocalDateTime from, String report, Dermatologist dermatologist) throws CheckupNotFoundException; List<CheckUp> getAllCheckUpsForPatientAndDermatologist(Patient patient, Dermatologist user); FreeCheckupDTO reserve(FreeCheckupDTO freeCheckupDTO, User user) throws CheckupNotFoundException, PatientNotFoundException; }