text
stringlengths
10
2.72M
package com.example.jkl.pojo; import lombok.Data; import java.util.Date; import javax.persistence.*; @Data @Table(name = "t_goods") public class Goods { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "g_name") private String gName; @Column(name = "g_count") private Integer gCount; @Column(name = "g_price") private Double gPrice; private String img1; private String img2; private String img3; private String img4; @Column(name = "g_brief") private String gBrief; @Column(name = "g_state") private Short gState; @Column(name = "g_address") private String gAddress; @Column(name = "create_time") private Date createTime; @Column(name = "update_time") private Date updateTime; /** * @return id */ public Integer getId() { return id; } /** * @param id */ public void setId(Integer id) { this.id = id; } /** * @return g_name */ public String getgName() { return gName; } /** * @param gName */ public void setgName(String gName) { this.gName = gName == null ? null : gName.trim(); } /** * @return g_count */ public Integer getgCount() { return gCount; } /** * @param gCount */ public void setgCount(Integer gCount) { this.gCount = gCount; } /** * @return g_price */ public Double getgPrice() { return gPrice; } /** * @param gPrice */ public void setgPrice(Double gPrice) { this.gPrice = gPrice; } /** * @return img1 */ public String getImg1() { return img1; } /** * @param img1 */ public void setImg1(String img1) { this.img1 = img1 == null ? null : img1.trim(); } /** * @return img2 */ public String getImg2() { return img2; } /** * @param img2 */ public void setImg2(String img2) { this.img2 = img2 == null ? null : img2.trim(); } /** * @return img3 */ public String getImg3() { return img3; } /** * @param img3 */ public void setImg3(String img3) { this.img3 = img3 == null ? null : img3.trim(); } /** * @return img4 */ public String getImg4() { return img4; } /** * @param img4 */ public void setImg4(String img4) { this.img4 = img4 == null ? null : img4.trim(); } /** * @return g_brief */ public String getgBrief() { return gBrief; } /** * @param gBrief */ public void setgBrief(String gBrief) { this.gBrief = gBrief == null ? null : gBrief.trim(); } /** * @return g_state */ public Short getgState() { return gState; } /** * @param gState */ public void setgState(Short gState) { this.gState = gState; } /** * @return g_address */ public String getgAddress() { return gAddress; } /** * @param gAddress */ public void setgAddress(String gAddress) { this.gAddress = gAddress == null ? null : gAddress.trim(); } /** * @return create_time */ public Date getCreateTime() { return createTime; } /** * @param createTime */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * @return update_time */ public Date getUpdateTime() { return updateTime; } /** * @param updateTime */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
package com.example.retail.controllers.retailer.edibleproducts_retailer; import com.example.retail.services.edibleproducts.EdibleProductsService; import com.example.retail.util.CreateResponse; import com.example.retail.util.JWTDetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Map; @RestController @RequestMapping("/api/v1/retailer/edibleProducts") @CrossOrigin(origins = "*") public class EdibleProductsRetailerController { @Autowired EdibleProductsService edibleProductsService; @Autowired CreateResponse createResponse; @Autowired JWTDetails jwtDetails; @GetMapping("/welcome") public String welcome() { return "Welcome!"; } @GetMapping(value = "/findAll") public ResponseEntity<?> findAll(){ try { List<?> finalRes = edibleProductsService.findAllEdibleProductsWithInventory(); return ResponseEntity.status(200).body(createResponse.createSuccessResponse( 200, finalRes.size() + " items found", finalRes )); } catch (Exception e) { return ResponseEntity.status(500).body( createResponse.createErrorResponse( 500, e.getLocalizedMessage(), "NA" ) ); } } @RequestMapping(value = "/add", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<Object> addEdibleProduct( HttpServletRequest request, @ModelAttribute AddEdibleProductsRequestBody newProduct, @RequestParam("edibleProductImages") ArrayList<MultipartFile> edibleProductImages) { try { return edibleProductsService.addEdibleProduct(request, edibleProductImages, newProduct); } catch (Exception e) { return ResponseEntity.status(500).body( createResponse.createErrorResponse( 500, e.getMessage(), e.toString() ) ); } } @RequestMapping(value = "/update/{subId}/increamentQuantity/{quantity}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> increamentEdibleProductsQuantity(@PathVariable Float quantity, @PathVariable String subId, HttpServletRequest request) { try { if(quantity < 0) { return ResponseEntity.status(400).body( createResponse.createErrorResponse( 400, "Quantity has to be greater that 0", "NA" ) ); } String addedBy = jwtDetails.userName(request); Map<String, Object> finalRes = edibleProductsService.increamentEdibleProductsQuantity(quantity, subId, addedBy); return ResponseEntity.status(201).body( createResponse.createSuccessResponse( 201, "Quantity updated by: " + quantity, finalRes ) ); } catch (Exception e) { return ResponseEntity.status(500).body( createResponse.createErrorResponse( 500, e.getLocalizedMessage(), "NA" ) ); } } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * DxjDeviceId generated by hbm2java */ public class DxjDeviceId implements java.io.Serializable { private String deviceId; private String deviceName; private String wcName; private String tableCount; private String wcId; public DxjDeviceId() { } public DxjDeviceId(String deviceId, String deviceName, String wcName, String tableCount, String wcId) { this.deviceId = deviceId; this.deviceName = deviceName; this.wcName = wcName; this.tableCount = tableCount; this.wcId = wcId; } public String getDeviceId() { return this.deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getDeviceName() { return this.deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getWcName() { return this.wcName; } public void setWcName(String wcName) { this.wcName = wcName; } public String getTableCount() { return this.tableCount; } public void setTableCount(String tableCount) { this.tableCount = tableCount; } public String getWcId() { return this.wcId; } public void setWcId(String wcId) { this.wcId = wcId; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof DxjDeviceId)) return false; DxjDeviceId castOther = (DxjDeviceId) other; return ((this.getDeviceId() == castOther.getDeviceId()) || (this.getDeviceId() != null && castOther.getDeviceId() != null && this.getDeviceId().equals(castOther.getDeviceId()))) && ((this.getDeviceName() == castOther.getDeviceName()) || (this.getDeviceName() != null && castOther.getDeviceName() != null && this.getDeviceName().equals(castOther.getDeviceName()))) && ((this.getWcName() == castOther.getWcName()) || (this.getWcName() != null && castOther.getWcName() != null && this.getWcName().equals(castOther.getWcName()))) && ((this.getTableCount() == castOther.getTableCount()) || (this.getTableCount() != null && castOther.getTableCount() != null && this.getTableCount().equals(castOther.getTableCount()))) && ((this.getWcId() == castOther.getWcId()) || (this.getWcId() != null && castOther.getWcId() != null && this.getWcId().equals(castOther.getWcId()))); } public int hashCode() { int result = 17; result = 37 * result + (getDeviceId() == null ? 0 : this.getDeviceId().hashCode()); result = 37 * result + (getDeviceName() == null ? 0 : this.getDeviceName().hashCode()); result = 37 * result + (getWcName() == null ? 0 : this.getWcName().hashCode()); result = 37 * result + (getTableCount() == null ? 0 : this.getTableCount().hashCode()); result = 37 * result + (getWcId() == null ? 0 : this.getWcId().hashCode()); return result; } }
package com.cnk.travelogix.operations.facades.populator; import de.hybris.platform.converters.Populator; import de.hybris.platform.enumeration.EnumerationService; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import com.cnk.travelogix.client.core.b2bunit.model.TravelogixB2BUnitModel; import com.cnk.travelogix.operations.data.EnumerationDto; import com.cnk.travelogix.operations.data.TravelogixClientDetailsData; /** * The travelogix B2B unit client populator */ public class TravelogixB2BClientPopulator implements Populator<TravelogixB2BUnitModel, TravelogixClientDetailsData> { @Resource private EnumerationService enumerationService; @Override public void populate(final TravelogixB2BUnitModel source, final TravelogixClientDetailsData target) throws ConversionException { target.setClientId(source.getUid()); target.setClientName(source.getLocName()); target.setClientType(getClientType(source)); target.setClientCategory(getClientCategory(source)); target.setClientSubCategory(getClientSubCategory(source)); } public List<EnumerationDto> getClientType(final TravelogixB2BUnitModel source) { final List<EnumerationDto> dtos = new ArrayList<>(); final EnumerationDto dto = new EnumerationDto(); dto.setCode(source.getTrvlClientType().getCode()); dto.setName(enumerationService.getEnumerationName(source.getTrvlClientType())); dtos.add(dto); return dtos; } public List<EnumerationDto> getClientCategory(final TravelogixB2BUnitModel source) { final List<EnumerationDto> dtos = new ArrayList<>(); final EnumerationDto dto = new EnumerationDto(); dto.setCode(source.getClientCategory().getCode()); dto.setName(enumerationService.getEnumerationName(source.getClientCategory())); dtos.add(dto); return dtos; } public List<EnumerationDto> getClientSubCategory(final TravelogixB2BUnitModel source) { final List<EnumerationDto> dtos = new ArrayList<>(); final EnumerationDto dto = new EnumerationDto(); dto.setCode(source.getClientSubCategory().getCode()); dto.setName(enumerationService.getEnumerationName(source.getClientSubCategory())); dtos.add(dto); return dtos; } }
package github.vatsal.popularmoviesapp.Utils; /** * Created by * --Vatsal Bajpai under * --AppyWare on * --17/06/16 at * --11:41 PM in * --PopularMoviesApp */ public class Constants { public static final String MOVIE_ITEM_KEY = "movieItem"; }
package main.java.com.Arkioner.schibstedTest.core.security.service; import com.sun.net.httpserver.HttpExchange; import main.java.com.Arkioner.schibstedTest.core.http.HttpSession; import main.java.com.Arkioner.schibstedTest.core.http.session.Session; import main.java.com.Arkioner.schibstedTest.core.security.token.UserToken; import main.java.com.Arkioner.schibstedTest.core.security.token.UserTokenNotFoundException; import java.util.Date; /** * Created by arkioner on 17/05/15. */ public class AuthenticationService { private static AuthenticationService instance; public static AuthenticationService getInstance(){ if(instance == null){ instance = new AuthenticationService(); } return instance; } public UserToken getAuthentication(HttpExchange exchange) throws UserTokenNotFoundException, AuthenticationExpiredException { Session session = (Session) exchange.getAttribute(HttpSession.sessionKey); UserToken userToken = (UserToken) session.get(HttpSession.userTokenKey); if (userToken == null){ throw new UserTokenNotFoundException("You are anonymous"); }else if(userToken.isExpired()){ throw new AuthenticationExpiredException("The token is expired"); } UserTokenService.getInstance().renewUserToken(userToken); return userToken; } }
package calculations; import java.util.Scanner; public class DeterminingCompoundInterest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("What is the principal amount? "); double principalAmount = scanner.nextDouble(); System.out.print("What is the rate? "); double rate = scanner.nextDouble() / 100; System.out.print("What is the number of years? "); int numberOfYears = scanner.nextInt(); System.out.print("What is the number of times the interest\n" + "is compounded per year? "); int numberOfTimes = scanner.nextInt(); double amountAtTheEndOfInvestment =principalAmount * Math.pow(1 + (rate / numberOfTimes), numberOfTimes * numberOfYears); System.out.print(principalAmount + " invested at " + rate * 100 + "% for " + numberOfYears + " years\n" + "compounded " + numberOfTimes + " times per year is $" + amountAtTheEndOfInvestment + "."); } } //The pow() function computes the power of a number
package com.apprisingsoftware.xmasrogue.io; import com.apprisingsoftware.xmasrogue.ChristmasRogue; import com.apprisingsoftware.xmasrogue.util.Coord; import java.awt.Color; import java.awt.event.KeyEvent; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; public class VictoryScreen extends MenuScreen implements NestedInputAcceptingAsciiScreen { public VictoryScreen(int width, int height) { super(width, height, new HashMap<Coord, Message>() {{ char[] title = {(char)17,' ',' ','M','E','R','R','Y',' ','C','H','R','I','S','T','M','A','S',' ',' ',(char)16}; for (int i=0; i<title.length; i++) { put(new Coord((width - title.length) / 2 + i, 3), new Message(String.valueOf(title[i]), i%2==0 ? Color.RED : Color.GREEN)); } String[] story = { "A WINNER IS YOU", "", "Congratulations -- you've saved Christmas!", "", "[n] New Game", "[w] Wizard Mode", }; int maxLen = Arrays.stream(story).mapToInt(String::length).max().getAsInt(); for (int i=0; i<story.length; i++) { put(new Coord((width - maxLen) / 2, 5 + i), new Message(story[i], Color.WHITE)); } }}); } @Override protected Color getBackgroundColor(int x, int y) { return Color.BLACK; } @Override public Collection<Coord> getUpdatedBackgroundTiles() { return Collections.emptyList(); } @Override public NestedInputAcceptingAsciiScreen respondToInput(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_N) { ChristmasRogue.setDEBUG(false); return new GameAsciiScreen(width, height, (int) System.currentTimeMillis()); } else if (e.getKeyCode() == KeyEvent.VK_W) { ChristmasRogue.setDEBUG(true); return new GameAsciiScreen(width, height, (int) System.currentTimeMillis()); } return null; } }
package dev.gerardo.shortener.utils; public interface Shortener { public String processUrl(String url); }
package com.jim.multipos.ui.products_expired.expired_products; import com.jim.multipos.core.Presenter; import com.jim.multipos.data.db.model.inventory.StockQueue; public interface ExpiredProductsFragmentPresenter extends Presenter { void onFilterClicked(); void search(String searchText); void onWriteOff(StockQueue stockQueue); void onOutVoice(StockQueue stockQueue); void onFilterApplied(int[] config); }
package com.example.ilham.obatherbal; public interface OnLoadMoreListener { void onLoadMore(); }
package com.nhatdear.sademo.activities; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import com.bumptech.glide.Glide; import com.facebook.login.LoginManager; import com.google.firebase.auth.FirebaseUser; import com.jaredrummler.materialspinner.MaterialSpinner; import com.nhatdear.sademo.R; import com.nhatdear.sademo.StashAwayApp; import com.nhatdear.sademo.components.MyCustomTextView; import com.nhatdear.sademo.database.SA_FirebaseDatabase; import com.nhatdear.sademo.fragments.SA_BarChartFragment; import com.nhatdear.sademo.fragments.SA_LineChartFragment; import com.nhatdear.sademo.helpers.RoundImageTransform; import com.nhatdear.sademo.helpers.SA_Helper; import com.nhatdear.sademo.models.SA_Portfolio; import com.nhatdear.sademo.models.SA_User; import java.util.ArrayList; import java.util.List; import static com.nhatdear.sademo.activities.SA_MainActivity.CHART_TYPE.BAR; import static com.nhatdear.sademo.activities.SA_MainActivity.CHART_TYPE.LINE; import static com.nhatdear.sademo.activities.SA_MainActivity.MODE.DAILY; import static com.nhatdear.sademo.activities.SA_MainActivity.MODE.MONTHLY; import static com.nhatdear.sademo.activities.SA_MainActivity.MODE.QUARTERLY; public class SA_MainActivity extends SA_BaseActivity implements NavigationView.OnNavigationItemSelectedListener { private static final String TAG = SA_MainActivity.class.getSimpleName(); private RadioGroup radioGroup1; private ArrayList<SA_Portfolio> arrayList; private int currentSearchYear = 2017; private MyCustomTextView tv_chart_name; public enum MODE { DAILY, QUARTERLY, MONTHLY } public enum CHART_TYPE { BAR, LINE } private MODE mode = MONTHLY; private CHART_TYPE chart_type = LINE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sa_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Vote me if you like this demo", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); SA_User currentUser = StashAwayApp.getInstance().getCurrentUser(); ImageView imageView = (ImageView)navigationView.getHeaderView(0).findViewById(R.id.imv_person); if (!TextUtils.isEmpty(currentUser.photoUrl)) { Glide.with(this).load(Uri.parse(currentUser.photoUrl)).centerCrop().transform(new RoundImageTransform(this)).into(imageView); } MyCustomTextView tv_username = (MyCustomTextView)navigationView.getHeaderView(0).findViewById(R.id.tv_username); tv_username.setText(currentUser.name); TextView tv_user_email = (TextView)navigationView.getHeaderView(0).findViewById(R.id.tv_user_email); tv_user_email.setText(currentUser.email); radioGroup1 = (RadioGroup)findViewById(R.id.radioGroup1); radioGroup1.setOnCheckedChangeListener((group, checkedId) -> { switch (checkedId) { case R.id.rbtn_daily: mode = DAILY; setDataToChart(arrayList, mode, chart_type); break; case R.id.rbtn_monthly: mode = MONTHLY; setDataToChart(arrayList, mode, chart_type); break; case R.id.rbtn_quarterly: mode = QUARTERLY; setDataToChart(arrayList, mode, chart_type); break; default: break; } }); tv_chart_name = (MyCustomTextView)findViewById(R.id.tv_chart_name); tv_chart_name.setText("REPORT OF "); MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner); spinner.setItems("2017", "2016", "2015"); spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() { @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) { currentSearchYear = Integer.parseInt(item); getDataFromFirebase(currentSearchYear, mode, chart_type); } }); getDataFromFirebase(currentSearchYear, mode, chart_type); } private void getDataFromFirebase(int _currentSearchYear, MODE _mode, CHART_TYPE _chart_type) { try { showProgressDialog("Loading portfolio data"); SA_FirebaseDatabase database = new SA_FirebaseDatabase(); database.getPortfolios(_currentSearchYear).subscribe(array->{ this.arrayList = array; setDataToChart(this.arrayList, _mode, _chart_type); hideProgressDialog(); },throwable -> { hideProgressDialog(); SA_Helper.showSnackbar(findViewById(R.id.main_view),throwable.getLocalizedMessage()); }); } catch (Exception e){ hideProgressDialog(); e.printStackTrace(); } } private void setDataToChart(ArrayList<SA_Portfolio> arrayList, MODE mode, CHART_TYPE chart_type) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction; switch (chart_type) { case BAR: fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_BarChartFragment.newInstance(arrayList, mode)).addToBackStack("BAR CHART"); fragmentTransaction.commit(); break; case LINE: fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_LineChartFragment.newInstance(arrayList, mode)).addToBackStack("LINE CHART"); fragmentTransaction.commit(); break; } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.sa__main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_logout) { String[] fileList = this.fileList(); for (String file : fileList) { this.deleteFile(file); } FirebaseUser user = mAuth.getCurrentUser(); if (user != null) { List<String> providers = user.getProviders(); if (providers != null) { if (providers.contains("facebook.com")) { LoginManager.getInstance().logOut(); } } } mAuth.signOut(); startActivity((new Intent(SA_MainActivity.this, SA_LoginActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)); return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_showAsBarChart) { chart_type = BAR; setDataToChart(arrayList,mode,chart_type); } else if (id == R.id.showAsLineChart) { chart_type = LINE; setDataToChart(arrayList,mode,chart_type); } else if (id == R.id.nav_referrals) { } else if (id == R.id.nav_support) { } else if (id == R.id.nav_setting) { } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
public class Main { public static void main(String[] args) { start(); } private static void start() { MainController mainController = new MainController(); mainController.getWord(); mainController.createListValidWords(); mainController.printValidWords(); start(); } }
package com.github.ovchingus.controller; import com.github.ovchingus.core.*; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; public class AppController { @FXML private TextArea textAreaArtist; /** * Artist scene */ @FXML private Button searchButtonArtist; private ObservableList<String> methodChooseListArtist = FXCollections.observableArrayList("Info", "Tracks", "Albums", "Search"); @FXML private ChoiceBox<String> methodChooseBoxArtist; @FXML private TextField artistNameTextFieldArtist; /** * Album scene */ @FXML private ChoiceBox<String> methodChooseBoxAlbum; @FXML private TextArea textAreaAlbum; @FXML private TextField artistNameTextFieldAlbum; @FXML private TextField albumNameTextFieldAlbum; @FXML private Button searchButtonAlbum; private ObservableList<String> methodChooseListAlbum = FXCollections.observableArrayList("Info", "Search"); /** * Track scene */ @FXML private ChoiceBox<String> methodChooseBoxTrack; @FXML private TextField artistNameTextFieldTrack; @FXML private TextField trackNameTextFieldTrack; @FXML private Button searchButtonTrack; private ObservableList<String> methodChooseListTrack = FXCollections.observableArrayList("Info", "Search"); @FXML private TextArea textAreaTrack; /** * Tag scene */ @FXML private ChoiceBox<String> methodChooseBoxTag; @FXML private TextField tagNameTextFieldTag; @FXML private Button searchButtonTag; @FXML private TextArea textAreaTags; private ObservableList<String> methodChooseListTag = FXCollections.observableArrayList("Info", "Tracks", "Albums", "Artists"); /** * Options scene */ @FXML private CheckBox autoCorrectButtonOptions; @FXML private TextField maxSearchResultsOptions; @FXML private Button applyButtonOptions; @FXML private TextField maxCachedFilesOptions; public AppController() { } public void initialize() { // Artist methodChooseBoxArtist.setValue("Info"); methodChooseBoxArtist.setItems(methodChooseListArtist); searchButtonArtist.setOnAction(e -> getSearchArtist(methodChooseBoxArtist)); // Album methodChooseBoxAlbum.setOnAction(e -> getChooseBoxActionAlbum(methodChooseBoxAlbum)); methodChooseBoxAlbum.setValue("Info"); methodChooseBoxAlbum.setItems(methodChooseListAlbum); searchButtonAlbum.setOnAction(e -> getSearchAlbum(methodChooseBoxAlbum)); // Track methodChooseBoxTrack.setOnAction(e -> getChooseBoxActionTrack(methodChooseBoxTrack)); methodChooseBoxTrack.setValue("Info"); methodChooseBoxTrack.setItems(methodChooseListTrack); searchButtonTrack.setOnAction(e -> getSearchTrack(methodChooseBoxTrack)); // Tag methodChooseBoxTag.setValue("Info"); methodChooseBoxTag.setItems(methodChooseListTag); searchButtonTag.setOnAction(e -> getSearchTag(methodChooseBoxTag)); // Options applyButtonOptions.setOnAction(e -> applyOptions()); } private void applyOptions() { if (!maxSearchResultsOptions.getText().isEmpty()) { int searchLimit = Integer.parseInt(maxSearchResultsOptions.getText()); Options.setSearchLimit(searchLimit); } if (!maxCachedFilesOptions.getText().isEmpty()) { int cachedFiles = Integer.parseInt(maxCachedFilesOptions.getText()); Options.setCachedFiles(cachedFiles); } if (autoCorrectButtonOptions.isSelected()) Options.setAutoCorrect(true); else Options.setAutoCorrect(false); } private void getSearchArtist(ChoiceBox<String> artistChooseBox) { String method = artistChooseBox.getValue(); if (method.equals("Info")) textAreaArtist.setText(Artist.getInfo(artistNameTextFieldArtist.getText())); if (method.equals("Tracks")) textAreaArtist.setText(Artist.getTopTracks(artistNameTextFieldArtist.getText())); if (method.equals("Albums")) textAreaArtist.setText(Artist.getTopAlbums(artistNameTextFieldArtist.getText())); if (method.equals("Search")) textAreaArtist.setText(Artist.search(artistNameTextFieldArtist.getText())); } private void getSearchAlbum(ChoiceBox<String> albumChooseBox) { String method = albumChooseBox.getValue(); if (method.equals("Info")) { textAreaAlbum.setText(Album.getInfo(albumNameTextFieldAlbum.getText(), artistNameTextFieldAlbum.getText())); } if (method.equals("Search")) { textAreaAlbum.setText(Album.search(albumNameTextFieldAlbum.getText())); } } private void getChooseBoxActionAlbum(ChoiceBox<String> albumChooseBox) { String method = albumChooseBox.getValue(); if (method.equals("Info")) artistNameTextFieldAlbum.setDisable(false); if (method.equals("Search")) artistNameTextFieldAlbum.setDisable(true); } private void getSearchTrack(ChoiceBox<String> trackChooseBox) { String method = trackChooseBox.getValue(); if (method.equals("Info")) textAreaTrack.setText(Track.getInfo(trackNameTextFieldTrack.getText(), artistNameTextFieldTrack.getText())); if (method.equals("Search")) textAreaTrack.setText(Track.multiSearch(trackNameTextFieldTrack.getText(), artistNameTextFieldTrack.getText())); } private void getChooseBoxActionTrack(ChoiceBox<String> trackChooseBox) { String method = trackChooseBox.getValue(); if (method.equals("Search")) artistNameTextFieldTrack.setPromptText("Optional"); } private void getSearchTag(ChoiceBox<String> tagChooseBox) { String method = tagChooseBox.getValue(); if (method.equals("Info")) textAreaTags.setText(Tag.getInfo(tagNameTextFieldTag.getText())); if (method.equals("Tracks")) textAreaTags.setText(Tag.getTopTracks(tagNameTextFieldTag.getText())); if (method.equals("Albums")) textAreaTags.setText(Tag.getTopAlbums(tagNameTextFieldTag.getText())); if (method.equals("Artists")) textAreaTags.setText(Tag.getTopArtists(tagNameTextFieldTag.getText())); } }
package com.tencent.mm.plugin.account.bind.ui; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.KeyEvent; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.ab.o; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.account.a.f; import com.tencent.mm.plugin.account.a.j; import com.tencent.mm.plugin.account.friend.a.ag; import com.tencent.mm.plugin.account.friend.ui.FindMContactAddUI; import com.tencent.mm.plugin.c.a; import com.tencent.mm.plugin.wxpay.a$k; import com.tencent.mm.protocal.c.arf; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMWizardActivity; import com.tencent.mm.ui.base.h; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class FindMContactLearmMoreUI extends MMWizardActivity { private String bTi; private Button eHP; private TextView eHQ; private String eHp = null; private String eHq = ""; private int eHr = 2; private List<String[]> eHv = null; private ProgressDialog eHw = null; private ag eHx; private e ehD = null; public void onCreate(Bundle bundle) { super.onCreate(bundle); this.eHp = getIntent().getStringExtra("regsetinfo_ticket"); this.eHq = getIntent().getStringExtra("regsetinfo_NextStep"); this.eHr = getIntent().getIntExtra("regsetinfo_NextStyle", 2); initView(); } public void onDestroy() { if (this.ehD != null) { g.DF().b(431, this.ehD); this.ehD = null; } super.onDestroy(); } protected void onResume() { super.onResume(); a.pT("R300_100_phone"); StringBuilder stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",RE300_600,"); g.Eg(); a.d(true, stringBuilder.append(com.tencent.mm.kernel.a.gd("RE300_600")).append(",1").toString()); } protected void onPause() { super.onPause(); StringBuilder stringBuilder = new StringBuilder(); g.Eg(); stringBuilder = stringBuilder.append(com.tencent.mm.kernel.a.DA()).append(",").append(getClass().getName()).append(",RE300_600,"); g.Eg(); a.d(false, stringBuilder.append(com.tencent.mm.kernel.a.gd("RE300_600")).append(",2").toString()); } protected final void initView() { setMMTitle(j.find_mcontact_upload_title); this.eHP = (Button) findViewById(f.ok_btn); this.eHQ = (TextView) findViewById(f.cancel_btn); this.eHP.setOnClickListener(new 1(this)); this.eHQ.setOnClickListener(new 2(this)); g.Ei().DT().set(12323, Boolean.valueOf(true)); this.bTi = (String) g.Ei().DT().get(6, null); if (this.bTi == null || this.bTi.equals("")) { this.bTi = (String) g.Ei().DT().get(4097, null); } } private void WR() { x.i("MicroMsg.FindMContactLearmMoreUI", "summerper checkPermission checkContacts[%b],stack[%s]", new Object[]{Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this, "android.permission.READ_CONTACTS", 48, null, null)), bi.cjd()}); if (com.tencent.mm.pluginsdk.permission.a.a(this, "android.permission.READ_CONTACTS", 48, null, null)) { o DF = g.DF(); AnonymousClass3 anonymousClass3 = new e() { public final void a(int i, int i2, String str, l lVar) { if (FindMContactLearmMoreUI.this.eHw != null) { FindMContactLearmMoreUI.this.eHw.dismiss(); FindMContactLearmMoreUI.this.eHw = null; } if (FindMContactLearmMoreUI.this.ehD != null) { g.DF().b(431, FindMContactLearmMoreUI.this.ehD); FindMContactLearmMoreUI.this.ehD = null; } if (i == 0 && i2 == 0) { int i3; LinkedList XR = ((ag) lVar).XR(); ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).setFriendData(XR); int i4; if (XR == null || XR.size() <= 0) { i4 = 0; i3 = 0; } else { Iterator it = XR.iterator(); i3 = 0; while (it.hasNext()) { arf arf = (arf) it.next(); if (arf != null) { if (arf.hcd == 1) { i4 = i3 + 1; } else { i4 = i3; } i3 = i4; } } i4 = i3 > 0 ? 1 : 0; } String str2 = "MicroMsg.FindMContactLearmMoreUI"; String str3 = "tigerreg data size=%d, addcount=%s"; Object[] objArr = new Object[2]; objArr[0] = Integer.valueOf(XR == null ? 0 : XR.size()); objArr[1] = Integer.valueOf(i3); x.d(str2, str3, objArr); if (FindMContactLearmMoreUI.this.eHq == null || !FindMContactLearmMoreUI.this.eHq.contains("1") || i4 == 0) { FindMContactLearmMoreUI.this.WL(); return; } a.pU("R300_300_phone"); Intent intent = new Intent(FindMContactLearmMoreUI.this, FindMContactAddUI.class); intent.putExtra("regsetinfo_ticket", FindMContactLearmMoreUI.this.eHp); intent.putExtra("regsetinfo_NextStep", FindMContactLearmMoreUI.this.eHq); intent.putExtra("regsetinfo_NextStyle", FindMContactLearmMoreUI.this.eHr); intent.putExtra("login_type", 0); MMWizardActivity.D(FindMContactLearmMoreUI.this, intent); return; } Toast.makeText(FindMContactLearmMoreUI.this, FindMContactLearmMoreUI.this.getString(j.app_err_system_busy_tip, new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}), 0).show(); FindMContactLearmMoreUI.this.WL(); } }; this.ehD = anonymousClass3; DF.a(431, anonymousClass3); ActionBarActivity actionBarActivity = this.mController.tml; getString(j.app_tip); this.eHw = h.a(actionBarActivity, getString(j.app_loading), true, new 4(this)); g.Em().a(new ah.a() { public final boolean Ks() { if (FindMContactLearmMoreUI.this.eHv == null || FindMContactLearmMoreUI.this.eHv.size() == 0) { if (FindMContactLearmMoreUI.this.eHw != null) { FindMContactLearmMoreUI.this.eHw.dismiss(); FindMContactLearmMoreUI.this.eHw = null; } FindMContactLearmMoreUI.this.WL(); } else { FindMContactLearmMoreUI.this.eHx = new ag(FindMContactLearmMoreUI.this.eHp, FindMContactLearmMoreUI.this.eHv); g.DF().a(FindMContactLearmMoreUI.this.eHx, 0); } return false; } public final boolean Kr() { try { FindMContactLearmMoreUI.this.eHv = com.tencent.mm.pluginsdk.a.cz(FindMContactLearmMoreUI.this); x.d("MicroMsg.FindMContactLearmMoreUI", "tigerreg mobileList size " + (FindMContactLearmMoreUI.this.eHv == null ? 0 : FindMContactLearmMoreUI.this.eHv.size())); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.FindMContactLearmMoreUI", e, "", new Object[0]); } return true; } public final String toString() { return super.toString() + "|doUpload"; } }); ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).syncUploadMContactStatus(true, false); ((com.tencent.mm.plugin.account.a.a.a) g.n(com.tencent.mm.plugin.account.a.a.a.class)).syncAddrBookAndUpload(); } } public boolean onKeyDown(int i, KeyEvent keyEvent) { if (i != 4 || keyEvent.getRepeatCount() != 0) { return super.onKeyDown(i, keyEvent); } WL(); return true; } private void WL() { YC(); DT(1); } protected final int getLayoutId() { return com.tencent.mm.plugin.account.a.g.findmcontact_intro_learn_more; } public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) { x.i("MicroMsg.FindMContactLearmMoreUI", "summerper onRequestPermissionsResult requestCode[%d],grantResults[%d] tid[%d]", new Object[]{Integer.valueOf(i), Integer.valueOf(iArr[0]), Long.valueOf(Thread.currentThread().getId())}); switch (i) { case a$k.AppCompatTheme_homeAsUpIndicator /*48*/: if (iArr[0] == 0) { WR(); return; } else { h.a(this, getString(j.permission_contacts_request_again_msg), getString(j.permission_tips_title), getString(j.jump_to_settings), getString(j.app_cancel), false, new OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); FindMContactLearmMoreUI.this.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS")); } }, new 7(this)); return; } default: return; } } }
package fr.lteconsulting.training.struts.interceptors; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; public class RandomErrorInterceptor extends AbstractInterceptor { private static final Logger LOG = LoggerFactory.getLogger( RandomErrorInterceptor.class ); public String intercept( ActionInvocation invocation ) throws Exception { if( Math.random() >= 0.5 ) { LOG.error( "L'intercepteur a mis la requête en erreur !" ); return Action.ERROR; } // invocation.getInvocationContext().getSession().put( "clé", value ); // L'appel à invoke peut ou pas déclencher la génération du flux HTML return invocation.invoke(); } }
package com.pineapple.mobilecraft.tumcca.server; import com.pineapple.mobilecraft.tumcca.data.Notification; import com.pineapple.mobilecraft.utils.SyncHttpGet; import com.pineapple.mobilecraft.utils.SyncHttpPost; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by yihao on 15/6/24. */ public class NotificationServer { /** * 发送关注 * @param token * @param followerId * @param toFollowId */ public static void sendFollowNotify(String token, int followerId, int toFollowId){ String url = "http://120.26.202.114/api/follow/notify"; JSONObject jsonObject = new JSONObject(); try { jsonObject.put("follower", followerId); jsonObject.put("toFollow", toFollowId); } catch (JSONException e) { e.printStackTrace(); } SyncHttpPost<String> post = new SyncHttpPost<String>(url, token, jsonObject.toString()) { @Override public String postExcute(String result) { return null; } }; post.execute(); } /** * 获取关于关注的通知 * @param token * @return */ public static List<Notification> getFollowNotification(String token){ String url = "http://120.26.202.114/api/notifications"; SyncHttpGet<List<Notification>> get = new SyncHttpGet<List<Notification>>(url, token) { @Override public List<Notification> postExcute(String result) { List<Notification> listNotification = new ArrayList<Notification>(); try { JSONArray jsonArray = new JSONArray(result); for(int i=0; i<jsonArray.length(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); Notification notification = Notification.fromJSON(jsonObject); listNotification.add(notification); } } catch (JSONException e) { e.printStackTrace(); } return listNotification; } }; List<Notification> listNotification = get.execute(); for(Notification notification:listNotification){ String url2 = "http://120.26.202.114/api/notifications/" + notification.id + "/read"; SyncHttpPost<String> post = new SyncHttpPost<String>(url2, token, "") { @Override public String postExcute(String result) { return null; } }; post.execute(); } return listNotification; } /** * 取消关注 * @param token * @param followerId 关注者id * @param followingId 被关注者id */ public static void sendUnFollowNotify(String token, int followerId, int followingId){ String url = "http://120.26.202.114/api/unfollow/notify"; JSONObject jsonObject = new JSONObject(); try { jsonObject.put("follower", followerId); jsonObject.put("following", followingId); } catch (JSONException e) { e.printStackTrace(); } SyncHttpPost<String> post = new SyncHttpPost<String>(url, token, jsonObject.toString()) { @Override public String postExcute(String result) { return null; } }; post.execute(); } // private void testWebsocket(){ // try { // mConnection.connect("http://120.26.202.114/ws/follow", new WebSocketConnectionHandler() { // @Override // public void onOpen() { // Log.d("Websocket", "onOpen"); // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("follower", 1); // jsonObject.put("toFollow", 3); // // } catch (JSONException e) { // e.printStackTrace(); // } // // mConnection.sendTextMessage(jsonObject.toString()); // } // // @Override // public void onTextMessage(String payload) { // Log.d("Websocket", payload); // // } // // @Override // public void onClose(int code, String reason) { // } // }); // } catch (WebSocketException e) { // // Log.d("Websocket", e.toString()); // } // Client client = ClientFactory.getDefault().newClient(); // // RequestBuilder request = client.newRequestBuilder() // .method(Request.METHOD.GET) // .uri("http://120.26.202.114/ws/follow") // .encoder(new Encoder<String, String>() { // @Override // public String encode(String data) { // return data; // } // }) // .decoder(new Decoder<String, String>() { // @Override // public String decode(Event event, String s) { // return null; // } // }) // .transport(Request.TRANSPORT.WEBSOCKET); // // final org.atmosphere.wasync.Socket socket = client.create(); // try { // socket.on("NOTIFY", new Function<String>() { // @Override // public void on(final String t) { // Log.v("Tumcca", t); // } // }).on(new Function<Throwable>() { // // @Override // public void on(Throwable t) { // //tv.setText("ERROR 3: " + t.getMessage()); // t.printStackTrace(); // } // // }).open(request.build()); // } catch (IOException e) { // e.printStackTrace(); // } // // // try { // // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("follower", 1); // jsonObject.put("toFollow", 3); // // } catch (JSONException e) { // e.printStackTrace(); // } // socket.fire(jsonObject.toString()); // } catch (IOException e) { // e.printStackTrace(); // } // } }
package la.opi.verificacionciudadana.activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import org.apache.commons.io.IOUtils; import java.io.StringWriter; import la.opi.verificacionciudadana.R; import la.opi.verificacionciudadana.api.ApiPitagorasService; import la.opi.verificacionciudadana.api.ClientServicePitagoras; import la.opi.verificacionciudadana.api.EndPoint; import la.opi.verificacionciudadana.api.HttpHelper; import la.opi.verificacionciudadana.exceptions.ExceptionErrorWriter; import la.opi.verificacionciudadana.fragments.TutorialFragment; import la.opi.verificacionciudadana.tabs.HomeTabs; import la.opi.verificacionciudadana.util.Config; import la.opi.verificacionciudadana.util.ConfigurationPreferences; import la.opi.verificacionciudadana.util.InternetConnection; import la.opi.verificacionciudadana.util.SessionManager; import la.opi.verificacionciudadana.util.StorageFiles; import la.opi.verificacionciudadana.util.StorageState; import la.opi.verificacionciudadana.util.SystemConfigurationBars; import retrofit.client.Response; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; public class TutorialActivity extends BaseActivity { String activity; Button btnOmited; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); btnOmited = (Button) findViewById(R.id.btn_omited); btnOmited.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (activity.equals("null")) { Intent intent = new Intent(TutorialActivity.this, LoginActivity.class); startActivity(intent); finish(); overridePendingTransition(R.animator.open_next, R.animator.close_main); } else if (activity.equals(Config.SHOWME_TUTORIAL) || activity.equals(Config.SHOWME_FROM_PREFERENCES_TUTORIAL)) { onBackPressed(); overridePendingTransition(R.animator.open_main, R.animator.close_next); } } }); Crashlytics.start(this); // super.getToolbar().setTitleTextColor(getResources().getColor(R.color.white)); createDirectory(); if (getIntent().getStringExtra(Config.FRAGMENT_TUTORIAL) != null) { activity = getIntent().getStringExtra(Config.FRAGMENT_TUTORIAL); } else { activity = "null"; } if (ConfigurationPreferences.getTutorialPreference(this)) { if (activity.equals(Config.SHOWME_TUTORIAL) || activity.equals(Config.SHOWME_FROM_PREFERENCES_TUTORIAL)) { showTutorial(savedInstanceState); } else { Log.d("tag_aux", ConfigurationPreferences.getOnDestroy(this).toString()); if (!ConfigurationPreferences.getUserSession(this).equals("close_session")) { if (InternetConnection.connectionState(this)) { try { // super.getToolbar().setTitleTextColor(getResources().getColor(R.color.white)); SharedPreferences preferences = getSharedPreferences(ConfigurationPreferences.TOKEN, Context.MODE_PRIVATE); singInRequest(this, EndPoint.PARAMETER_UTF8, preferences.getString(ConfigurationPreferences.USER_TOKEN, ""), preferences.getString(ConfigurationPreferences.USER_MAIL_LOGIN, ""), preferences.getString(ConfigurationPreferences.USER_PASS, "") , EndPoint.PARAMETER_REMEMBERME, EndPoint.PARAMETER_COMMIT_SIGN_IN); } catch (Exception e) { e.printStackTrace(); } } else { showToast(R.string.not_internet_conection); } } else { startActivity(new Intent(TutorialActivity.this, LoginActivity.class)); finish(); } } } else { showTutorial(savedInstanceState); } ConfigurationPreferences.setTutorialPreference(this, true); } @Override protected int getLayoutResource() { return R.layout.activity_demo; } @Override public void onBackPressed() { if (activity.equals(Config.SHOWME_TUTORIAL) || activity.equals(Config.SHOWME_FROM_PREFERENCES_TUTORIAL)) { super.onBackPressed(); overridePendingTransition(R.animator.open_main, R.animator.close_next); } } private void signIn() { super.onBackPressed(); overridePendingTransition(R.animator.open_main, R.animator.close_next); } private void showTutorial(Bundle savedInstanceState) { if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, TutorialFragment.newInstance()) .commit(); } } private void createDirectory() { // FALTA VALIDAR CUANDO ESTA LLENA LA MEMORIA if (StorageState.validateStorage(this)) { Log.i("DIRECTORY", "se puede crear "); StorageFiles.createDirectory(this); } else { Log.i("DIRECTORY", "no se puede crear"); } } private void singInRequest(final Context context, String utf, final String tokenLogin, final String userMail, final String userPassword, String rememberme, String commit) { ApiPitagorasService apiPitagorasService = ClientServicePitagoras.getRestAdapter().create(ApiPitagorasService.class); apiPitagorasService.userSingIn(utf, tokenLogin, userMail, userPassword, rememberme, commit) .observeOn(AndroidSchedulers.handlerThread(new Handler())).subscribe(new Action1<Response>() { @Override public void call(Response response) { try { final StringWriter writer = new StringWriter(); IOUtils.copy(response.getBody().in(), writer, Config.UTF_8); if (HttpHelper.regexLoginSuccess(writer.toString())) { ConfigurationPreferences.setTokenPreference(context, tokenLogin, userPassword, userMail); ConfigurationPreferences.setUserSession(context, "inicio_session_user"); Intent intent = new Intent(context, HomeTabs.class); startActivity(intent); finish(); } else { } } catch (Exception e) { e.printStackTrace(); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { } }); } private void showToast(int message) { Toast.makeText(this, getResources().getString(message), Toast.LENGTH_SHORT).show(); } }
package com.mertbozkurt.readingisgood.mapper; import com.mertbozkurt.readingisgood.dto.book.BookDTO; import com.mertbozkurt.readingisgood.dto.customer.CustomerProfileDTO; import com.mertbozkurt.readingisgood.model.Book; import com.mertbozkurt.readingisgood.model.Customer; import com.mertbozkurt.readingisgood.model.Order; import com.mertbozkurt.readingisgood.service.OrderService; import org.apache.commons.collections4.CollectionUtils; import org.modelmapper.ModelMapper; import org.modelmapper.config.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Component public class BookDTOMapper { @Autowired private ModelMapper modelMapper; public Book convertBookDTOToBook(BookDTO bookDTO) { modelMapper.getConfiguration() .setFieldMatchingEnabled(true) .setFieldAccessLevel(Configuration.AccessLevel.PRIVATE); Book book = modelMapper.map(bookDTO, Book.class); return book; } }
package com.diozero.sampleapps; import java.util.concurrent.locks.LockSupport; import com.diozero.internal.spi.MmapGpioInterface; import com.diozero.sbc.DeviceFactoryHelper; public class Rf433Sender { public static void main(String[] args) { int gpio = 26; int iterations = 10; int delay_ns = 300_000; try (MmapGpioInterface mmap_gpio = DeviceFactoryHelper.getNativeDeviceFactory().getBoardInfo() .createMmapGpio()) { for (int i = 0; i < iterations; i++) { mmap_gpio.gpioWrite(gpio, false); LockSupport.parkNanos(delay_ns); mmap_gpio.gpioWrite(gpio, true); LockSupport.parkNanos(delay_ns); } } } }
package day08ternaryoperator; import java.util.Scanner; public class TernaryOperator04 { public static void main(String[] args) { // ternary operator (if else if) // Kullanicidanbir sayi aliniz // sayi o dan buyuk esit ise "10 dan kpcpk olup olmadigini kontrol ediniz // kücük ise ekrana " rakam" degilse "pozitiv sayi" //sayi kücük ise " negativ" Scanner scan = new Scanner(System.in); System.out.println("bir tamsayi giriniz"); int num = scan.nextInt(); String result = num >=0 ? (num<10 ? "Rakam" : "Pozitiv sayi") : "negativ"; System.out.println(num + " " + result +"dir"); scan.close(); } }
package com.vinicius.pixeon.challenge.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.vinicius.pixeon.challenge.domain.HealthcareInstitution; import com.vinicius.pixeon.challenge.dto.HealthcareInstitutionRequestDto; import com.vinicius.pixeon.challenge.exception.PixeonNotFoundException; import com.vinicius.pixeon.challenge.exception.PixeonServiceException; import com.vinicius.pixeon.challenge.repository.HealthcareInstitutionRepository; @Service public class HealthcareInstitutionService { @Autowired private HealthcareInstitutionRepository repo; public HealthcareInstitution findById(Long id) { return repo.findById(id).orElseThrow(() -> new PixeonNotFoundException("Instituição de saúde não encontrada")); } public HealthcareInstitution findByName(String name) { return repo.findByName(name); } public HealthcareInstitution findByCnpj(String cnpj) { return repo.findByCnpj(cnpj); } @Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRES_NEW) public int chargeOneCoin(Long id) { return repo.chargeOneCoin(id); } public boolean hasCoins(Long id) { return repo.retrieveNumberOfCoins(id) > 0; } @Transactional public HealthcareInstitution save(HealthcareInstitutionRequestDto dto) { validateSaveOperation(dto); return repo.save(new HealthcareInstitution(dto.getName(), dto.getCnpj(), Integer.valueOf(20))); } private void validateSaveOperation(HealthcareInstitutionRequestDto dto) { if (dto == null) { throw new PixeonServiceException("dto is null"); } // Valida se existe instituição com mesmo nome HealthcareInstitution byName = findByName(dto.getName()); if (byName != null) { throw new PixeonServiceException("já existe intituição de saúde com este nome cadastrado"); } // Valida se existe instituição com mesmo cnpj HealthcareInstitution byCnpj = findByCnpj(dto.getCnpj()); if (byCnpj != null) { throw new PixeonServiceException("já existe intituição de saúde com este cnpj cadastrado"); } } }
package com.javateam.demoMyBatis.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.javateam.demoMyBatis.service.EmployeeService; import lombok.extern.java.Log; @Controller @Log public class DemoController { @Autowired private EmployeeService service; @RequestMapping("/") public String home() { return "redirect:/getAll"; } @RequestMapping("/getAll") public String getAll(Model model) { log.info("getAll"); model.addAttribute("list", service.getAll()); return "getAll"; } @RequestMapping("/getOne/{id}") public String getOne(@PathVariable("id") int id, Model model) { log.info("getOne"); model.addAttribute("employees", service.getOne(id)); return "getOne"; } }
package com.mundo.web.annotation; import java.lang.annotation.*; /** * CheckLogin * * @author maodh * @since 2017/8/1 */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface CheckLogin { boolean value() default true; }
package day13_review; public class kahootReview { public static void main(String[] args) { //Q1 if (!true != !false) { // false != true===>true System.out.println("Cybertek"); }else { System.out.println("Batch12"); } //Q2 boolean resultA = 9>=9 || 10<=10; // true || true===>true boolean resultB = 'A' >=128 && 'B'<128; // false && true ===>false if (resultA) { if(resultB) { System.out.println(resultA); } else { System.out.println(resultB); } } //Q3 in multibranch statement we dont need ELSE block, // the ELSE block can not be declared independetly, IF is mandatory if(true) { }else if (false) { } //Q4 int num1 = 9; if (++num1 < 10) { //10<9==>false System.out.println(num1 +"Hello World"); }else { System.out.println(num1 + " Hello universe "); } //Q5 int x =1; int y =0; if(x++ > ++y) { // 1> 1===>false System.out.println("Hello"); }else { System.out.print("Welcome"); } System.out.println("log " + x+ ":" + y); // 2 1 //7 boolean result = true; int N =100; if (true) { System.out.println("one"); } if(true ) { System.out.println("two"); } if (true) { System.out.println("three"); } // still Q7 boolean X =true; int B =100; if(X) { B/=10;//10 X = !X;// ==false } if (X) {//false B*=2;//N==10 } else { B-=5;//N = 10-5=5 System.out.println(B); } //Q8 boolean A= true; if (A==false) { //true==false===false System.out.println("one"); } else if (A==false!=true) { // true==false != true //false!=true==>true System.out.println("Two"); } //rest of the else if not important any more // Q10 int n1 ='B'; if (n1 >128 || n1 <= 129) { //false|| true== >true System.out.println('B'); }else System.out.println('A'); } }
package com.yunheenet.pcroom.view; import javax.swing.*; import java.awt.*; public class PopupFrame extends Frame { private String userId; private int screenWidth; private int screenHeight; private JFrame frame; private JLabel titleLabel; public static void main(String args[]) { new PopupFrame(); } public PopupFrame() { getScreenSize(); initializeFrame(); start(); } public PopupFrame(String id) { this.userId = id; getScreenSize(); initializeFrame(); start(); } private void getScreenSize() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); screenWidth = (int)screenSize.getWidth(); screenHeight = (int)screenSize.getHeight(); System.out.println("#ScreenSize=" + screenWidth + "x" + screenHeight); } private void initializeFrame() { frame = new JFrame(); frame.setBounds(screenWidth-500, 100, 400, 400); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setUndecorated(true); frame.setBackground(new Color(0, 0, 0, 0)); //frame.setVisible(true); } private void start() { JPanel panel = new JPanel(); BorderLayout fl = new BorderLayout(); // Title Label titleLabel = new JLabel(); titleLabel.setHorizontalAlignment(SwingConstants.CENTER); if (userId != null) { titleLabel.setText(userId + "님 환영합니다."); } else { titleLabel.setText("PICO System."); } panel.setLayout(fl); panel.add(titleLabel, BorderLayout.NORTH); frame.setContentPane(panel); frame.setVisible(true); } }
package kr.meet42.memberservice.config; import kr.meet42.memberservice.security.FtOAuth2SuccessHandler; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig extends WebSecurityConfigurerAdapter { private final Environment env; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login") .authenticated(); http.authorizeRequests() .antMatchers("*") .permitAll(); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.formLogin().disable(); http.csrf().disable();; http.logout(); http.oauth2Login() .successHandler(ftOAuth2SuccessHandler) .loginPage("/oauth2/authorization/oauth42") .and() .cors(); } @Autowired private FtOAuth2SuccessHandler ftOAuth2SuccessHandler; @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin(env.getProperty("42meet.server.test")); configuration.addAllowedMethod("*"); configuration.addAllowedHeader("*"); configuration.addExposedHeader("access-token"); configuration.addExposedHeader("refresh-token"); configuration.setAllowCredentials(true); configuration.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
package de.zarncke.lib.util; import java.io.Serializable; public interface Shortener extends Serializable { /** * Leaves text unchanged. */ Shortener NONE = new Shortener() { public CharSequence shorten(final CharSequence longText) { return longText; } }; /** * Shortens to 80 characters by truncating. See {@link Chars#summarize(CharSequence, int)}. */ Shortener SIMPLE = new Shortener() { public CharSequence shorten(final CharSequence longText) { return Chars.summarize(longText, 80); } }; /** * @param longText != null * @return text as most as long as the given text */ CharSequence shorten(CharSequence longText); }
package com.dilip.annotationbased.SpringAnnotationBased; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App { public static void main( String[] args ) { ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); Samsung samsung=ac.getBean(Samsung.class); samsung.config(); /** if we dont need Bean to be speicifed in AppConfig, then we can add * @Component to the classes that we need and add * @ComponentScan and give the basepackages in AppConfig **/ /** * if we write @primary on the class, it will be considered first */ /** * if we specify the @qualifier in appconfig file and provide name as argument, * then it will be considered first */ } }
package com.codecool.csepdo.FilePartReader; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; public class FileWordAnalyzer { private FilePartReader text; public FileWordAnalyzer(FilePartReader filePart) { this.text = filePart; } public ArrayList<String> getWordsOrderedAlphabetically() { ArrayList<String> textArrayList = getText(); textArrayList.sort(String::compareToIgnoreCase); return textArrayList; } public ArrayList<String> getWordsContainingSubstring(String substring) throws NoSuchElementException { ArrayList<String> textArrayList = getText(); ArrayList<String> containerList = textArrayList.stream() .filter(w -> w.toLowerCase().contains(substring.toLowerCase())) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); if (containerList.size() > 0) { return containerList; } else { throw new NoSuchElementException("Can't find substring in the text"); } } public ArrayList<String> getStringsWhichPalindromes() { ArrayList<String> textArrayList = getText(); ArrayList<String> newList = removeDuplicates(textArrayList); ArrayList<String> palindromes = new ArrayList<>(); for (String word : newList) { for (String checkedWord : newList) { if (word.toLowerCase().equals(reverseString(checkedWord.toLowerCase()))) { palindromes.add(word); palindromes.add(checkedWord); } } } return palindromes; } private ArrayList<String> getText() { String textString = text != null ? text.readLines() : null; return new ArrayList<>(Arrays.asList(textString != null ? textString.split(" ") : new String[0])); } private ArrayList<String> removeDuplicates(ArrayList<String> originalList) { ArrayList<String> newList = new ArrayList<>(); for (String element : originalList) { if (!newList.contains(element)) { newList.add(element); } } return newList; } private String reverseString(String word) { StringBuilder reversedWord = new StringBuilder(); reversedWord.append(word); reversedWord = reversedWord.reverse(); return reversedWord.toString(); } }
package de.ybroeker.assertions.json; import org.assertj.core.api.AbstractDoubleAssert; import org.assertj.core.util.CheckReturnValue; /** * @author ybroeker */ public class JsonDoubleAssert extends AbstractDoubleAssert<JsonDoubleAssert> implements JsonElementAssert { private final JsonAssert parent; @CheckReturnValue public JsonDoubleAssert(final JsonAssert parent, final Double actual) { super(actual, JsonDoubleAssert.class); this.parent = parent; } @CheckReturnValue @Override public JsonAssert and() { return parent; } }
package org.newdawn.slick.tests; import java.util.ArrayList; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.Game; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.util.Log; public class InputTest extends BasicGame { private String message = "Press any key, mouse button, or drag the mouse"; private ArrayList lines = new ArrayList(); private boolean buttonDown; private float x; private float y; private Color[] cols = new Color[] { Color.red, Color.green, Color.blue, Color.white, Color.magenta, Color.cyan }; private int index; private Input input; private int ypos; private AppGameContainer app; private boolean space; private boolean lshift; private boolean rshift; public InputTest() { super("Input Test"); } public void init(GameContainer container) throws SlickException { if (container instanceof AppGameContainer) this.app = (AppGameContainer)container; this.input = container.getInput(); this.x = 300.0F; this.y = 300.0F; } public void render(GameContainer container, Graphics g) { g.drawString("left shift down: " + this.lshift, 100.0F, 240.0F); g.drawString("right shift down: " + this.rshift, 100.0F, 260.0F); g.drawString("space down: " + this.space, 100.0F, 280.0F); g.setColor(Color.white); g.drawString(this.message, 10.0F, 50.0F); g.drawString(container.getInput().getMouseY(), 10.0F, 400.0F); g.drawString("Use the primary gamepad to control the blob, and hit a gamepad button to change the color", 10.0F, 90.0F); for (int i = 0; i < this.lines.size(); i++) { Line line = this.lines.get(i); line.draw(g); } g.setColor(this.cols[this.index]); g.fillOval((int)this.x, (int)this.y, 50.0F, 50.0F); g.setColor(Color.yellow); g.fillRect(50.0F, (200 + this.ypos), 40.0F, 40.0F); } public void update(GameContainer container, int delta) { this.lshift = container.getInput().isKeyDown(42); this.rshift = container.getInput().isKeyDown(54); this.space = container.getInput().isKeyDown(57); if (this.controllerLeft[0]) this.x -= delta * 0.1F; if (this.controllerRight[0]) this.x += delta * 0.1F; if (this.controllerUp[0]) this.y -= delta * 0.1F; if (this.controllerDown[0]) this.y += delta * 0.1F; } public void keyPressed(int key, char c) { if (key == 1) System.exit(0); if (key == 59 && this.app != null) try { this.app.setDisplayMode(600, 600, false); this.app.reinit(); } catch (Exception e) { Log.error(e); } } public void keyReleased(int key, char c) { this.message = "You pressed key code " + key + " (character = " + c + ")"; } public void mousePressed(int button, int x, int y) { if (button == 0) this.buttonDown = true; this.message = "Mouse pressed " + button + " " + x + "," + y; } public void mouseReleased(int button, int x, int y) { if (button == 0) this.buttonDown = false; this.message = "Mouse released " + button + " " + x + "," + y; } public void mouseClicked(int button, int x, int y, int clickCount) { System.out.println("CLICKED:" + x + "," + y + " " + clickCount); } public void mouseWheelMoved(int change) { this.message = "Mouse wheel moved: " + change; if (change < 0) this.ypos -= 10; if (change > 0) this.ypos += 10; } public void mouseMoved(int oldx, int oldy, int newx, int newy) { if (this.buttonDown) this.lines.add(new Line(oldx, oldy, newx, newy)); } private class Line { private int oldx; private int oldy; private int newx; private int newy; public Line(int oldx, int oldy, int newx, int newy) { this.oldx = oldx; this.oldy = oldy; this.newx = newx; this.newy = newy; } public void draw(Graphics g) { g.drawLine(this.oldx, this.oldy, this.newx, this.newy); } } public void controllerButtonPressed(int controller, int button) { super.controllerButtonPressed(controller, button); this.index++; this.index %= this.cols.length; } public static void main(String[] argv) { try { AppGameContainer container = new AppGameContainer((Game)new InputTest()); container.setDisplayMode(800, 600, false); container.start(); } catch (SlickException e) { e.printStackTrace(); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\InputTest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package org.b.d; import java.io.OutputStream; public final class a { public final String scope; public final String vKl; public final String vKm; public final String vKn; public final h vKp; private final OutputStream vKq; public a(String str, String str2, String str3, h hVar, String str4, OutputStream outputStream) { this.vKl = str; this.vKm = str2; this.vKn = str3; this.vKp = hVar; this.scope = str4; this.vKq = outputStream; } public final void sL(String str) { if (this.vKq != null) { try { this.vKq.write(new StringBuilder(String.valueOf(str)).append("\n").toString().getBytes("UTF8")); } catch (Throwable e) { throw new RuntimeException("there were problems while writting to the debug stream", e); } } } }
package com.cmj.netty.response; /** * Created by chenminjian on 2018/4/19. */ public abstract class AbstractResponseFuture<T> implements ResponseFuture<T> { protected volatile FutureState state = FutureState.NEW; //状态 protected final long createTime = System.currentTimeMillis();//处理开始时间 public AbstractResponseFuture() { } @Override public boolean isCancelled() { return this.state == FutureState.CANCELLED; } @Override public boolean isDone() { return this.state == FutureState.DONE; } }
/* * Copyright 2008 Eckhart Arnold (eckhart_arnold@hotmail.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package tddd24.ajgallery.client.gwtphotoalbum; //import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasMouseMoveHandlers; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseMoveHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.ui.Widget; /** * Abstract base class for the control panel overlay classes. * */ public abstract class PanelOverlayBase implements MouseMoveHandler, ClickHandler, ResizeListener, PopupPanel.PositionCallback, AttachmentListener { /** the key in the "info.json" dictionary that determines the * panel position. Possible values: "top", "bottom", * "upper left", "upper right", "lower left", "lower right" */ public static final String KEY_PANEL_POSITION = "panel position"; /** * The time in milliseconds until the control panel popup is hidden * again after showing */ public int delay = 2500; protected ControlPanel controlPanel; protected Widget baseWidget; protected PopupPanel popup; protected boolean popupVisible; protected Timer timer; protected int lastMouseX = -1, lastMouseY = -1; public PanelOverlayBase(ControlPanel controlPanel, Widget baseWidget) { this.controlPanel = controlPanel; this.baseWidget = baseWidget; if (baseWidget instanceof SourcesAttachmentEvents) ((SourcesAttachmentEvents) this.baseWidget).addAttachmentListener(this); ((HasMouseMoveHandlers)baseWidget).addMouseMoveHandler(this); ((HasClickHandlers)baseWidget).addClickHandler(this); } /* (non-Javadoc) * @see com.google.gwt.event.dom.client.MouseMoveHandler#onMouseMove(com.google.gwt.event.dom.client.MouseMoveEvent) */ @Override public void onClick(ClickEvent event) { // GWT.log("clicked!"); showPopup(event.getX(), event.getY()); } /* (non-Javadoc) * @see com.google.gwt.event.dom.client.MouseMoveHandler#onMouseMove(com.google.gwt.event.dom.client.MouseMoveEvent) */ @Override public void onMouseMove(MouseMoveEvent event) { int x = event.getX(); int y = event.getY(); if (lastMouseX != x || lastMouseY != y) { showPopup(x, y); lastMouseX = x; lastMouseY = y; } } // /* (non-Javadoc) // * @see com.google.gwt.event.dom.client.MouseMoveHandler#onMouseMove(com.google.gwt.event.dom.client.MouseMoveEvent) // */ // @Override // public void onTouchEnd(TouchEndEvent event) { // JsArray<Touch> touches = event.getTargetTouches(); // Touch touch = touches.get(0); // EventTarget target = touch.getTarget(); // showPopup(touch.getRelativeX(target), event.getRelativeY(target)); // } /** * Hides the popup panel. */ protected void hidePopup() { popup.hide(); popupVisible = false; } /** * Shows the popup panel. * @param x x position where the popup shall be placed * @param y y position where the popup shall be placed */ protected void showPopup(int x, int y) { if (!popupVisible) { popup.setPopupPositionAndShow(this); popupVisible = true; } timer.schedule(delay); } }
package at.ac.tuwien.sepm.assignment.individual.unit.persistence; import static org.junit.jupiter.api.Assertions.*; import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException; import at.ac.tuwien.sepm.assignment.individual.persistence.BreedDao; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; public abstract class BreedDaoTestBase { @Autowired BreedDao breedDao; @Test @DisplayName("Finding breed by non-existing ID should throw NotFoundException") public void findingBreedById_nonExisting_shouldThrowNotFoundException() { assertThrows(NotFoundException.class, () -> breedDao.getOneById(1L)); } }
package components; public class UserPiece extends Piece { public UserPiece(int posX, int posY, Matrix mat) { super(posX, posY); this.mat = mat; } }
package com.example.root.monerotest.QRReader; 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 com.example.root.monerotest.R; public class QRReaderFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.qr_reader_fragment, container, false); //TODO: here you set up any listeners to the views in the layout return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if(getView() != null){ View v = getView(); //TODO: here you can call findViewWithId and get the view u need from the qr_reder_fragment layout } } }
package com.example.testproject; import android.content.Intent; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.View; import android.widget.Button; public class AdminMenuActivity extends AppCompatActivity { private Button juryButton, logoutButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_menu); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); juryButton = (Button)findViewById(R.id.jurybutton); juryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(AdminMenuActivity.this, JuryActivity.class); AdminMenuActivity.this.startActivity(myIntent); } }); // this doesn't jump back to AuthActivity because it remembers the user!!! logoutButton = (Button)findViewById(R.id.logoutbutton); logoutButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(AdminMenuActivity.this, AuthActivity.class); AdminMenuActivity.this.startActivity(myIntent); } }); /*juryButton = (Button)findViewById(R.id.jurybutton); juryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(AdminMenuActivity.this, JuryActivity.class); AdminMenuActivity.this.startActivity(myIntent); } }); juryButton = (Button)findViewById(R.id.jurybutton); juryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(AdminMenuActivity.this, JuryActivity.class); AdminMenuActivity.this.startActivity(myIntent); } });*/ } }
package pe.egcc.cursoapp.controller; import java.util.List; import pe.egcc.cursoapp.dto.ProductoDto; import pe.egcc.cursoapp.service.contrato.CursoService; import pe.egcc.cursoapp.service.implementacion.CursoServiceImpl; public class CursoController { private CursoService cursoService; public CursoController() { cursoService = new CursoServiceImpl(); } public String[] getCategorias() { return cursoService.getListaCategoria(); } public void registrarProducto(ProductoDto dto) { cursoService.registrarProducto(dto); } public List<ProductoDto> getProductos(String categoria) { return cursoService.getProductos(categoria); } public List<ProductoDto> getAllProductos() { return cursoService.getAllProductos(); } }
package io.github.wickhamwei.wessential.wprotect.command; import io.github.wickhamwei.wessential.WEssentialMain; import io.github.wickhamwei.wessential.wprotect.WProtect; import io.github.wickhamwei.wessential.wtools.WPlayer; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Set; public class Add implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { if (commandSender instanceof Player) { String playerName = commandSender.getName(); WPlayer player = WPlayer.getWPlayer(playerName); if (strings.length >= 1) { Block lastChest = WProtect.getLastChest(player); // 您必须选择了一个箱子而且箱子的主人是您 if (lastChest != null) { String chestOwnerName = WProtect.getChestOwnerName(lastChest); if (chestOwnerName != null && chestOwnerName.equals(playerName)) { for (String string : strings) { if (WProtect.setMoreUser(lastChest, string)) { player.sendMessage("&e" + string + WEssentialMain.languageConfig.getConfig().getString("message.w_protect_chest_user_add")); } } Set<String> moreUsers = WProtect.getMoreUsers(lastChest); player.sendMessage(WEssentialMain.languageConfig.getConfig().getString("message.w_protect_chest_all_user") + moreUsers); return true; } } player.sendMessage(WEssentialMain.languageConfig.getConfig().getString("message.w_protect_chest_unknown")); return true; } } return false; } }
package techokami.computronics; import java.util.Random; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import li.cil.oc.api.Driver; import openperipheral.api.OpenPeripheralAPI; import techokami.computronics.audio.DFPWMPlaybackManager; import techokami.computronics.block.BlockCamera; import techokami.computronics.block.BlockChatBox; import techokami.computronics.block.BlockCipher; import techokami.computronics.block.BlockIronNote; import techokami.computronics.block.BlockSorter; import techokami.computronics.block.BlockTapeReader; import techokami.computronics.gui.GuiOneSlot; import techokami.computronics.item.ItemOpenComputers; import techokami.computronics.item.ItemTape; import techokami.computronics.storage.StorageManager; import techokami.computronics.tile.ContainerTapeReader; import techokami.computronics.tile.TileCamera; import techokami.computronics.tile.TileChatBox; import techokami.computronics.tile.TileCipherBlock; import techokami.computronics.tile.TileIronNote; import techokami.computronics.tile.TileTapeDrive; import techokami.computronics.tile.sorter.TileSorter; import techokami.lib.gui.GuiHandler; import techokami.lib.item.ItemMultiple; import techokami.lib.network.PacketHandler; import techokami.lib.util.ModIntegrationHandler; import techokami.lib.util.ModIntegrationHandler.Stage; import techokami.lib.util.color.RecipeColorizer; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.oredict.ShapedOreRecipe; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerAboutToStartEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; @Mod(modid="computronics", name="Computronics", version="0.4.1", dependencies="required-after:asielib;after:OpenPeripheralCore;after:ComputerCraft;after:OpenComputers;after:OpenComputers|Core;after:BuildCraft|Core") public class Computronics { public Configuration config; public static Random rand = new Random(); public static Logger log; @Instance(value="computronics") public static Computronics instance; public static StorageManager storage; public static GuiHandler gui; public static PacketHandler packet; public DFPWMPlaybackManager audio; public static int CHATBOX_DISTANCE = 40; public static int CAMERA_DISTANCE = 32; public static int TAPEDRIVE_DISTANCE = 24; public static int BUFFER_MS = 750; public static String CHATBOX_PREFIX = "[ChatBox]"; public static boolean CAMERA_REDSTONE_REFRESH, CHATBOX_ME_DETECT, CHATBOX_CREATIVE; @SidedProxy(clientSide="techokami.computronics.ClientProxy", serverSide="techokami.computronics.CommonProxy") public static CommonProxy proxy; public static BlockIronNote ironNote; public static BlockTapeReader tapeReader; public static BlockCamera camera; public static BlockChatBox chatBox; public static BlockSorter sorter; public static BlockCipher cipher; public static ItemTape itemTape; public static ItemMultiple itemParts; public static ItemOpenComputers itemRobotUpgrade; //public static Class<? extends TileEntity> CHAT_BOX_CLASS; public static CreativeTabs tab = new CreativeTabs("tabComputronics") { public Item getTabIconItem() { return itemTape; } }; @EventHandler public void preInit(FMLPreInitializationEvent event) { log = LogManager.getLogger("computronics"); config = new Configuration(event.getSuggestedConfigurationFile()); config.load(); audio = new DFPWMPlaybackManager(proxy.isClient()); packet = new PacketHandler("computronics", new NetworkHandlerClient(), new NetworkHandlerServer()); // Configs CHATBOX_DISTANCE = config.get("chatbox", "maxDistance", 40).getInt(); CAMERA_DISTANCE = config.get("camera", "maxDistance", 32).getInt(); CAMERA_REDSTONE_REFRESH = config.get("camera", "sendRedstoneSignal", true).getBoolean(true); BUFFER_MS = config.get("tapedrive", "audioPreloadMs", 750).getInt(); CHATBOX_PREFIX = config.get("chatbox", "prefix", "[ChatBox]").getString(); CHATBOX_ME_DETECT = config.get("chatbox", "readCommandMe", false).getBoolean(false); CHATBOX_CREATIVE = config.get("chatbox", "enableCreative", true).getBoolean(true); TAPEDRIVE_DISTANCE = config.get("tapedrive", "hearingDistance", 24).getInt(); config.get("camera", "sendRedstoneSignal", true).comment = "Setting this to false might help Camera tick lag issues, at the cost of making them useless with redstone circuitry."; ironNote = new BlockIronNote(); GameRegistry.registerBlock(ironNote, "computronics.ironNoteBlock"); GameRegistry.registerTileEntity(TileIronNote.class, "computronics.ironNoteBlock"); tapeReader = new BlockTapeReader(); GameRegistry.registerBlock(tapeReader, "computronics.tapeReader"); GameRegistry.registerTileEntity(TileTapeDrive.class, "computronics.tapeReader"); camera = new BlockCamera(); GameRegistry.registerBlock(camera, "computronics.camera"); GameRegistry.registerTileEntity(TileCamera.class, "computronics.camera"); chatBox = new BlockChatBox(); GameRegistry.registerBlock(chatBox, "computronics.chatBox"); GameRegistry.registerTileEntity(TileChatBox.class, "computronics.chatBox"); //sorter = new BlockSorter(); //GameRegistry.registerBlock(sorter, "computronics.sorter"); //GameRegistry.registerTileEntity(TileSorter.class, "computronics.sorter"); cipher = new BlockCipher(); GameRegistry.registerBlock(cipher, "computronics.cipher"); GameRegistry.registerTileEntity(TileCipherBlock.class, "computronics.cipher"); if(Loader.isModLoaded("OpenPeripheralCore")) { OpenPeripheralAPI.createAdapter(TileTapeDrive.class); OpenPeripheralAPI.createAdapter(TileIronNote.class); OpenPeripheralAPI.createAdapter(TileCamera.class); //OpenPeripheralAPI.createAdapter(TileSorter.class); OpenPeripheralAPI.createAdapter(TileCipherBlock.class); } itemTape = new ItemTape(); GameRegistry.registerItem(itemTape, "computronics.tape"); itemParts = new ItemMultiple("computronics", new String[]{"part_tape_track"}); itemParts.setCreativeTab(tab); GameRegistry.registerItem(itemParts, "computronics.parts"); if(Loader.isModLoaded("OpenComputers")) { itemRobotUpgrade = new ItemOpenComputers(); GameRegistry.registerItem(itemRobotUpgrade, "computronics.robotUpgrade"); Driver.add(itemRobotUpgrade); } } @EventHandler public void init(FMLInitializationEvent event) { gui = new GuiHandler(); NetworkRegistry.INSTANCE.registerGuiHandler(Computronics.instance, gui); MinecraftForge.EVENT_BUS.register(new ComputronicsEventHandler()); proxy.registerGuis(gui); FMLInterModComms.sendMessage("Waila", "register", "techokami.computronics.integration.waila.IntegrationWaila.register"); GameRegistry.addShapedRecipe(new ItemStack(camera, 1, 0), "sss", "geg", "iii", 's', Blocks.stonebrick, 'i', Items.iron_ingot, 'e', Items.ender_pearl, 'g', Blocks.glass); GameRegistry.addShapedRecipe(new ItemStack(chatBox, 1, 0), "sss", "ses", "iri", 's', Blocks.stonebrick, 'i', Items.iron_ingot, 'e', Items.ender_pearl, 'r', Items.redstone); GameRegistry.addShapedRecipe(new ItemStack(ironNote, 1, 0), "iii", "ini", "iii", 'i', Items.iron_ingot, 'n', Blocks.noteblock); GameRegistry.addShapedRecipe(new ItemStack(tapeReader, 1, 0), "iii", "iri", "iai", 'i', Items.iron_ingot, 'r', Items.redstone, 'a', ironNote); GameRegistry.addShapedRecipe(new ItemStack(cipher, 1, 0), "sss", "srs", "eie", 'i', Items.iron_ingot, 'r', Items.redstone, 'e', Items.ender_pearl, 's', Blocks.stonebrick); // Tape recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 0), " i ", "iii", " T ", 'T', new ItemStack(itemParts, 1, 0), 'i', Items.iron_ingot)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 1), " i ", "ngn", " T ", 'T', new ItemStack(itemParts, 1, 0), 'i', Items.iron_ingot, 'n', Items.gold_nugget, 'g', Items.gold_ingot)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 2), " i ", "ggg", "nTn", 'T', new ItemStack(itemParts, 1, 0), 'i', Items.iron_ingot, 'n', Items.gold_nugget, 'g', Items.gold_ingot)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 3), " i ", "ddd", " T ", 'T', new ItemStack(itemParts, 1, 0), 'i', Items.iron_ingot, 'd', Items.diamond)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 4), " d ", "dnd", " T ", 'T', new ItemStack(itemParts, 1, 0), 'n', Items.nether_star, 'd', Items.diamond)); // Mod compat - copper/steel GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 5), " i ", " c ", " T ", 'T', new ItemStack(itemParts, 1, 0), 'i', Items.iron_ingot, 'c', "ingotCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 6), " i ", "isi", " T ", 'T', new ItemStack(itemParts, 1, 0), 'i', Items.iron_ingot, 's', "ingotSteel")); // Mod compat - GregTech GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemTape, 1, 7), " i ", "isi", " T ", 'T', new ItemStack(itemParts, 1, 0), 'i', "plateIridium", 's', "plateTungstenSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(itemParts, 1, 0), " i ", "rrr", "iii", 'r', Items.redstone, 'i', Items.iron_ingot)); GameRegistry.addRecipe(new RecipeColorizer(itemTape)); if(Loader.isModLoaded("OpenComputers")) { GameRegistry.addShapedRecipe(new ItemStack(itemRobotUpgrade, 1, 0), "mcm", 'c', new ItemStack(camera, 1, 0), 'm', li.cil.oc.api.Items.MicroChipTier2); GameRegistry.addShapedRecipe(new ItemStack(itemRobotUpgrade, 1, 0), "m", "c", "m", 'c', new ItemStack(camera, 1, 0), 'm', li.cil.oc.api.Items.MicroChipTier2); } config.save(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { } @EventHandler public void serverStart(FMLServerAboutToStartEvent event) { Computronics.storage = new StorageManager(); } }
package ru.lember.neointegrationadapter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import ru.lember.neointegrationadapter.configuration.projectA.RoutingConfiguration; @SpringBootApplication @ComponentScan(basePackages = {"ru.lember.neointegrationadapter.configuration"}) @Import(value = {RoutingConfiguration.class}) public class NeoIntegrationAdapterApplication { public static void main(String[] args) { SpringApplication.run(NeoIntegrationAdapterApplication.class, args); } }
package org.locker; public class DeadlockDetectedException extends RuntimeException { public DeadlockDetectedException(String message) { super(message); } }
/* * Copyright 2007 Bastian Schenke Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package nz.org.take.r2ml.reference; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import de.tu_cottbus.r2ml.AssociationAtom; import de.tu_cottbus.r2ml.DataTerm; import de.tu_cottbus.r2ml.ObjectTerm; import nz.org.take.Fact; import nz.org.take.SimplePredicate; import nz.org.take.Term; import nz.org.take.r2ml.AssociationResolvPolicy; import nz.org.take.r2ml.MappingContext; import nz.org.take.r2ml.R2MLDriver; import nz.org.take.r2ml.R2MLException; import nz.org.take.r2ml.XmlTypeHandler; import nz.org.take.r2ml.util.R2MLUtil; /** * * @author schenke * */ public class SimpleAssociationResolvPolicy implements AssociationResolvPolicy { public Fact resolv(AssociationAtom atom) throws R2MLException { R2MLDriver driver = R2MLDriver.get(); MappingContext context = MappingContext.get(); context.getPredicate(atom.getAssociationPredicateID().getLocalPart()); Fact result = R2MLUtil.newFact(); result.setId(atom.getAssociationPredicateID().getLocalPart()); // build fact for association List<Term> terms = new ArrayList<Term>(); List<Class> termTypes = new ArrayList<Class>(); // build all terms and types of terms for (JAXBElement<? extends ObjectTerm> objectTermElement : atom.getObjectArguments().getObjectTerm()) { XmlTypeHandler handler = driver.getHandlerByXmlType(objectTermElement.getDeclaredType()); Term argument = null; try { argument = (Term) handler.importObject(objectTermElement.getValue()); terms.add(argument); termTypes.add(argument.getType()); } catch (ClassCastException e) { throw new R2MLException("Error while handling ObjectTerms for Association " + atom.getAssociationPredicateID(), e); } } for (JAXBElement<? extends DataTerm> dataTermElement : atom.getDataArguments().getDataTerm()) { XmlTypeHandler handler = driver.getHandlerByXmlType(dataTermElement.getDeclaredType()); Term argument = null; try { argument = (Term) handler.importObject(dataTermElement.getValue()); terms.add(argument); termTypes.add(argument.getType()); } catch (ClassCastException e) { throw new R2MLException("Error while handling DataTerms for Association " + atom.getAssociationPredicateID(), e); } } // try to reuse predicate build earlier if (context.getPredicate(atom.getAssociationPredicateID().getLocalPart()) != null) { result.setPredicate(context.getPredicate(atom.getAssociationPredicateID().getLocalPart())); } else { // build new predicate SimplePredicate simpleAssociationPredicate = new SimplePredicate(); simpleAssociationPredicate.setName(atom.getAssociationPredicateID().getLocalPart()); simpleAssociationPredicate.setNegated(atom.isIsNegated() == null?false:atom.isIsNegated()); simpleAssociationPredicate.setSlotNames(driver.getNameMapper().getSlotNames(atom.getAssociationPredicateID())); simpleAssociationPredicate.setSlotTypes(termTypes.toArray(new Class[] {})); result.setPredicate(simpleAssociationPredicate); } // apply terms result.setTerms(terms.toArray(new Term[] {})); return result; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; public class Evade_CLI implements Observer { public static void main(String[] args) { System.out.println("********************"); System.out.println("* Welcome to EVADE *"); System.out.println("********************"); Evade_CLI evadeCLI = new Evade_CLI(); GameManager gameManager = new GameManager(); gameManager.addObserver(evadeCLI); gameManager.setPlayers(Evade_CLI.setupPlayers(2, gameManager)); Board board = new Board(); board.setupNewBoard(); gameManager.startGame(board); } @Override public void update(Observable observable, Object o) { Board board = (Board) o; this.printBoard(board); } public void printBoard(Board board) { Deck deck = board.getDeck(); String [] deckArray = deck.toString().split("#"); for (int i = 0; i < deckArray.length; i++) { for (int j = 0; j < 6; j++) { int val = Character.getNumericValue(deckArray[i].charAt(j)); switch (val) { case Deck.WHITE: val = 'x'; break; case Deck.BLACK: val = 'y'; break; case Deck.WHITE_KING: val = 'X'; break; case Deck.BLACK_KING: val = 'Y'; break; case Deck.FROZEN_KING: val = 'Z'; break; case Deck.FROZEN: val = 'z'; break; default: val = '0'; break; } System.out.printf("%c",val); } System.out.printf("\n"); } } private static ArrayList<Player> setupPlayers(int count, GameManager gameManager) { ArrayList<Player> players = new ArrayList<>(); for(int i=1;i<=count;i++) { System.out.printf("Select player no. %d ([C]omputer/[H]uman):\n", i); Player player = setupPlayer(gameManager); //TODO: Handle player signs better player.setSign(i); players.add(player); } return players; } private static Player setupPlayer(GameManager gameManager) { String input = ""; Player player = null; while(player == null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { input = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (input.charAt(0) == 'C') { player = new Computer(gameManager); Evade_CLI.askForLevel(player); } else if (input.charAt(0) == 'H') { player = new Human(gameManager); Evade_CLI.askForName(player); } else { System.out.println("Bad input, please write only 'C' or 'H'."); } } return player; } private static void askForName(Player player) { String input = ""; System.out.println(String.format("What's your name?:")); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { input = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } player.setName(input); } private static void askForLevel(Player player) { String input = ""; System.out.println(String.format("Select difficulty: (E)asy - (M)edium - (H)ard")); boolean correct = false; while(!correct) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { input = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } switch(input.charAt(0)){ case 'E': player.setLevel(Computer.levels.EASY); player.setName("Holly"); correct = true; break; case 'M': player.setLevel(Computer.levels.MEDIUM); player.setName("Hex"); correct = true; break; case 'H': player.setLevel(Computer.levels.HARD); player.setName("Hal 3000"); correct = true; break; default: System.out.println("Bad input, please write only 'E', 'M' or 'H'."); break; } } } }
package com.example.httpclient.demohttpclient.entity; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class Person { String name; String age; User user; }
package application.repository.impls; import application.mapper.PersonRowMapper; import application.model.Person; import application.model.Song; import application.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; public class PersonRepositoryImpl implements PersonRepository { @Autowired private JdbcTemplate jdbcTemplate; @Override public Person findByName(String name) { Person person = jdbcTemplate.queryForObject("SELECT * FROM person p WHERE p.person_name = ?", new Object[]{name}, new PersonRowMapper()); return person; } @Override public void save(Person person) { jdbcTemplate.update("INSERT INTO person(person_name) VALUES(?)", person.getName()); } @Override public void update(Person person) { jdbcTemplate.update("UPDATE person SET person_name = ? WHERE id=?", person.getName(),person.getId()); } @Override public List<Person> findAll() { List<Person> personList = jdbcTemplate.query("SELECT * FROM person",(rs,i ) -> new PersonRowMapper().mapRow(rs,i)); return personList; } }
package board; import java.util.*; import java.io.BufferedReader; import java.io.FileReader; import city.City; import _aux.Options; import _aux.CustomTypes; import _aux.CustomTypes.Direction; /* Board class Mimics the game board. Composed by individual cells disposed in bidimensional arrays */ public class Board { private int[][] map_threat; private Cell[][] map; public int n_cols; public int n_rows; public ArrayList<String> used_cities; public Hashtable<String, ArrayList<String>> adjacent_cities; // Resolves adjacency between cities // Constructors public Board(Cell[][] map, int w, int h) { this.map = map; this.n_cols = w; this.n_rows = h; // Threat map. Initially zeroed across all cells this.map_threat = new int[h][w]; } /* * Constructor Loads map from csv file. Expected format: * * <number of rows>;<number of columns> [<city alias or 0 if none>;...] [...] ** * PARAMETERS: datapath: String; path to map valid_cities: Dictionary; Contains * the valid city aliases as dictionary keys. Each value is the actual City * object used_cities: list in which the specified board cities will be saved */ public Board(String datapath, Hashtable<String, City> valid_cities) { this.used_cities = new ArrayList<String>(); this.adjacent_cities = new Hashtable<String, ArrayList<String>>(); // Read csv lines creating stream from file try { BufferedReader br = new BufferedReader(new FileReader(datapath)); // Reads map data from subsequent lines (Must follow the expected map format) // Layout must be regular! (same number of columns across all rows) String line; String[] line_data; // Control list. Cities can only be set once ArrayList<String> picked_cities = new ArrayList<String>(); // Iterable indices int n_row = 0; int n_col = 0; // Tries to read map dimensions from first line line_data = br.readLine().split(";"); if (line_data.length != 2) { if (Options.LOG.ordinal() >= CustomTypes.LogLevel.CRITICAL.ordinal()) System.out .printf("[Board] CRITICAL: Can't load map from file. Expected dimensions in first line.\n"); System.exit(0); } try { // Sets board dimensions this.n_rows = Integer.parseInt(line_data[0]); this.n_cols = Integer.parseInt(line_data[1]); // Builds static map array this.map = new Cell[n_rows][n_cols]; // Loads actual map reading line by line the input file while ((line = br.readLine()) != null) { line_data = line.split(";"); Cell cell; if (line_data.length != n_cols) { if (Options.LOG.ordinal() >= CustomTypes.LogLevel.CRITICAL.ordinal()) System.out.printf( "[Board] CRITICAL: Can't load map from file. Wrong number of columns at row %d. Expected %d, found %d.\n", n_row, n_cols, line_data.length); System.exit(0); } // Iterates through every line element and checks if contains a valid city alias // cell_text contains the city alias for (String cell_text : line_data) { cell = new Cell(n_col, n_row); // Checks for special character in city (identifies initial city) // Initial city is always at the first position of the control list (used // cities) if (cell_text.charAt(0) == '*') { cell_text = cell_text.substring(1); this.used_cities.add(0, cell_text); } // Creates city and cross reference between itself and the assigned cell if (valid_cities.containsKey(cell_text) && !picked_cities.contains(cell_text)) { City city = valid_cities.get(cell_text); cell.setCity(city); city.setCell(cell); // Appends city alias to control list this.used_cities.add(cell_text); // City won't be loaded twice picked_cities.add(cell_text); } else if (picked_cities.contains(cell_text)) { if (Options.LOG.ordinal() >= CustomTypes.LogLevel.WARN.ordinal()) System.out.printf("[Board] WARN: City %s already set. Ignoring...\n", cell_text); } // Assigns cell to map (either empty or with an actual city) this.map[n_row][n_col++] = cell; } n_row++; n_col = 0; } // Resolves adjacencies for (int i = 0; i < n_rows; i++) { // Iterates every cell and defines its adjacencies for (int j = 0; j < n_cols; j++) { // If cell contains a valid city, evaluates its surroundings if (this.map[i][j] != null) { City c = this.map[i][j].city; ArrayList<String> c_adjacent = new ArrayList<String>(); Cell cleft = this.map[Math.floorMod(i - 1, n_rows)][j], ctop = this.map[i][Math.floorMod(j - 1, n_cols)], cright = this.map[Math.floorMod(i + 1, n_rows)][j], cbottom = this.map[i][Math.floorMod(j + 1, n_cols)]; // Left cell if (cleft != null) { c_adjacent.add(cleft.city.alias); } // Top cell if (ctop != null) { c_adjacent.add(ctop.city.alias); } // Right cell if (ctop != null) { c_adjacent.add(cright.city.alias); } // Bottom cell if (ctop != null) { c_adjacent.add(cbottom.city.alias); } this.adjacent_cities.put(c.alias, c_adjacent); } } } for (Cell map_row[] : this.map) { for (Cell cell : map_row) { } } // Threat map. Initially zeroed across all cells this.map_threat = new int[this.n_rows][this.n_cols]; // Updates valid_cities dictionary. Only used cities are retained (updates the // main city map in the game!!) valid_cities.keySet().retainAll(picked_cities); } catch (NumberFormatException e) { if (Options.LOG.ordinal() >= CustomTypes.LogLevel.CRITICAL.ordinal()) System.out .printf("[Board] CRITICAL: Can't load map from file. Expected dimensions in first line.\n"); System.err.println(e.getMessage()); System.exit(0); } br.close(); } catch (Exception e) { if (Options.LOG.ordinal() >= CustomTypes.LogLevel.CRITICAL.ordinal()) System.out.printf("[Board] CRITICAL: Error while parsing\n"); System.err.println(e.getMessage()); e.printStackTrace(); System.exit(0); } } // Setters/getters public int[] getDimensions() { return new int[] { this.n_rows, this.n_cols }; } public Cell getCell(int row, int col) { return this.map[row][col]; } /* * Resolves adjacent cities */ public static void resolveAdjacentCities(Board board, Hashtable<String, City> cities) { Cell current, adjacent; int pos_x, pos_y, new_x, new_y; for (City city : cities.values()) { Hashtable<Direction, City> local_adjacents = new Hashtable<Direction, City>(); current = city.getCell(); pos_x = current.x; pos_y = current.y; // Adjacent city, left if (pos_x - 1 < 0) { new_x = board.n_cols - 1; } else { new_x = pos_x - 1; } adjacent = board.map[pos_y][new_x]; local_adjacents.put(Direction.LEFT, adjacent.getCity()); // Adjacent city, right if (pos_x + 1 >= board.n_cols) { new_x = 0; } else { new_x = pos_x + 1; } adjacent = board.map[pos_y][new_x]; local_adjacents.put(Direction.RIGHT, adjacent.getCity()); // Adjacent city, up if (pos_y - 1 < 0) { new_y = board.n_rows - 1; } else { new_y = pos_y - 1; } adjacent = board.map[new_y][pos_x]; local_adjacents.put(Direction.UP, adjacent.getCity()); // Adjacent city, down if (pos_y + 1 >= board.n_rows) { new_y = 0; } else { new_y = pos_y + 1; } adjacent = board.map[new_y][pos_x]; local_adjacents.put(Direction.DOWN, adjacent.getCity()); city.setNeighbors(local_adjacents); } return; } // TODO /* * Returns a sorted list of Cell objects, which represents the shortest path * between two cells in the board */ public ArrayList<Cell> getPath(Cell origin, Cell target) { return null; } // Dummy method to print board data public void dump() { for (Cell[] c_row : map) { for (Cell c : c_row) { if (c.isEmpty()) { System.out.printf("NIL;"); } else { System.out.printf("%s;", c.getCity().alias); } } System.out.println(); } } }
package plp.orientadaObjetos1.expressao.leftExpression; import plp.orientadaObjetos1.expressao.Expressao; /** * Classe que representa um acesso de atributo. */ public abstract class AcessoAtributo implements LeftExpression{ /** * Identificador. */ private Id id; /** * Construtor * @param id Identificador */ public AcessoAtributo(Id id) { this.id = id; } /** * Obtém o identificador. * @return o identificador. */ public Id getId(){ return id; } /** * Obtém uma expressao * @return uma expressão. */ public abstract Expressao getExpressaoObjeto(); }
/** */ package com.rockwellcollins.atc.limp.impl; import com.rockwellcollins.atc.limp.Else; import com.rockwellcollins.atc.limp.Expr; import com.rockwellcollins.atc.limp.IfThenElseStatement; import com.rockwellcollins.atc.limp.LimpPackage; import com.rockwellcollins.atc.limp.StatementBlock; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>If Then Else Statement</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link com.rockwellcollins.atc.limp.impl.IfThenElseStatementImpl#getCond <em>Cond</em>}</li> * <li>{@link com.rockwellcollins.atc.limp.impl.IfThenElseStatementImpl#getThenBlock <em>Then Block</em>}</li> * <li>{@link com.rockwellcollins.atc.limp.impl.IfThenElseStatementImpl#getElse <em>Else</em>}</li> * </ul> * * @generated */ public class IfThenElseStatementImpl extends StatementImpl implements IfThenElseStatement { /** * The cached value of the '{@link #getCond() <em>Cond</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getCond() * @generated * @ordered */ protected Expr cond; /** * The cached value of the '{@link #getThenBlock() <em>Then Block</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getThenBlock() * @generated * @ordered */ protected StatementBlock thenBlock; /** * The cached value of the '{@link #getElse() <em>Else</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getElse() * @generated * @ordered */ protected Else else_; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfThenElseStatementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return LimpPackage.Literals.IF_THEN_ELSE_STATEMENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expr getCond() { return cond; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetCond(Expr newCond, NotificationChain msgs) { Expr oldCond = cond; cond = newCond; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, LimpPackage.IF_THEN_ELSE_STATEMENT__COND, oldCond, newCond); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setCond(Expr newCond) { if (newCond != cond) { NotificationChain msgs = null; if (cond != null) msgs = ((InternalEObject)cond).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - LimpPackage.IF_THEN_ELSE_STATEMENT__COND, null, msgs); if (newCond != null) msgs = ((InternalEObject)newCond).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - LimpPackage.IF_THEN_ELSE_STATEMENT__COND, null, msgs); msgs = basicSetCond(newCond, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LimpPackage.IF_THEN_ELSE_STATEMENT__COND, newCond, newCond)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StatementBlock getThenBlock() { return thenBlock; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetThenBlock(StatementBlock newThenBlock, NotificationChain msgs) { StatementBlock oldThenBlock = thenBlock; thenBlock = newThenBlock; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK, oldThenBlock, newThenBlock); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setThenBlock(StatementBlock newThenBlock) { if (newThenBlock != thenBlock) { NotificationChain msgs = null; if (thenBlock != null) msgs = ((InternalEObject)thenBlock).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK, null, msgs); if (newThenBlock != null) msgs = ((InternalEObject)newThenBlock).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK, null, msgs); msgs = basicSetThenBlock(newThenBlock, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK, newThenBlock, newThenBlock)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Else getElse() { return else_; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetElse(Else newElse, NotificationChain msgs) { Else oldElse = else_; else_ = newElse; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE, oldElse, newElse); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setElse(Else newElse) { if (newElse != else_) { NotificationChain msgs = null; if (else_ != null) msgs = ((InternalEObject)else_).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE, null, msgs); if (newElse != null) msgs = ((InternalEObject)newElse).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE, null, msgs); msgs = basicSetElse(newElse, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE, newElse, newElse)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case LimpPackage.IF_THEN_ELSE_STATEMENT__COND: return basicSetCond(null, msgs); case LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK: return basicSetThenBlock(null, msgs); case LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE: return basicSetElse(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case LimpPackage.IF_THEN_ELSE_STATEMENT__COND: return getCond(); case LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK: return getThenBlock(); case LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE: return getElse(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case LimpPackage.IF_THEN_ELSE_STATEMENT__COND: setCond((Expr)newValue); return; case LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK: setThenBlock((StatementBlock)newValue); return; case LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE: setElse((Else)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case LimpPackage.IF_THEN_ELSE_STATEMENT__COND: setCond((Expr)null); return; case LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK: setThenBlock((StatementBlock)null); return; case LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE: setElse((Else)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case LimpPackage.IF_THEN_ELSE_STATEMENT__COND: return cond != null; case LimpPackage.IF_THEN_ELSE_STATEMENT__THEN_BLOCK: return thenBlock != null; case LimpPackage.IF_THEN_ELSE_STATEMENT__ELSE: return else_ != null; } return super.eIsSet(featureID); } } //IfThenElseStatementImpl
package COM.JambPracPortal.DAO; import COM.JambPracPortal.MODEL.userResponse; import java.sql.PreparedStatement; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import org.primefaces.context.RequestContext; public class userResponseDAO extends DAO { public void userResponseMethod(userResponse usrResp) throws Exception { try { String myflag = "answered"; PreparedStatement st3 = getCn().prepareStatement("INSERT INTO signup values(?,?,?,?,?,?,?)"); st3.setString(1, usrResp.getUsername()); st3.setString(2, usrResp.getSubject()); st3.setInt(3, usrResp.getSid()); st3.setString(4, usrResp.getQuestionNo()); st3.setString(5, usrResp.getCorrectAnswer()); st3.setString(6, usrResp.getUserAnswers()); st3.setString(7, usrResp.getFlag()); st3.executeUpdate(); st3.close(); FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Successful Options Selection", "You succcessfully entered your response = "); RequestContext.getCurrentInstance().showMessageInDialog(message); } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Error in data entry pls, try again " + e, "")); } finally { Close(); } } }
/* * Copyright (C) 2021-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.services.store.models; import static com.hedera.services.utils.MiscUtils.asFcKeyUnchecked; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.ACCOUNT_FROZEN_FOR_TOKEN; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.ACCOUNT_KYC_NOT_GRANTED_FOR_TOKEN; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.protobuf.ByteString; import com.hedera.node.app.service.evm.exceptions.InvalidTransactionException; import com.hedera.node.app.service.evm.store.tokens.TokenType; import com.hedera.services.jproto.JKey; import com.hederahashgraph.api.proto.java.Key; import com.hederahashgraph.api.proto.java.KeyList; import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import com.hederahashgraph.api.proto.java.TokenSupplyType; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class TokenRelationshipTest { private final Id tokenId = new Id(0, 0, 1234); private final Id accountId = new Id(1, 0, 4321); private final long balance = 1_234L; private final JKey kycKey = asFcKeyUnchecked( Key.newBuilder().setKeyList(KeyList.getDefaultInstance()).build()); private final JKey freezeKey = asFcKeyUnchecked( Key.newBuilder().setKeyList(KeyList.getDefaultInstance()).build()); private final long defaultLongValue = 0; private final int defaultIntValue = 0; private Token token; private Account account; private TokenRelationship subject; @BeforeEach void setUp() { token = new Token( 0L, tokenId, new ArrayList<>(), new ArrayList<>(), new HashMap<>(), false, TokenType.FUNGIBLE_COMMON, TokenSupplyType.FINITE, defaultIntValue, 21_000_000, null, null, null, null, null, null, null, false, null, null, false, false, false, defaultIntValue, defaultIntValue, true, "the mother", "bitcoin", "BTC", 10, defaultLongValue, defaultLongValue, Collections.emptyList()); account = new Account( ByteString.EMPTY, 0L, accountId, defaultLongValue, defaultLongValue, false, defaultLongValue, defaultLongValue, Id.DEFAULT, defaultIntValue, null, null, null, 3, defaultIntValue, defaultIntValue, 0L, false, null); subject = new TokenRelationship(token, account, balance, false, false, false, true, true, true, 0); } @Test void ofRecordInterestIfFungibleBalanceChanges() { token.setType(TokenType.FUNGIBLE_COMMON); subject = subject.setBalance(balance - 1); assertTrue(subject.hasChangesForRecord()); } @Test void notOrdinarilyOfRecordInterestIfNonFungibleBalanceChanges() { token.setType(TokenType.NON_FUNGIBLE_UNIQUE); subject = subject.setBalance(balance - 1); assertTrue(subject.hasChangesForRecord()); } @Test void ordinarilyOfRecordInterestIfNonFungibleBalanceChangesForDeletedToken() { token.setType(TokenType.NON_FUNGIBLE_UNIQUE); // token.setIsDeleted(true); subject = subject.setBalance(balance - 1); assertTrue(subject.hasChangesForRecord()); } @Test void toStringAsExpected() { // given: final var desired = "TokenRelationship{notYetPersisted=true, account=Account{id=1.0.4321," + " expiry=0, balance=0, deleted=false, ownedNfts=0, alreadyUsedAutoAssociations=0, maxAutoAssociations=0," + " alias=, cryptoAllowances=null, fungibleTokenAllowances=null, approveForAllNfts=null, numAssociations=3," + " numPositiveBalances=0}, token=Token{id=0.0.1234, type=FUNGIBLE_COMMON, deleted=false, autoRemoved=false, treasury=null," + " autoRenewAccount=null, kycKey=null, freezeKey=null, frozenByDefault=false, supplyKey=null, currentSerialNumber=0," + " pauseKey=null, paused=false}, balance=1234, balanceChange=0, frozen=false, kycGranted=false, isAutomaticAssociation=true}"; // expect: assertEquals(desired, subject.toString()); } @Test void equalsWorks() { assertEquals(subject, subject); assertNotEquals(subject, freezeKey); } @Test void automaticAssociationSetterWorks() { subject = new TokenRelationship(token, account, balance, false, false, false, true, false, true, 0); assertFalse(subject.isAutomaticAssociation()); subject = new TokenRelationship(token, account, balance, false, false, false, true, true, true, 0); assertTrue(subject.isAutomaticAssociation()); } @Test void cannotChangeBalanceIfFrozenForToken() { // given: token = token.setFreezeKey(freezeKey); subject = new TokenRelationship(token, account, balance, true, false, false, true, true, true, 0); assertFailsWith(() -> subject.setBalance(balance + 1), ACCOUNT_FROZEN_FOR_TOKEN); } @Test void canChangeBalanceIfFrozenForDeletedToken() { token = token.setFreezeKey(freezeKey); token = token.setIsDeleted(true); subject = new TokenRelationship(token, account, balance, true, false, false, true, true, false, 0); subject = subject.setBalance(0); assertEquals(-balance, subject.getBalanceChange()); } @Test void canChangeBalanceIfUnfrozenForToken() { // given: token = token.setFreezeKey(freezeKey); // when: subject = subject.setBalance(balance + 1); // then: assertEquals(1, subject.getBalanceChange()); } @Test void canChangeBalanceIfNoFreezeKey() { // given: subject = new TokenRelationship(token, account, balance, true, false, false, true, true, true, 0); // when: subject = subject.setBalance(balance + 1); // then: assertEquals(1, subject.getBalanceChange()); } @Test void cannotChangeBalanceIfKycNotGranted() { // given: token = token.setKycKey(kycKey); subject = new TokenRelationship(token, account, balance, false, false, false, true, true, true, 0); // verify assertFailsWith(() -> subject.setBalance(balance + 1), ACCOUNT_KYC_NOT_GRANTED_FOR_TOKEN); } @Test void canChangeBalanceIfKycGranted() { // given: token = token.setKycKey(kycKey); subject = new TokenRelationship(token, account, balance, false, true, false, true, true, true, 0); // when: subject = subject.setBalance(balance + 1); // then: assertEquals(1, subject.getBalanceChange()); } @Test void canChangeBalanceIfNoKycKey() { // when: subject = subject.setBalance(balance + 1); // then: assertEquals(1, subject.getBalanceChange()); } @Test void updateFreezeWorksIfFeezeKeyIsPresent() { // given: token = token.setFreezeKey(freezeKey); // when: subject = new TokenRelationship(token, account, balance, true, false, false, true, true, true, 0); // then: assertTrue(subject.isFrozen()); } @Test void givesCorrectRepresentation() { Token newToken = subject.getToken().setType(TokenType.NON_FUNGIBLE_UNIQUE); subject = subject.setToken(newToken); assertTrue(subject.hasUniqueRepresentation()); newToken = subject.getToken().setType(TokenType.FUNGIBLE_COMMON); subject = subject.setToken(newToken); assertTrue(subject.hasCommonRepresentation()); } @Test void testHashCode() { var rel = new TokenRelationship(token, account, balance, false, false, false, true, true, true, 0); assertEquals(rel.hashCode(), subject.hashCode()); } @Test void updateKycWorksIfKycKeyIsPresent() { // given: token.setKycKey(kycKey); // when: subject = new TokenRelationship(token, account, balance, false, true, false, true, true, true, 0); // then: assertTrue(subject.isKycGranted()); } private void assertFailsWith(Runnable something, ResponseCodeEnum status) { var ex = assertThrows(InvalidTransactionException.class, something::run); assertEquals(status, ex.getResponseCode()); } }
/* * The purpose of this lab is to learn about how to extract data * from user input and apply the extracted digit using remainder * and division symbols. * * Author: Victor (Zach) Johnson * Date: 9/9/17 */ package chapter2; import java.util.Scanner; public class Ex2_06 { public static void main (String [] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a number between 0 and 1000:"); double userInput = input.nextDouble(); System.out.println("the number is: " + userInput); double firstDigit = userInput % 10; double findSecond = (int)userInput / 10; double secondDigit = findSecond % 10; double findThird = (int)findSecond / 10; double thirdDigit = findThird % 10; double sumOfDigits = firstDigit + secondDigit + thirdDigit; System.out.println("The user typed the number : " + userInput); System.out.println("The first number was " + thirdDigit); System.out.println("The second number was " + secondDigit); System.out.println("The third number was " + firstDigit); System.out.println("The sum of your numbers is " + sumOfDigits); } }
package android.support.v4.app; import android.app.Notification; import android.os.Bundle; import android.support.v4.app.ae.a; import android.support.v4.app.z.d; import android.support.v4.app.z.l; class z$p extends l { z$p() { } public Notification b(d dVar) { a aVar = new a(dVar.mContext, dVar.pQ, dVar.ps, dVar.pt, dVar.py, dVar.pw, dVar.pz, dVar.pu, dVar.pv, dVar.px, dVar.pE, dVar.pF, dVar.pG, dVar.pB, dVar.mPriority, dVar.pD, dVar.pL, dVar.mExtras, dVar.pH, dVar.pI, dVar.pJ); z.a(aVar, dVar.pK); z.a(aVar, dVar.pC); return aVar.build(); } public Bundle a(Notification notification) { return ae.a(notification); } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.theelm.sewingmachine.protection.claims; import net.theelm.sewingmachine.base.CoreMod; import net.theelm.sewingmachine.config.SewConfig; import net.theelm.sewingmachine.events.PlayerNameCallback; import net.theelm.sewingmachine.protection.config.SewProtectionConfig; import net.theelm.sewingmachine.protection.enums.ClaimRanks; import net.theelm.sewingmachine.protection.interfaces.PlayerClaimData; import net.theelm.sewingmachine.protection.objects.ServerClaimCache; import net.theelm.sewingmachine.protection.utilities.ClaimNbtUtils; import net.theelm.sewingmachine.utilities.FormattingUtils; import net.theelm.sewingmachine.utilities.TownNameUtils; import net.theelm.sewingmachine.utilities.mod.Sew; import net.theelm.sewingmachine.utilities.nbt.NbtUtils; import net.minecraft.entity.passive.VillagerEntity; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtElement; import net.minecraft.server.MinecraftServer; import net.minecraft.server.PlayerManager; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.HoverEvent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.theelm.sewingmachine.utilities.text.TextUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashSet; import java.util.Set; import java.util.UUID; public final class ClaimantTown extends Claimant { private boolean deleted = false; private @Nullable UUID ownerId; private @Nullable ClaimantPlayer owner; private Set<UUID> villagers; public ClaimantTown(@NotNull ServerClaimCache cache, @NotNull UUID townId) { super(cache, ClaimantType.TOWN, townId); } public ClaimantTown(@NotNull ServerClaimCache cache, @NotNull UUID townId, @NotNull MutableText townName) { this(cache, townId); this.name = townName; } public @NotNull String getTownType() { return TownNameUtils.getTownName( this.getCount(), this.getResidentCount() ); } public @NotNull String getOwnerTitle() { return TownNameUtils.getOwnerTitle( this.getCount(), this.getResidentCount(), true ); } public @NotNull MutableText getOwnerName() { return TextUtils.mutable(PlayerNameCallback.getName(this.getOwnerId())); } public @Nullable UUID getOwnerId() { return this.ownerId; } public @Nullable ClaimantPlayer getOwner() { if (this.owner == null && this.ownerId != null && this.claimCache instanceof ServerClaimCache claimCache) this.owner = claimCache.getPlayerClaim(this.ownerId); return this.owner; } public void setOwner(@NotNull UUID owner) { if (this.claimCache instanceof ServerClaimCache claimCache) { this.updateFriend(owner, ClaimRanks.OWNER); this.ownerId = owner; this.owner = claimCache.getPlayerClaim(owner); this.markDirty(); } } public int getResidentCount() { return this.getFriends().size() + (SewConfig.get(SewProtectionConfig.TOWN_VILLAGERS_INCLUDE) && SewConfig.get(SewProtectionConfig.TOWN_VILLAGERS_VALUE) > 0 ? this.getVillagers().size() / SewConfig.get(SewProtectionConfig.TOWN_VILLAGERS_VALUE) : 0); } @Override public @NotNull MutableText getName() { return FormattingUtils.deepCopy(this.name); } public @NotNull HoverEvent getHoverText() { return new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal("Town: ") .append(this.getName() .formatted(Formatting.DARK_AQUA, Formatting.BOLD)) .append("\nOwner: ") .append(this.getOwnerName() .formatted(Formatting.DARK_AQUA, Formatting.BOLD))); } /* Villager Options */ public Set<UUID> getVillagers() { return this.villagers; } public boolean addVillager(@NotNull VillagerEntity villager) { if (this.villagers.add(villager.getUuid())) { CoreMod.logInfo("Added a new villager to " + this.getName().getString() + "!"); this.markDirty(); return true; } return false; } public boolean removeVillager(@NotNull VillagerEntity villager) { if (this.villagers.remove(villager.getUuid())) { this.markDirty(); return true; } return false; } /* Player Friend Options */ @Override public ClaimRanks getFriendRank(@Nullable UUID player) { if ( this.getOwnerId().equals( player ) ) return ClaimRanks.OWNER; return super.getFriendRank( player ); } @Override public boolean updateFriend(@NotNull final UUID player, @Nullable final ClaimRanks rank) { if ( super.updateFriend(player, rank) ) { if (this.claimCache instanceof ServerClaimCache claimCache) { ClaimantPlayer claim = claimCache.getPlayerClaim(player); claim.setTown(rank == null ? null : this); } return true; } return false; } @Override public boolean updateFriend(@NotNull ServerPlayerEntity player, @Nullable ClaimRanks rank) { if ( super.updateFriend( player, rank ) ) { ClaimantPlayer claim = ((PlayerClaimData) player).getClaim(); claim.setTown(rank == null ? null : this); return true; } return false; } /* Send Messages */ @Override public void send(@NotNull MinecraftServer server, @NotNull final Text text) { this.getFriends().forEach((uuid) -> { ServerPlayerEntity player = Sew.getPlayer(server, uuid); if (player != null) player.sendMessage(text); }); } /* Tax Options */ public int getTaxRate() { return 0; } /* Nbt saving */ @Override public void writeCustomDataToTag(@NotNull NbtCompound tag) { if (this.ownerId == null) throw new RuntimeException("Town owner should not be null"); tag.putUuid("owner", this.ownerId); if ( this.name != null ) tag.putString("name", Text.Serializer.toJson( this.name )); tag.put("villagers", NbtUtils.toList(this.getVillagers(), UUID::toString)); // Write to tag super.writeCustomDataToTag( tag ); } @Override public void readCustomDataFromTag(@NotNull NbtCompound tag) { // Get the towns owner this.ownerId = (NbtUtils.hasUUID(tag, "owner") ? NbtUtils.getUUID(tag, "owner") : null); this.owner = null; // Get the town name if (tag.contains("name", NbtElement.STRING_TYPE)) this.name = Text.Serializer.fromJson(tag.getString("name")); // Get the towns villagers this.villagers = new HashSet<>(); if (tag.contains("villagers", NbtElement.LIST_TYPE)) this.villagers.addAll(NbtUtils.fromList(tag.getList("villagers", NbtElement.STRING_TYPE), UUID::fromString)); // Read from tag super.readCustomDataFromTag( tag ); } public void delete(@NotNull PlayerManager playerManager) { ServerPlayerEntity player; this.deleted = true; // Remove all players from the town for (UUID member : this.getFriends()) { if ((player = playerManager.getPlayer(member)) != null) ((PlayerClaimData) player).getClaim().setTown(null); } // Remove from the cache (So it doesn't save again) this.claimCache.removeFromCache(this); ClaimNbtUtils.delete(this); CoreMod.logInfo("Deleted town " + this.getName().getString() + " (" + this.getId() + ")"); } @Override public boolean forceSave() { if (!this.deleted) return super.forceSave(); return true; } }
package Domain; import Domain.Effetti.Effetto; import Exceptions.DomainException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by Michele on 04/06/2017. */ public class TorreTest { private Torre torre; @Before public void setUp() throws Exception { torre = new Torre(TipoCarta.Territorio); assertEquals(TipoCarta.Territorio, torre.Tipo); assertEquals(4, torre.SpaziAzione.size()); assertEquals(1, torre.SpaziAzione.get(0).Valore); assertEquals(7, torre.SpaziAzione.get(3).Valore); } @Test public void torreOccupata() throws Exception { assertFalse(torre.TorreOccupata()); Giocatore giocatore = new Giocatore(); torre.SpaziAzione.get(1).FamiliarePiazzato = new Familiare(giocatore, ColoreDado.NERO); assertTrue(torre.TorreOccupata()); } @Test(expected = DomainException.class) public void validaPiazzamentoFamiliare_stessoGiocatore() throws Exception { Giocatore giocatore = new Giocatore(); torre.SpaziAzione.get(1).FamiliarePiazzato = new Familiare(giocatore, ColoreDado.NERO); torre.ValidaPiazzamentoFamiliare(new Familiare(giocatore, ColoreDado.ARANCIO)); } @Test public void validaPiazzamentoFamiliare_familiareNeutro() throws Exception { Giocatore giocatore = new Giocatore(); torre.SpaziAzione.get(1).FamiliarePiazzato = new Familiare(giocatore, ColoreDado.NERO); torre.ValidaPiazzamentoFamiliare(new Familiare(giocatore, ColoreDado.NEUTRO)); } @Test public void validaPiazzamentoFamiliare_torreVuota() throws Exception { Giocatore giocatore = new Giocatore(); torre.ValidaPiazzamentoFamiliare(new Familiare(giocatore, ColoreDado.NEUTRO)); } @Test public void pescaCarte() throws Exception { ArrayList<Carta> carteDisponibili = new ArrayList<>(); for(int i = 0; i < 4; i++ ) carteDisponibili.add(new CartaTerritorio("nome"+i, 1, 1, new ArrayList<>(), new ArrayList<>())); torre.PescaCarte(1, carteDisponibili); assertTrue(torre.SpaziAzione.stream().allMatch(x -> x.FamiliarePiazzato == null)); assertTrue(torre.SpaziAzione.stream().allMatch(x -> x.CartaAssociata != null)); } }
package bootcamp.test.elements; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class IsDisplayed { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); // to launch a page driver.get("file:///Users/kunalashar/automation_bootcamp/SeleniumWebDriver/src/main/resources/hidden.html"); System.out.println(driver.findElement(By.id("lname")).isDisplayed()); driver.quit(); } }
package polydungeons.item; import net.minecraft.item.Item; public class EssenceItem extends Item { public EssenceItem(Settings settings) { super(settings); } }
package Structural.Composite; //Composite Class // This will have operations to access child public class Menu extends MenuComponent{ public Menu(String name , String url) { this.name = name; this.url = url; } public MenuComponent add(MenuComponent menuComponent){ this.menuComponents.add(menuComponent); return menuComponent; } public MenuComponent remove(MenuComponent menuComponent){ this.menuComponents.remove(menuComponent); return menuComponent; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.print(this)); menuComponents.forEach( component ->{ builder.append(component.toString()); }); return builder.toString(); } }
/** * Tina Rickard, William Eggert * CSC 365-03 * Lab 8: Database Connectivity with JDBC */ import java.io.*; import java.util.*; import java.sql.*; import java.lang.*; import java.text.*; import java.util.Date; public class InnReservations { static String url = null; static String user = null; static String pw = null; static boolean roomsExist = false; static boolean reservationsExist = false; static boolean roomsFilled = false; static boolean reservationsFilled = false; static Connection conn = null; static String cur = ""; static int state = 1; static int adminState; static int guestState; public static void main(String args[]) throws ParseException { // reads server settings try { FileReader fr = new FileReader("ServerSettings.txt"); BufferedReader br = new BufferedReader(fr); url = br.readLine(); user = br.readLine(); pw = br.readLine(); br.close(); } catch (Exception e) { } // opens connection try { Class.forName("com.mysql.jdbc.Driver").newInstance(); System.out.println("Driver class found and loaded."); } catch (Exception ex) { System.out.println("Driver not found"); System.out.println(ex); } ; try { conn = DriverManager.getConnection(url + "?" + "user=" + user + "&password=" + pw); } catch (Exception ex) { System.out.println("Could not open connection"); System.out.println(ex); } ; // checks for table existence try { DatabaseMetaData md = conn.getMetaData(); ResultSet rs = md.getTables(null, null, "rooms", null); if (rs.next()) roomsExist = true; rs = md.getTables(null, null, "reservations", null); if (rs.next()) reservationsExist = true; } catch (Exception e) { } // creates tables if not already created if (!roomsExist) try { String roomTable = "CREATE TABLE rooms (RoomCode CHAR(5) PRIMARY KEY," + "RoomName VARCHAR(30) UNIQUE, Beds INTEGER, bedType varchar(8)," + "maxOcc INTEGER, basePrice FLOAT, decor VARCHAR(20))"; Statement s1 = conn.createStatement(); s1.executeUpdate(roomTable); roomsExist = true; } catch (Exception e) { } if (!reservationsExist) try { String resTable = "CREATE TABLE reservations (CODE INTEGER PRIMARY KEY, " + "Room CHAR(5), CheckIn DATE, Checkout DATE, Rate FLOAT, LastName " + "VARCHAR(15), FirstName VARCHAR(15), Adults Integer, Kids INTEGER, " + "FOREIGN KEY (room) REFERENCES rooms(RoomCode))"; Statement s2 = conn.createStatement(); s2.executeUpdate(resTable); reservationsExist = true; } catch (Exception e) { System.out.println(e); } // checks if table populated try { Statement s3 = conn.createStatement(); ResultSet rs = s3.executeQuery("SELECT COUNT(*) FROM rooms"); rs.next(); if (rs.getInt(1) > 0) roomsFilled = true; Statement s4 = conn.createStatement(); rs = s4.executeQuery("SELECT COUNT(*) FROM reservations"); rs.next(); if (rs.getInt(1) > 0) reservationsFilled = true; } catch (Exception e) { System.out.println(e); } // main loop while (state > 0) { adminState = 1; guestState = 1; System.out.println("Enter A for Admin"); System.out.println("Enter O for Owner"); System.out.println("Enter G for Guest"); System.out.println("Enter E for Exit"); Scanner scan = new Scanner(System.in); String s = scan.next(); if (s.equals("E")) state = 0; else if (s.equals("A")) runAdmin(); else if (s.equals("O")) runOwnerMenu(); else if (s.equals("G")) runGuestMenu(); } // closes connection try { conn.close(); } catch (Exception ex) { System.out.println("ex177: Unable to close connection"); } ; } // -- ADMIN FUNCTIONS -- public static void runAdmin() { Statement s; ResultSet rs; Scanner scan = new Scanner(System.in); while (adminState > 0) { System.out.println(); if (!roomsExist) System.out.println("No database"); else { if (roomsFilled) System.out.println("Full"); else System.out.println("Empty"); } try { s = conn.createStatement(); rs = s.executeQuery("SELECT COUNT(*) FROM reservations"); rs.next(); System.out.println("Reservations: " + rs.getInt(1)); rs = s.executeQuery("SELECT COUNT(*) FROM rooms"); rs.next(); System.out.println("Rooms: " + rs.getInt(1)); } catch (Exception e) { } System.out.println("Enter V to view tables"); System.out.println("Enter C to clear tables"); System.out.println("Enter L to load tables"); System.out.println("Enter R to remove tables"); System.out.println("Enter E to switch user type"); String curS = scan.next(); if (curS.equals("E")) { adminState = 0; System.out.println(" "); } else if (curS.equals("V")) adminDisplay(); else if (curS.equals("C")) adminClear(); else if (curS.equals("L")) adminLoad(); else if (curS.equals("R")) adminRemove(); } } public static void adminDisplay() { System.out.println(); if (!roomsExist) System.out.println("There are no tables to display"); else if (!roomsFilled) System.out.println("The tables are empty"); else { System.out.println("Enter Ro for rooms"); System.out.println("Enter Re for reservations"); System.out.println("Enter anything else to return to admin display"); Scanner scan = new Scanner(System.in); String str = scan.next(); ResultSet rs; PreparedStatement statement; int i = 1; try { if (str.equals("Ro")) { statement = conn.prepareStatement("select * from rooms"); rs = statement.executeQuery(); System.out.printf("%3s%11s%27s%7s%10s%12s%9s%14s\n", "No", "RoomCode", "RoomName", "Beds", "bedType", "Occupancy", "Price", "Decor"); while (rs.next()) { System.out.printf("%3d", i); System.out.printf("%11s", rs.getString("RoomCode")); System.out.printf("%27s", rs.getString("RoomName")); System.out.printf("%7s", rs.getInt("Beds")); System.out.printf("%10s", rs.getString("bedType")); System.out.printf("%12s", rs.getInt("maxOcc")); System.out.printf("%9.2f", rs.getFloat("basePrice")); System.out.printf("%14s", rs.getString("decor")); System.out.println(); i++; } } if (str.equals("Re")) { statement = conn.prepareStatement("select * from reservations"); rs = statement.executeQuery(); System.out.printf("%3s%8s%7s%13s%13s%9s%16s%16s%9s%7s\n", "No", "CODE", "Room", "CheckIn", "CheckOut", "Rate", "LastName", "FirstName", "Adults", "Kids"); while (rs.next()) { System.out.printf("%3d", i); System.out.printf("%8s", rs.getInt("CODE")); System.out.printf("%7s", rs.getString("Room")); System.out.printf("%13s", rs.getDate("CheckIn")); System.out.printf("%13s", rs.getDate("Checkout")); System.out.printf("%9.2f", rs.getFloat("Rate")); System.out.printf("%16s", rs.getString("LastName")); System.out.printf("%16s", rs.getString("FirstName")); System.out.printf("%9s", rs.getInt("Adults")); System.out.printf("%7s", rs.getInt("Kids")); System.out.println(); i++; } } } catch (Exception e) { } } } public static void adminClear() { if (roomsExist && roomsFilled) { try { Statement s = conn.createStatement(); s.executeUpdate("delete from reservations"); s.executeUpdate("delete from rooms"); roomsFilled = false; reservationsFilled = false; System.out.println("Both tables have been cleared"); } catch (Exception e) { System.out.println(e); } } } public static void adminLoad() { if (roomsExist && roomsFilled) System.out.println("Tables are already created and populated"); if (!roomsExist) { try { String roomTable = "CREATE TABLE rooms (RoomCode CHAR(5) PRIMARY KEY," + "RoomName VARCHAR(30) UNIQUE, Beds INTEGER, bedType varchar(8)," + "maxOcc INTEGER, basePrice FLOAT, decor VARCHAR(20))"; Statement s1 = conn.createStatement(); s1.executeUpdate(roomTable); roomsExist = true; } catch (Exception e) { } try { String resTable = "CREATE TABLE reservations (CODE INTEGER PRIMARY KEY, " + "Room CHAR(5), CheckIn DATE, Checkout DATE, Rate FLOAT, LastName " + "VARCHAR(15), FirstName VARCHAR(15), Adults Integer, Kids INTEGER, " + "FOREIGN KEY (room) REFERENCES rooms(RoomCode))"; Statement s2 = conn.createStatement(); s2.executeUpdate(resTable); reservationsExist = true; } catch (Exception e) { System.out.println(e); } } if (!roomsFilled) { try { String psText = "INSERT INTO rooms VALUES(?,?,?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(psText); BufferedReader br = new BufferedReader(new FileReader("Rooms.csv")); String line = ""; while ((line = br.readLine()) != null) { line = line.replace("'", ""); String[] roomRes = line.split(","); ps.setString(1, roomRes[0]); ps.setString(2, roomRes[1]); ps.setInt(3, Integer.parseInt(roomRes[2])); ps.setString(4, roomRes[3]); ps.setInt(5, Integer.parseInt(roomRes[4])); ps.setFloat(6, Float.parseFloat(roomRes[5])); ps.setString(7, roomRes[6]); ps.executeUpdate(); } roomsFilled = true; psText = "INSERT INTO reservations VALUES(?,?," + "STR_TO_DATE(?,'%d-%b-%Y'),STR_TO_DATE(?,'%d-%b-%Y'),?,?,?,?,?)"; ps = conn.prepareStatement(psText); br = new BufferedReader(new FileReader("Reservations.csv")); line = ""; while ((line = br.readLine()) != null) { line = line.replace("'", ""); String[] resRes = line.split(","); ps.setInt(1, Integer.parseInt(resRes[0])); ps.setString(2, resRes[1]); ps.setString(3, resRes[2]); ps.setString(4, resRes[3]); ps.setFloat(5, Float.parseFloat(resRes[4])); ps.setString(6, resRes[5]); ps.setString(7, resRes[6]); ps.setInt(8, Integer.parseInt(resRes[7])); ps.setInt(9, Integer.parseInt(resRes[8])); ps.executeUpdate(); } reservationsFilled = true; } catch (Exception e) { System.out.println(e); } } } public static void adminRemove() { try { Statement s = conn.createStatement(); s.executeUpdate("drop table reservations"); s.executeUpdate("drop table rooms"); reservationsExist = false; reservationsFilled = false; roomsExist = false; roomsFilled = false; } catch (Exception e) { System.out.println(e); } } // -- OWNER FUNCTIONS -- public static void runOwnerMenu() throws ParseException { int ownerState = 1; while (ownerState > 0) { System.out.println(""); System.out.println("Enter Occ for occupancy review"); System.out.println("Enter Rev for view revenue"); System.out.println("Enter Res for review reservations"); System.out.println("Enter Ro for review rooms"); System.out.println("Enter E to return to switch user type"); Scanner slay = new Scanner(System.in); String na = slay.next(); System.out.println(""); if (na.equals("E")) ownerState = 0; else if (na.equals("Occ")) runOccRev(); else if (na.equals("Rev")) runViewRev(); else if (na.equals("Ro")) runRevRooms(); else if (na.equals("Res")) runRevRes(); } } // OR-1 public static void runOccRev() { System.out.println("Options:"); System.out.println("1 - One day"); System.out.println("2 - Date range"); System.out.println("E - Return to Owner menu"); System.out.print("Enter choice: "); Scanner slay = new Scanner(System.in); String na = slay.next(); System.out.println(""); if (na.equals("1")) checkSingleAvail(); else if (na.equals("2")) checkRangeAvail(); else if (na.toUpperCase().equals("E")) return; else System.out.println("Invalid option"); } public static void checkSingleAvail() { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { int month = 0, day = 0; Scanner scan = new Scanner(System.in); System.out.println("Single date - enter values in numbers"); System.out.print("Enter month: "); try { month = scan.nextInt(); } catch (Exception e) { System.out.println("Invalid number"); return; } System.out.print("Enter day: "); try { day = scan.nextInt(); } catch (Exception e) { System.out.println("Invalid number"); return; } System.out.println(); try { String date = "2010-" + month + "-" + day; statement = conn.prepareStatement("" + "select ro.RoomCode, ro.RoomName, " + "case when ro.RoomName in (" + "select ro.RoomName " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and re.CheckIn <= ? " + "and ? < re.CheckOut" + ") then ? " + "else ? end as Vacancy " + "from rooms ro" + ";" ); statement.setString(1, date); statement.setString(2, date); statement.setString(3, "Occupied"); statement.setString(4, "Empty"); System.out.printf("Date: %s\n", date); rs = statement.executeQuery(); int i = 1; String headers = String.format("%3s%5s%25s | %s", "No", "CODE", "RoomName", "Vacancy"); String border = getBorder(headers.length()); System.out.println(headers); System.out.println(border); while (rs.next()) { System.out.printf("%3d", i); System.out.printf("%5s%25s | %s", rs.getString("RoomCode"), rs.getString("RoomName"), rs.getString("Vacancy")); System.out.println(); i++; } viewSingleRes(rs, date); } catch (Exception e) { } } else { System.out.println("Tables not created/filled"); } } public static String getBorder(int times) { return String.format("%0" + times + "d", 0).replace("0", "-"); } public static void viewSingleRes(ResultSet rs, String date) { boolean view = true; Scanner scan = new Scanner(System.in); while (view = true) { System.out.println(); System.out.println("Enter 3-digit room code to view reservation details"); System.out.println("Enter E to return to menu"); System.out.print("Input: "); String input = scan.next(); if (!input.toUpperCase().equals("E")) { System.out.println(); getSingleRes(input, date); } else { view = false; break; } } } public static void getSingleRes(String code, String date) { ResultSet rs; try { PreparedStatement statement = conn.prepareStatement("" + "select ro.RoomName, re.* " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and ro.RoomCode = ? " + "and re.CheckIn <= ? " + "and ? < re.Checkout" + ";" ); statement.setString(1, code); statement.setString(2, date); statement.setString(3, date); rs = statement.executeQuery(); displayReservations(rs); } catch (Exception e) { System.out.println(e); } } public static void displayReservations(ResultSet rs) { String headers = String.format("%25s%8s%7s%13s%13s%9s%16s%16s%9s%7s", "RoomName", "CODE", "Room", "CheckIn", "CheckOut", "Rate", "LastName", "FirstName", "Adults", "Kids"); System.out.println(headers); System.out.println(getBorder(headers.length())); try { while (rs.next()) { System.out.printf("%25s", rs.getString("RoomName")); System.out.printf("%8s", rs.getInt("CODE")); System.out.printf("%7s", rs.getString("Room")); System.out.printf("%13s", rs.getDate("CheckIn")); System.out.printf("%13s", rs.getDate("Checkout")); System.out.printf("%9.2f", rs.getFloat("Rate")); System.out.printf("%16s", rs.getString("LastName")); System.out.printf("%16s", rs.getString("FirstName")); System.out.printf("%9s", rs.getInt("Adults")); System.out.printf("%7s", rs.getInt("Kids")); System.out.println(); } } catch (Exception e) { } } public static void checkRangeAvail() { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { int[][] range = new int[2][2]; String startDate = "", endDate = ""; System.out.println("Date range - enter values in numbers"); for (int i = 0; i < 2; i++) { System.out.println("Day " + (i + 1)); Scanner scan = new Scanner(System.in); System.out.print("Enter month: "); try { range[i][0] = scan.nextInt(); } catch (Exception e) { System.out.println("Invalid number"); return; } System.out.print("Enter day: "); try { range[i][1] = scan.nextInt(); } catch (Exception e) { System.out.println("Invalid number"); return; } System.out.println(); startDate = "2010-" + range[0][0] + "-" + range[0][1]; endDate = "2010-" + range[1][0] + "-" + range[1][1]; } try { statement = conn.prepareStatement("" + "select ro.RoomCode, ro.RoomName, " + "case when res.Days IS NULL then ? " // ? 1 + "when res.Days = DATEDIFF(?, ?) + 1 then ? " // ? 2, 3, 4 + "else ? " // ? 5 + "end as Vacancy " + "from rooms ro " + "left outer join ( " + "select re.Room, count(distinct dates) as Days " + "from ( " + "select selected_date as dates " + "from " + "(select adddate('2010-1-1', t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from " + "(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0, " + "(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1, " + "(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2, " + "(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3) v " + "where selected_date between cast(? as date) and cast(? as date) " // ? 6, 7 + ") as dates " + "inner join ( " + "select re.Room, re.CODE, re.CheckIn, re.Checkout " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and ? < re.Checkout " // ? 8 + "and re.CheckIn <= ? " // ? 9 + "order by re.Room " + ") as re " + "on dates between cast(re.CheckIn as date) and cast(re.Checkout as date) " + "group by re.Room " + "order by re.Room, Days " + ") as res " + "on ro.RoomCode = res.Room " + ";" ); statement.setString(1, "Vacant"); statement.setString(2, endDate); statement.setString(3, startDate); statement.setString(4, "Full"); statement.setString(5, "Partially Occupied"); statement.setString(6, startDate); statement.setString(7, endDate); statement.setString(8, startDate); statement.setString(9, endDate); rs = statement.executeQuery(); String headers = String.format("%8s%25s | %-18s", "RoomCode", "RoomName", "Vacancy"); System.out.println(headers); System.out.println(getBorder(headers.length())); while (rs.next()) { System.out.printf("%8s", rs.getString("RoomCode")); System.out.printf("%25s | ", rs.getString("RoomName")); System.out.printf("%-18s", rs.getString("Vacancy")); System.out.println(); } viewBriefRangeRes(rs, startDate, endDate); } catch (Exception e) { System.out.println(e); } } else { System.out.println("Tables not created/filled"); } } public static void viewBriefRangeRes(ResultSet rs, String startDate, String endDate) { boolean view = true; Scanner scan = new Scanner(System.in); while (view = true) { System.out.println(); // System.out.println("Enter V to view reservations"); System.out.println("Enter 3-digit room code to view reservations"); System.out.println("Enter E to return to menu"); System.out.print("Input: "); String input = scan.next(); if (!input.toUpperCase().equals("E")) { System.out.println(); getRangeRes(input, startDate, endDate); } else { view = false; break; } } } public static void getRangeRes(String code, String startDate, String endDate) { ResultSet rs; try { PreparedStatement statement = conn.prepareStatement("" + "select re.Room, ro.RoomName, re.CODE, re.CheckIn, re.Checkout " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and ro.RoomCode = ? " + "and ? < re.Checkout " + "and re.CheckIn <= ? " + ";" ); statement.setString(1, code); statement.setString(2, startDate); statement.setString(3, endDate); rs = statement.executeQuery(); displayBriefReservations(rs); viewRangeRes(); } catch (Exception e) { System.out.println(e); } } public static void displayBriefReservations(ResultSet rs) { String headers = String.format("%25s%8s%13s%13s", "RoomName", "CODE", "CheckIn", "CheckOut"); System.out.println(headers); System.out.println(getBorder(headers.length())); try { while (rs.next()) { System.out.printf("%25s", rs.getString("RoomName")); System.out.printf("%8s", rs.getInt("CODE")); System.out.printf("%13s", rs.getDate("CheckIn")); System.out.printf("%13s", rs.getDate("Checkout")); System.out.println(); } } catch (Exception e) { } } public static void viewRangeRes() { boolean view = true; Scanner scan = new Scanner(System.in); while (view = true) { System.out.println(); System.out.println("Enter 5-digit reservation code to view details"); System.out.println("Enter E to return to previous"); System.out.print("Input: "); String input = scan.next(); if (!input.toUpperCase().equals("E")) { System.out.println(); getResDetails(input); } else { view = false; break; } } } public static void getResDetails(String code) { ResultSet rs; try { PreparedStatement statement = conn.prepareStatement("" + "select ro.RoomName, re.* " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and re.CODE = ? " + ";" ); statement.setString(1, code); rs = statement.executeQuery(); displayReservations(rs); } catch (Exception e) { System.out.println(e); } } // OR-2 public static void runViewRev() { boolean loop = true; while (loop = true) { System.out.println("Options:"); System.out.println("1 - Reservation counts"); System.out.println("2 - Total days occupied"); System.out.println("3 - Monthly revenue"); System.out.println("E - Return to Owner menu"); System.out.print("Enter choice: "); Scanner slay = new Scanner(System.in); String na = slay.next(); System.out.println(""); if (na.equals("1")) resCounts(); else if (na.equals("2")) totalDaysOcc(); else if (na.equals("3")) monthlyRev(); else if (na.toUpperCase().equals("E")) return; else System.out.println("Invalid option"); } } public static void resCounts() { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { try { statement = conn.prepareStatement("" + "select ro.RoomName, " + "sum(case when month(re.Checkout) = 1 then 1 else 0 end) as January, " + "sum(case when month(re.Checkout) = 2 then 1 else 0 end) as February, " + "sum(case when month(re.Checkout) = 3 then 1 else 0 end) as March, " + "sum(case when month(re.Checkout) = 4 then 1 else 0 end) as April, " + "sum(case when month(re.Checkout) = 5 then 1 else 0 end) as May, " + "sum(case when month(re.Checkout) = 6 then 1 else 0 end) as June, " + "sum(case when month(re.Checkout) = 7 then 1 else 0 end) as July, " + "sum(case when month(re.Checkout) = 8 then 1 else 0 end) as August, " + "sum(case when month(re.Checkout) = 9 then 1 else 0 end) as September, " + "sum(case when month(re.Checkout) = 10 then 1 else 0 end) as October, " + "sum(case when month(re.Checkout) = 11 then 1 else 0 end) as November, " + "sum(case when month(re.Checkout) = 12 then 1 else 0 end) as December, " + "count(*) as TOTALS " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "group by re.Room " + "union " + "select ?, " + "sum(case when month(re.Checkout) = 1 then 1 else 0 end) as January, " + "sum(case when month(re.Checkout) = 2 then 1 else 0 end) as February, " + "sum(case when month(re.Checkout) = 3 then 1 else 0 end) as March, " + "sum(case when month(re.Checkout) = 4 then 1 else 0 end) as April, " + "sum(case when month(re.Checkout) = 5 then 1 else 0 end) as May, " + "sum(case when month(re.Checkout) = 6 then 1 else 0 end) as June, " + "sum(case when month(re.Checkout) = 7 then 1 else 0 end) as July, " + "sum(case when month(re.Checkout) = 8 then 1 else 0 end) as August, " + "sum(case when month(re.Checkout) = 9 then 1 else 0 end) as September, " + "sum(case when month(re.Checkout) = 10 then 1 else 0 end) as October, " + "sum(case when month(re.Checkout) = 11 then 1 else 0 end) as November, " + "sum(case when month(re.Checkout) = 12 then 1 else 0 end) as December, " + "count(*) as TOTALS " + "from reservations re " + ";" ); statement.setString(1, "TOTALS"); rs = statement.executeQuery(); printResTables(rs); } catch (Exception e) { System.out.println(e); } } else { System.out.println("Tables not created/filled"); } } public static void totalDaysOcc() { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { try { statement = conn.prepareStatement("" + "select ro.RoomName, " + "sum(case when month(re.Checkout) = 1 then datediff(re.Checkout, re.CheckIn) else 0 end) as January, " + "sum(case when month(re.Checkout) = 2 then datediff(re.Checkout, re.CheckIn) else 0 end) as February, " + "sum(case when month(re.Checkout) = 3 then datediff(re.Checkout, re.CheckIn) else 0 end) as March, " + "sum(case when month(re.Checkout) = 4 then datediff(re.Checkout, re.CheckIn) else 0 end) as April, " + "sum(case when month(re.Checkout) = 5 then datediff(re.Checkout, re.CheckIn) else 0 end) as May, " + "sum(case when month(re.Checkout) = 6 then datediff(re.Checkout, re.CheckIn) else 0 end) as June, " + "sum(case when month(re.Checkout) = 7 then datediff(re.Checkout, re.CheckIn) else 0 end) as July, " + "sum(case when month(re.Checkout) = 8 then datediff(re.Checkout, re.CheckIn) else 0 end) as August, " + "sum(case when month(re.Checkout) = 9 then datediff(re.Checkout, re.CheckIn) else 0 end) as September, " + "sum(case when month(re.Checkout) = 10 then datediff(re.Checkout, re.CheckIn) else 0 end) as October, " + "sum(case when month(re.Checkout) = 11 then datediff(re.Checkout, re.CheckIn) else 0 end) as November, " + "sum(case when month(re.Checkout) = 12 then datediff(re.Checkout, re.CheckIn) else 0 end) as December, " + "sum(datediff(re.Checkout, re.CheckIn)) as TOTALS " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "group by re.Room " + "union " + "select ?, " + "sum(case when month(re.Checkout) = 1 then datediff(re.Checkout, re.CheckIn) else 0 end) as January, " + "sum(case when month(re.Checkout) = 2 then datediff(re.Checkout, re.CheckIn) else 0 end) as February, " + "sum(case when month(re.Checkout) = 3 then datediff(re.Checkout, re.CheckIn) else 0 end) as March, " + "sum(case when month(re.Checkout) = 4 then datediff(re.Checkout, re.CheckIn) else 0 end) as April, " + "sum(case when month(re.Checkout) = 5 then datediff(re.Checkout, re.CheckIn) else 0 end) as May, " + "sum(case when month(re.Checkout) = 6 then datediff(re.Checkout, re.CheckIn) else 0 end) as June, " + "sum(case when month(re.Checkout) = 7 then datediff(re.Checkout, re.CheckIn) else 0 end) as July, " + "sum(case when month(re.Checkout) = 8 then datediff(re.Checkout, re.CheckIn) else 0 end) as August, " + "sum(case when month(re.Checkout) = 9 then datediff(re.Checkout, re.CheckIn) else 0 end) as September, " + "sum(case when month(re.Checkout) = 10 then datediff(re.Checkout, re.CheckIn) else 0 end) as October, " + "sum(case when month(re.Checkout) = 11 then datediff(re.Checkout, re.CheckIn) else 0 end) as November, " + "sum(case when month(re.Checkout) = 12 then datediff(re.Checkout, re.CheckIn) else 0 end) as December, " + "sum(datediff(re.Checkout, re.CheckIn)) as TOTALS " + "from reservations re " + ";" ); statement.setString(1, "TOTALS"); rs = statement.executeQuery(); printResTables(rs); } catch (Exception e) { System.out.println(e); } } else { System.out.println("Tables not created/filled"); } } public static void monthlyRev() { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { try { statement = conn.prepareStatement("" + "select ro.RoomName, " + "sum(case when month(re.Checkout) = 1 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as January, " + "sum(case when month(re.Checkout) = 2 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as February, " + "sum(case when month(re.Checkout) = 3 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as March, " + "sum(case when month(re.Checkout) = 4 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as April, " + "sum(case when month(re.Checkout) = 5 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as May, " + "sum(case when month(re.Checkout) = 6 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as June, " + "sum(case when month(re.Checkout) = 7 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as July, " + "sum(case when month(re.Checkout) = 8 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as August, " + "sum(case when month(re.Checkout) = 9 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as September, " + "sum(case when month(re.Checkout) = 10 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as October, " + "sum(case when month(re.Checkout) = 11 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as November, " + "sum(case when month(re.Checkout) = 12 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as December, " + "sum(re.Rate * datediff(re.Checkout, re.CheckIn)) as TOTALS " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "group by re.Room " + "union " + "select ?, " + "sum(case when month(re.Checkout) = 1 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as January, " + "sum(case when month(re.Checkout) = 2 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as February, " + "sum(case when month(re.Checkout) = 3 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as March, " + "sum(case when month(re.Checkout) = 4 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as April, " + "sum(case when month(re.Checkout) = 5 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as May, " + "sum(case when month(re.Checkout) = 6 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as June, " + "sum(case when month(re.Checkout) = 7 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as July, " + "sum(case when month(re.Checkout) = 8 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as August, " + "sum(case when month(re.Checkout) = 9 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as September, " + "sum(case when month(re.Checkout) = 10 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as October, " + "sum(case when month(re.Checkout) = 11 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as November, " + "sum(case when month(re.Checkout) = 12 then re.Rate * datediff(re.Checkout, re.CheckIn) else 0 end) as December, " + "sum(re.Rate * datediff(re.Checkout, re.CheckIn)) as TOTALS " + "from reservations re " + ";" ); statement.setString(1, "TOTALS"); rs = statement.executeQuery(); printRevTable(rs); } catch (Exception e) { System.out.println(e); } } else { System.out.println("Tables not created/filled"); } } public static void printResTables(ResultSet rs) { String headers = String.format( "%27s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s", "RoomName", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "TOTALS" ); System.out.println(headers); System.out.println(getBorder(headers.length())); try { while(rs.next()) { System.out.printf( "%27s%11d%11d%11d%11d%11d%11d%11d%11d%11d%11d%11d%11d%11s\n", rs.getString("RoomName"), // 0 rs.getInt("January"), // 1 rs.getInt("February"), // 2 rs.getInt("March"), // 3 rs.getInt("April"), // 4 rs.getInt("May"), // 5 rs.getInt("June"), // 6 rs.getInt("July"), // 7 rs.getInt("August"), // 8 rs.getInt("September"), // 9 rs.getInt("October"), // 10 rs.getInt("November"), // 11 rs.getInt("December"), // 12 rs.getInt("TOTALS") // 13 ); } System.out.println(); } catch (Exception e) { System.out.println(e); } } public static void printRevTable(ResultSet rs) { String headers = String.format( "%27s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s", "RoomName", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "TOTALS" ); System.out.println(headers); System.out.println(getBorder(headers.length())); try { while(rs.next()) { System.out.printf( "%27s%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f%11.2f\n", rs.getString("RoomName"), // 0 rs.getFloat("January"), // 1 rs.getFloat("February"), // 2 rs.getFloat("March"), // 3 rs.getFloat("April"), // 4 rs.getFloat("May"), // 5 rs.getFloat("June"), // 6 rs.getFloat("July"), // 7 rs.getFloat("August"), // 8 rs.getFloat("September"), // 9 rs.getFloat("October"), // 10 rs.getFloat("November"), // 11 rs.getFloat("December"), // 12 rs.getFloat("TOTALS") // 13 ); } System.out.println(); } catch (Exception e) { System.out.println(e); } } // OR-3 public static void runRevRes() { if (roomsExist && roomsFilled) { boolean loop = true; Scanner scan = new Scanner(System.in); while (loop) { String startDate = "2010-1-1"; String endDate = "2011-12-31"; String room = "*"; System.out.println("Enter E at any time to return to menu"); System.out.print("Select date range? (y/n): "); String input = scan.next().toUpperCase(); if (input.equals("Y") || input.equals("YES")) { System.out.print("Enter start date (YYYY-MM-DD): "); startDate = scan.next(); if (startDate.toUpperCase().equals("E")) return; System.out.print("Enter end date (YYYY-MM-DD): "); endDate = scan.next(); if (endDate.toUpperCase().equals("E")) return; } else if (input.equals("N") || input.equals("NO")) { // Ok then } else if (input.equals("E")) { return; } else { System.out.println("Invalid input"); } System.out.print("Select specific room? (y/n): "); input = scan.next().toUpperCase(); if (input.equals("Y") || input.equals("YES")) { System.out.println(); printRooms(); System.out.print("Enter 3-digit room code: "); room = scan.next(); if (room.toUpperCase().equals("E")) return; } else if (input.equals("N") || input.equals("NO")) { // Ok then } else if (input.equals("E")) { return; } else { System.out.println("Invalid input"); } revRes(room, startDate, endDate); } } else { System.out.println("Tables not created/filled"); } } public static void printRooms() { try { PreparedStatement statement = conn.prepareStatement("" + "select * " + "from rooms ro " + ";" ); ResultSet rs = statement.executeQuery(); String headers = String.format("%8s%27s", "RoomCode", "RoomName"); System.out.println(headers); System.out.println(getBorder(headers.length())); while (rs.next()) { System.out.printf("%8s%27s\n", rs.getString("RoomCode"), rs.getString("RoomName")); } System.out.println(); } catch (Exception e) { System.out.println(e); } } public static void revRes(String code, String startDate, String endDate) { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { try { if (code.equals("*")) { statement = conn.prepareStatement("" + "select ro.RoomName, re.CODE, re.CheckIn, re.Checkout " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and ? <= re.CheckIn " + "and re.CheckIn <= ? " + "order by ro.RoomCode, re.CheckIn " + ";" ); statement.setString(1, startDate); statement.setString(2, endDate); } else { statement = conn.prepareStatement("" + "select ro.RoomName, re.CODE, re.CheckIn, re.Checkout " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and ro.RoomCode = ? " + "and ? <= re.CheckIn " + "and re.CheckIn <= ? " + "order by ro.RoomCode, re.CheckIn " + ";" ); statement.setString(1, code); statement.setString(2, startDate); statement.setString(3, endDate); } rs = statement.executeQuery(); System.out.println(); displayBriefReservations(rs); viewRangeRes(); } catch (Exception e) { System.out.println(e); } } } // OR-4 public static void runRevRooms() { if (roomsExist && roomsFilled) { boolean loop = true; Scanner scan = new Scanner(System.in); while (loop) { printRooms(); System.out.println("Options:"); System.out.println("1 - View room info"); System.out.println("2 - View room reservations"); System.out.println("E - Return to Owner menu"); System.out.print("Input: "); String input = scan.next(); if (input.toUpperCase().equals("E")) return; System.out.print("Enter 3-digit code of room to view: "); String code = scan.next(); if (input.equals("1")) { displayRoomInfo(code); } else if (input.equals("2")) { displayRoomRes(code); } else { System.out.println("Invalid input"); } } } else { System.out.println("Tables not created/filled"); } } public static void displayRoomInfo(String code) { ResultSet rs; PreparedStatement statement; try { statement = conn.prepareStatement("" + "select r.*, (r.DaysOccupied / z.Days) * 100 as PercentDays, " + "(r.TotalRevenue / z.Revenue) * 100 as PercentRevenue " + "from " + "(select ro.*, sum(datediff(re.Checkout, re.CheckIn)) as DaysOccupied, " + "sum(re.Rate * datediff(re.Checkout, re.CheckIn)) as TotalRevenue " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and year(re.Checkout) = 2010 " + "and ro.RoomCode = ? " + ") as r, " + "(select sum(datediff(re.Checkout, re.CheckIn)) as Days, " + "sum(re.Rate * datediff(re.Checkout, re.CheckIn)) as Revenue " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and year(re.Checkout) = 2010 " + ") as z " + ";" ); statement.setString(1, code); rs = statement.executeQuery(); System.out.println(); String headers = String.format("%8s%27s%6s%9s%8s%10s%13s%14s%14s%13s%17s", "RoomCode", "RoomName", "Beds", "bedType", "maxOcc", "basePrice", "decor", "DaysOccupied", "TotalRevenue", "PercentDays", "PercentRevenue"); System.out.println(headers); System.out.println(getBorder(headers.length())); while (rs.next()) { System.out.printf("%8s", rs.getString("RoomCode")); System.out.printf("%27s", rs.getString("RoomName")); System.out.printf("%6s", rs.getString("Beds")); System.out.printf("%9s", rs.getString("bedType")); System.out.printf("%8s", rs.getString("maxOcc")); System.out.printf("%10.2f", rs.getFloat("basePrice")); System.out.printf("%13s", rs.getString("decor")); System.out.printf("%14s", rs.getString("DaysOccupied")); System.out.printf("%14s", rs.getString("TotalRevenue")); System.out.printf("%13.2f", rs.getFloat("PercentDays")); System.out.printf("%17.2f", rs.getFloat("PercentRevenue")); } System.out.println("\n"); } catch (Exception e) { System.out.print(e); } } public static void displayRoomRes(String code) { ResultSet rs; PreparedStatement statement; try { statement = conn.prepareStatement("" + "select ro.RoomName, re.* " + "from rooms ro, reservations re " + "where ro.RoomCode = re.Room " + "and re.Room = ? " + "order by re.CheckIn " + ";" ); statement.setString(1, code); rs = statement.executeQuery(); displayBriefReservations(rs); viewRangeRes(); } catch (Exception e) { System.out.print(e); } } // -- GUEST FUNCTIONS -- public static void runGuestMenu() throws ParseException { while (guestState > 0) { System.out.println(""); System.out.println("Enter Ro for rooms and rates"); System.out.println("Enter Re for reservations"); System.out.println("Enter E to return to switch user type"); Scanner slay = new Scanner(System.in); String na = slay.next(); System.out.println(); if (na.equals("E")) guestState = 0; else if (na.equals("Ro")) runGuestRooms(); else if (na.equals("Re")) { if (roomsFilled && roomsExist) runGuestRes(); else System.out.println("Tables not created/filled"); } } } public static void runGuestRooms() { ResultSet rs; PreparedStatement statement; if (roomsExist && roomsFilled) { try { statement = conn.prepareStatement("select * from rooms"); rs = statement.executeQuery(); int i = 1; while (rs.next()) { System.out.printf("%2d%5s\n", i, rs.getString("RoomCode")); i++; } System.out.println(); } catch (Exception e) { System.out.println(e); } System.out.println("Choose a room by entering its number"); Scanner s = new Scanner(System.in); String room = s.next(); try { statement = conn.prepareStatement("select * from rooms"); rs = statement.executeQuery(); int roomNum = Integer.parseInt(room); if (roomNum < 11 && roomNum > 0 && rs != null) { rs.absolute(roomNum); System.out.println(""); String headers = String.format("%11s%27s%7s%10s%12s%9s%14s", "RoomCode", "RoomName", "Beds", "bedType", "Occupancy", "Price", "Decor"); System.out.println(headers); System.out.println(getBorder(headers.length())); System.out.printf("%11s", rs.getString("RoomCode")); System.out.printf("%27s", rs.getString("RoomName")); System.out.printf("%7s", rs.getInt("Beds")); System.out.printf("%10s", rs.getString("bedType")); System.out.printf("%12s", rs.getInt("maxOcc")); System.out.printf("%9.2f", rs.getFloat("basePrice")); System.out.printf("%14s", rs.getString("decor")); System.out.println("\n"); System.out.println("Enter C to check availability"); System.out.println("Enter anything else to return to guest menu"); room = s.next(); if (room.equals("C")) checkAvai(roomNum, rs.getString("RoomCode"), rs.getFloat("basePrice"), rs.getString("RoomName"), rs.getInt("maxOcc")); System.out.println(); } } catch (Exception e) { System.out.println("Bad input"); } } else System.out.println("Tables not created/filled"); } public static void checkAvai(int roomNum, String roomCode, double bP, String roomName, int occ) throws ParseException { boolean occupied = false; System.out.println("\nEnter the CheckIn date in YYYY DD MM format"); Scanner scan = new Scanner(System.in); String t = scan.nextLine(); StringTokenizer st = new StringTokenizer(t); String checkIn = ""; checkIn = checkIn + st.nextToken() + "." + st.nextToken() + "." + st.nextToken(); System.out.println("\nEnter the CheckOut date in YYYY DD MM format"); t = scan.nextLine(); st = new StringTokenizer(t); String checkOut = ""; checkOut = checkOut + st.nextToken() + "." + st.nextToken() + "." + st.nextToken(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.dd.MM"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); Date starts = sdf.parse(checkIn); Date ends = sdf.parse(checkOut); double mult = 1.0; Date j1 = sdf.parse("2010.01.01"); Date j4 = sdf.parse("2010.07.04"); Date s6 = sdf.parse("2010.09.06"); Date o3 = sdf.parse("2010.10.30"); Date jj = sdf.parse("2011.01.01"); Calendar start = Calendar.getInstance(); start.setTime(starts); Calendar end = Calendar.getInstance(); end.setTime(ends); if ((j1.compareTo(starts) >= 0 && j1.compareTo(ends) < 0) || (j4.compareTo(starts) >= 0 && j4.compareTo(ends) < 0) || (s6.compareTo(starts) >= 0 && s6.compareTo(ends) < 0) || (o3.compareTo(starts) >= 0 && o3.compareTo(ends) < 0) || (jj.compareTo(starts) >= 0 && jj.compareTo(ends) < 0)) mult = 1.25; if (mult == 1.0) { for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) { if (start.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || start.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) mult = 1.1; } } start.setTime(starts); for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) { System.out.println(""); System.out.printf(sdf2.format(date)); try { Statement s = conn.createStatement(); ResultSet rs; rs = s.executeQuery("SELECT COUNT(*) FROM reservations WHERE CheckIn <= '" + sdf2.format(date) + "' && Checkout > '" + sdf2.format(date) + "' && Room = '" + roomCode + "'"); rs.next(); if (!(rs.getInt(1) > 0)) System.out.print(" " + bP * mult); else { occupied = true; System.out.print(" Occupied"); } } catch (Exception e) { System.out.println(e); } } if (!occupied) { System.out.println("\nEnter P to place a reservation"); System.out.println("Enter anything else to return to guest menu"); Scanner newNew = new Scanner(System.in); if (newNew.next().equals("P")) System.out.println("place a res"); completeReservation(starts, ends, (float) bP * (float) mult, roomCode, roomName, occ); } } public static void runGuestRes() throws ParseException { try { System.out.println("Enter the CheckIn date in YYYY DD MM format"); Scanner scan = new Scanner(System.in); String t = scan.nextLine(); StringTokenizer st = new StringTokenizer(t); String checkIn = ""; checkIn = checkIn + st.nextToken() + "." + st.nextToken() + "." + st.nextToken(); System.out.println("\nEnter the CheckOut date in YYYY DD MM format"); t = scan.nextLine(); System.out.println(); st = new StringTokenizer(t); String checkOut = ""; checkOut = checkOut + st.nextToken() + "." + st.nextToken() + "." + st.nextToken(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.dd.MM"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); Date starts = sdf.parse(checkIn); Date ends = sdf.parse(checkOut); double mult = 1.0; Date j1 = sdf.parse("2010.01.01"); Date j4 = sdf.parse("2010.07.04"); Date s6 = sdf.parse("2010.09.06"); Date o3 = sdf.parse("2010.10.30"); Date jj = sdf.parse("2011.01.01"); Calendar start = Calendar.getInstance(); start.setTime(starts); Calendar end = Calendar.getInstance(); end.setTime(ends); if ((j1.compareTo(starts) >= 0 && j1.compareTo(ends) < 0) || (j4.compareTo(starts) >= 0 && j4.compareTo(ends) < 0) || (s6.compareTo(starts) >= 0 && s6.compareTo(ends) < 0) || (o3.compareTo(starts) >= 0 && o3.compareTo(ends) < 0) || (jj.compareTo(starts) >= 0 && jj.compareTo(ends) < 0)) mult = 1.25; if (mult == 1.0) { for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) { if (start.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || start.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) mult = 1.1; } } PreparedStatement s = conn.prepareStatement("SELECT RoomCode FROM rooms"); ResultSet rs = s.executeQuery(); ArrayList<String> validRooms = new ArrayList<String>(); while (rs.next()) { validRooms.add(rs.getString("RoomCode")); } start.setTime(starts); Statement sa = conn.createStatement(); ResultSet rsa; for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) { try { rsa = sa.executeQuery("SELECT DISTINCT Room FROM reservations WHERE CheckIn <= '" + sdf2.format(date) + "' && Checkout > '" + sdf2.format(date) + "'"); while (rsa.next()) { if (validRooms.contains(rsa.getString("Room"))) validRooms.remove(rsa.getString("Room")); } } catch (Exception e) { System.out.println(e); } } ArrayList<String> realName = new ArrayList<String>(); ArrayList<Float> prices = new ArrayList<Float>(); for (int i = 0; i < validRooms.size(); i++) { s = conn.prepareStatement( "SELECT RoomName, basePrice FROM rooms WHERE RoomCode = '" + validRooms.get(i) + "'"); rs = s.executeQuery(); rs.next(); realName.add(rs.getString("RoomName")); prices.add(rs.getFloat("basePrice") * (float) mult); } for (int i = 0; i < validRooms.size(); i++) { System.out.print(i + 1 + "\t"); System.out.print(validRooms.get(i) + "\t"); System.out.print(realName.get(i) + "\t"); System.out.print(prices.get(i) + "\n"); } System.out.println("\nEnter the room number you would like to view"); System.out.println("Enter anything else to return to guest menu"); Scanner sce = new Scanner(System.in); int sca = sce.nextInt(); if (sca > 0 && sca < validRooms.size() + 1) { s = conn.prepareStatement("SELECT * FROM rooms WHERE RoomCode = '" + validRooms.get(sca - 1) + "'"); rs = s.executeQuery(); rs.next(); String headers = String.format("%11s%27s%7s%10s%12s%9s%14s", "RoomCode", "RoomName", "Beds", "bedType", "Occupancy", "Price", "Decor"); System.out.println(headers); System.out.println(getBorder(headers.length())); System.out.printf("%11s", rs.getString("RoomCode")); System.out.printf("%27s", rs.getString("RoomName")); System.out.printf("%7s", rs.getInt("Beds")); System.out.printf("%10s", rs.getString("bedType")); System.out.printf("%12s", rs.getInt("maxOcc")); System.out.printf("%9s", rs.getFloat("basePrice")); System.out.printf("%14s", rs.getString("decor")); System.out.println("\n\nEnter P to place a reservation\nEnter anything else to return to guest menu"); if (sce.next().equals("P")) completeReservation(starts, ends, rs.getFloat("basePrice") * (float) mult, rs.getString("RoomCode"), rs.getString("RoomName"), rs.getInt("maxOcc")); } } catch (Exception e) { System.out.println(e); } } public static void completeReservation(Date starts, Date ends, float basePrice, String RoomCode, String RoomName, int occ) { Scanner scan = new Scanner(System.in); String first; String last; int adults = 0; int kids = 0; boolean bad = true; String temp; float disc = 1.0f; try { System.out.println("Enter first name"); first = scan.next(); System.out.println("Enter last name"); last = scan.next(); while (bad) { System.out.println("Enter number of adults"); adults = scan.nextInt(); System.out.println("Enter number of kids"); kids = scan.nextInt(); if (adults + kids > occ) System.out.println("Total occupancy exceeds maximum of " + occ); else bad = false; } System.out.println("Enter AAA for 10% discount"); System.out.println("Enter AARP for 15% discount"); System.out.println("Enter anything else for no discount"); temp = scan.next(); if (temp.equals("AAA")) disc = 0.9f; else if (temp.equals("AARP")) disc = 0.85f; System.out.println("Enter P to place a reservation"); System.out.println("Enter anything else to cancel the reservation"); temp = scan.next(); if (temp.equals("P")) { Statement sa = conn.createStatement(); ResultSet rsa = sa.executeQuery("SELECT CODE from reservations"); ArrayList<Integer> unique = new ArrayList<Integer>(); while (rsa.next()) unique.add(rsa.getInt("CODE")); int code = 100000; while (unique.contains(code)) code++; PreparedStatement ps = conn.prepareStatement("INSERT INTO reservations VALUES(?,?," + "STR_TO_DATE(?,'%Y-%m-%d'),STR_TO_DATE(?,'%Y-%m-%d'),?,?,?,?,?)"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); ps.setInt(1, code); ps.setString(2, RoomCode); ps.setString(3, sdf2.format(starts)); ps.setString(4, sdf2.format(ends)); ps.setFloat(5, basePrice * disc); ps.setString(6, last.toUpperCase()); ps.setString(7, first.toUpperCase()); ps.setInt(8, adults); ps.setInt(9, kids); ps.executeUpdate(); System.out.println("Reservation has been placed"); } } catch (Exception e) { System.out.println(e); } } }
package jour14; import java.util.Scanner; public class Soru02 { public static void main(String[] args) { //Kullanıcıdan başlangıç ve bitiş değerlerini alın //ve başlangıç değerinden başlayıp bitiş değerinde biten //4 ve 6 ile bölünebilen tüm tamsayıları ekrana yazdırınız. Scanner scan = new Scanner(System.in); System.out.println("Başlangıç değerlerini giriniz"); int bas =scan.nextInt(); System.out.println("Bitis değerlerini giriniz"); int son =scan.nextInt(); int num=bas; do { if(num%12==0) { System.out.println(num); } num++; }while(num<son); scan.close(); } }
package ru.otus.json.writer; import com.google.gson.Gson; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import ru.otus.json.writer.gson.GsonWriter; import ru.otus.json.writer.testobjects.TestPrimitive; import ru.otus.json.writer.testobjects.TestWithArrays; public class TestGson { @Test public void testObjectWithPrimitive(){ Gson gson = new Gson(); var gsonBuilder = new GsonWriter(); var testInstance = new TestPrimitive(); String myGson = gsonBuilder.toGson(testInstance); String targetJson = gson.toJson(testInstance); assertTrue(targetJson.equals(myGson)); } @Test public void testObjectWithArrayAndCollections(){ Gson gson = new Gson(); var gsonBuilder = new GsonWriter(); var testInstance = new TestWithArrays(); testInstance.addStringCollection("Hello "); testInstance.addStringCollection("everybody"); testInstance.addStringCollection("!"); testInstance.addObjettsCollection(null); testInstance.addObjettsCollection(12389); testInstance.addObjettsCollection(3031); testInstance.addObjettsCollection(1918); String myGson = gsonBuilder.toGson(testInstance); String targetJson = gson.toJson(testInstance); assertTrue(targetJson.equals(myGson)); } @Test() public void testNullObject(){ var gsonBuilder = new GsonWriter(); Gson gson = new Gson(); assertEquals(gson.toJson(null), gsonBuilder.toGson(null)); } @Test() public void testPrimitives() { var gson = new Gson(); var gsonBuilder = new GsonWriter(); assertEquals(gson.toJson(123), gsonBuilder.toGson(123)); assertEquals(gson.toJson('\n'), gsonBuilder.toGson('\n')); assertEquals(gson.toJson("abc"), gsonBuilder.toGson("abc")); assertEquals(gson.toJson(true), gsonBuilder.toGson(true)); assertEquals(gson.toJson(false), gsonBuilder.toGson(false)); } }
package com.example.sujith.roomdatabdase_demo; import android.arch.persistence.room.Room; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class AddUserActivity extends AppCompatActivity { EditText idp,namep,emailp; Button addBp; MyAppDatabase myAppDatabase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_user); idp=findViewById(R.id.add_userid); namep=findViewById(R.id.add_username); emailp=findViewById(R.id.add_useremail); addBp=findViewById(R.id.addB); myAppDatabase=Room.databaseBuilder(getApplicationContext() ,MyAppDatabase.class,"userdb").allowMainThreadQueries().build(); addBp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int id=Integer.parseInt(idp.getText().toString()); String username=namep.getText().toString(); String useremail=emailp.getText().toString(); User user=new User(); user.setId(id); user.setName(username); user.setEmail(useremail); myAppDatabase.myDao().addUser(user); Toast.makeText(AddUserActivity.this, "User Added", Toast.LENGTH_SHORT).show(); idp.setText(""); namep.setText(""); emailp.setText(""); } }); } }
package com.gcsw.teamone; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import androidx.annotation.NonNull; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; public class groupDeleter extends Activity { View selfLayout; Button okB, cancelB; String result; ArrayList<String> groupItems; FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference UserGroupRef = database.getReference("UsersGroupInfo"); DatabaseReference GroupRef = database.getReference("grouplist"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_groupdeleter); selfLayout = findViewById(R.id.gDeleter); String MyID = FirstAuthActivity.getMyID(); EditText gnameTxt = (EditText)selfLayout.findViewById(R.id.txtGname); Intent ReceiveIntent = getIntent(); groupItems = ReceiveIntent.getStringArrayListExtra("GroupData"); okB = (Button)selfLayout.findViewById(R.id.btnOK); okB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String gName = gnameTxt.getText().toString(); if(gName.isEmpty()){return;} // 아무것도 입력하지 않으면 중지 for(String groupData : groupItems){ if(groupData.contains(gName)){ String Code = groupData.replace("@Admin_split@" + gName,""); UserGroupRef.child(MyID).child(Code).removeValue(); GroupRef.child(Code).child("members").child(MyID).removeValue(); GroupRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() { @Override public void onComplete(@NonNull @NotNull Task<DataSnapshot> task) { if(!(task.getResult().child(Code).hasChild("members"))){ GroupRef.child(Code).removeValue(); } } }); result = groupData; } } Intent intent = new Intent(getApplicationContext(), FragmentGroupList.class); intent.putExtra("groupInfo", result); setResult(RESULT_OK, intent); finish(); } }); cancelB = (Button)selfLayout.findViewById(R.id.btnCancel); cancelB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_OUTSIDE) return false; return true; } @Override public void onBackPressed() { return; } }
package com.appdear.bdmap; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONStringer; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.util.Log; public class Location { public static String LOCATIONS_URL = "http://www.google.com.hk/loc/json"; public static String currentCity=null; public static String getLocations(Context context) { // generate json request String jr = generateJsonRequest(context); try { DefaultHttpClient client = new DefaultHttpClient(); StringEntity entity = new StringEntity(jr); HttpPost httpost = new HttpPost(LOCATIONS_URL); httpost.setEntity(entity); HttpResponse response = client.execute(httpost); String locationsJSONString = getStringFromHttp(response.getEntity()); // Log.i("info111", locationsJSONString+"=locationsJSONString"); return extractLocationsFromJsonStringForCity(locationsJSONString); } catch (ClientProtocolException e) { // Log.i("info111", e.getMessage()+"=ClientProtocolException"); //e.printStackTrace(); } catch (IOException e) { // Log.i("info111", e.getMessage()+"=IOException"); //e.printStackTrace(); } catch (Exception e) { //e.printStackTrace(); // Log.i("info111", e.getMessage()+"=Exception"); } return null; } private static String extractLocationsFromJsonStringForCity(String jsonString) { String country = ""; String region = ""; String city = ""; String street = ""; String street_number = ""; double latitude = 0.0; double longitude = 0.0; //"accuracy":901.0 double accuracy = 0.0; try { JSONObject jo = new JSONObject(jsonString); JSONObject location = (JSONObject) jo.get("location"); latitude = (Double) location.get("latitude"); longitude = (Double) location.get("longitude"); accuracy = (Double) location.get("accuracy"); JSONObject address = (JSONObject) location.get("address"); country = (String) address.get("country"); region = (String) address.get("region"); city = (String) address.get("city"); street = (String) address.get("street"); street_number = (String) address.get("street_number"); } catch (JSONException e) { //e.printStackTrace(); } currentCity=(city==null||city.equals(""))?null:city; return city; } // 获取所有的网页信息以String 返回 private static String getStringFromHttp(HttpEntity entity) { StringBuffer buffer = new StringBuffer(); try { // 获取输入流 BufferedReader reader = new BufferedReader(new InputStreamReader( entity.getContent())); // 将返回的数据读到buffer中 String temp = null; while ((temp = reader.readLine()) != null) { buffer.append(temp); } } catch (IllegalStateException e) { //e.printStackTrace(); } catch (IOException e) { //e.printStackTrace(); } return buffer.toString(); } private static String generateJsonRequest(Context context) { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); Log.i("info111","generateJsonRequest"); List<NeighboringCellInfo> cellList = manager.getNeighboringCellInfo(); Log.i("info111",cellList+"=cellList"); GsmCellLocation location =null; if (cellList.size() == 0){ CellLocation loction1=manager.getCellLocation(); if(loction1 instanceof GsmCellLocation){ location = (GsmCellLocation)loction1; }else { return null; } if(location==null)return null; } JSONStringer js = new JSONStringer(); try { js.object(); js.key("version").value("1.1.0"); js.key("host").value("maps.google.com.hk"); js.key("home_mobile_country_code").value(460); js.key("home_mobile_network_code").value(0); js.key("radio_type").value("gsm"); js.key("request_address").value(true); js.key("address_language").value("zh_CN"); JSONArray ct = new JSONArray(); if (cellList.size() > 0){ for (NeighboringCellInfo info : cellList) { JSONObject c = new JSONObject(); c.put("cell_id", info.getCid()); c.put("location_area_code", info.getLac()); c.put("mobile_country_code", 460); c.put("mobile_network_code",0); c.put("signal_strength", info.getRssi()); // 获取邻居小区信号强度 ct.put(c); } }else{ JSONObject c = new JSONObject(); c.put("cell_id", location.getCid()); c.put("location_area_code", location.getLac()); c.put("mobile_country_code", 460); c.put("mobile_network_code", 0); // 获取邻居小区信号强度 ct.put(c); } js.key("cell_towers").value(ct); js.endObject(); } catch (JSONException e) { //e.printStackTrace(); return null; } return js.toString().replace("true", "True"); } public static String getWifiLocation(Context context) { WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); mWifiManager.startScan(); // List<ScanResult> lsScanResult = mWifiManager.getScanResults(); List<WifiConfiguration> lsWifiConfiguration = mWifiManager.getConfiguredNetworks(); String str = ""; for(WifiConfiguration config : lsWifiConfiguration) { if(config.status == WifiConfiguration.Status.CURRENT) str += config.SSID + ","; } WifiInfo info = mWifiManager.getConnectionInfo(); String mac = info.getMacAddress(); JSONObject holder = new JSONObject(); JSONArray array = new JSONArray(); JSONObject data = new JSONObject(); try { holder.put("version", "1.1.0"); holder.put("host", "maps.google.com.hk"); holder.put("address_language", "zh_CN"); holder.put("request_address", true); data.put("ssid", info.getSSID()); data.put("mac_address", mac); data.put("signal_strength", 8); data.put("age", 0); array.put(data); holder.put("wifi_towers", array); } catch (JSONException e) { e.printStackTrace(); } DefaultHttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(LOCATIONS_URL); StringEntity stringEntity = null; try { stringEntity = new StringEntity(holder.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpPost.setEntity(stringEntity); HttpResponse httpResponse = null; try { httpResponse = client.execute(httpPost); } catch (ClientProtocolException e) { e.printStackTrace(); // Log.i("info111","ClientProtocolException="+e.getMessage()); } catch (IOException e) { e.printStackTrace(); //Log.i("info111","IOException="+e.getMessage()); } StringBuffer stringBuffer =new StringBuffer(); Log.i("info111","httpResponse="+httpResponse); if(httpResponse!=null){ int state = httpResponse.getStatusLine().getStatusCode(); if (state == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = null; try { is = httpEntity.getContent(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } InputStreamReader isr = new InputStreamReader(is); BufferedReader reader = new BufferedReader(isr); stringBuffer = new StringBuffer(); try { String result = ""; while ((result = reader.readLine()) != null) { stringBuffer.append(result); } } catch (IOException e) { e.printStackTrace(); } } return extractLocationsFromJsonStringForCity(stringBuffer.toString()); } return null; } }
package com.leepc.chat.controller; import com.alibaba.druid.util.StringUtils; import com.leepc.chat.annotation.PassToken; import com.leepc.chat.exception.ClientException; import com.leepc.chat.service.UserService; import com.leepc.chat.util.Response; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; @Slf4j @Controller @RestController @CrossOrigin public class UserController { @Autowired private UserService service; @PostMapping("/login") @ResponseBody @PassToken public Response login(@RequestParam("username") @NotNull String username, @RequestParam("password") @NotNull String password) { Response response = new Response(); String token = service.login(username, password); if (!StringUtils.isEmpty(token)) { Map data = new HashMap(); data.put("token", token); return response.setCode(HttpStatus.OK.value()).setData(data).setMsg("登录成功"); } throw new ClientException("用户名或密码错误"); } @PostMapping("/logout") @ResponseBody @PassToken public Response logout(@RequestHeader("token") @NotNull String token) { service.logout(token); return Response.build().setCode(200).setMsg("退出成功"); } }
import java.util.Scanner; public class CurrencyConversion { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("input amount of money (in USD)"); int rate = scanner.nextInt(); int vnd = rate * 23000; System.out.printf("The amount of money in VND is %d", vnd); } }
package br.com.sdad; public class Alertas { public enum TipoAlerta { EMAIL("email"), SMS("sms"), TELEGRAM("telegram"); private String tipoAlerta; TipoAlerta(String tipoAlerta){ this.tipoAlerta = tipoAlerta; } public String getTipoAlerta() { return tipoAlerta; } } }
package com.rbgt.mb.respons; /** * @project_name: mb * @package_name: com.rbgt.mb.respons * @name: ResponseCode * @author: 俞春旺 * @date: 2020/4/5 10:50 * @day_name_full: 星期日 * @remark: 返回状态码 **/ public enum ResponseCode { /** * 成功返回的状态码 */ SUCCESS(10000, "success"), /** * 资源不存在的状态码 */ RESOURCES_NOT_EXIST(10001, "资源不存在"), /** * 所有无法识别的异常默认的返回状态码 */ SERVICE_ERROR(50000, "服务器异常"); /** * 状态码 */ private int code; /** * 返回信息 */ private String msg; ResponseCode(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } }
package com.shopify.admin.popup; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import com.shopify.admin.AdminData; import com.shopify.admin.price.PriceController; import com.shopify.admin.price.PriceData; import com.shopify.admin.price.PriceService; import com.shopify.common.SpConstants; import com.shopify.mapper.PriceMapper; /** * 요금 맵핑 관리 팝업 컨트롤러 * */ @Controller public class PricePopupController { private Logger LOGGER = LoggerFactory.getLogger(PricePopupController.class); @Autowired private PriceMapper priceMapper; @Autowired private PriceService priceService; /** * 요금매핑관리 > 공시가격 등록 Popup * @return */ @GetMapping(value = "/admin/popup/feesPriceNewPop") public String feesPriceNewPop(Model model,HttpSession sess, @ModelAttribute PriceData price) { // AdminData adminData = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); AdminData sd = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); String code = price.getCode(); String shipCompany = price.getShipCompany(); model.addAttribute("shipCompany", shipCompany); model.addAttribute("code", code); return "/admin/popup/popFeesPriceNew"; } /** * 요금매핑관리 > 할인가격 등록 Popup * @return */ @GetMapping(value = "/admin/popup/salePriceNewPop") public String salePriceNewPop(Model model,HttpSession sess, @ModelAttribute PriceData price) { // AdminData adminData = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); AdminData sd = (AdminData) sess.getAttribute(SpConstants.ADMIN_SESSION_KEY); String code = price.getCode(); String shipCompany = price.getShipCompany(); model.addAttribute("shipCompany", shipCompany); model.addAttribute("code", code); return "/admin/popup/popSalePriceNew"; } }
package chainofresponsibility.design.pattern.example1; public class CsvParser extends Parser { @Override public void parse(String fileName) { if ( canHandleFile(fileName, ".csv")){ System.out.println(fileName+" parsed by CSV Parser"); } else{ super.parse(fileName); } } }
package com.application.model.tax; import java.text.NumberFormat; import java.util.Locale; /** * This class is percentage representation. * Anywhere in project if percentage need to be described this class can be used. */ public final class Percent { public static final Percent TEN_PERCENT = new Percent(10); public static final Percent TWENTY_PERCENT = new Percent(20); public static final Percent ZERO_PERCENT = new Percent(0); private static final double ONE_HUNDRED_PERCENT_VALUE = 100.0; public static final Percent HUNDRED_PERCENT = new Percent(ONE_HUNDRED_PERCENT_VALUE); private final double value; /** * Make a new percentage * * @param value value between 0 and 100 inclusive */ public Percent(final double value) { if (value < 0.0 || value > ONE_HUNDRED_PERCENT_VALUE) { throw new IllegalArgumentException("Percent value must be between 0 and 100 but is " + value); } this.value = value; } public double getValue() { return value; } @Override public String toString() { return NumberFormat.getPercentInstance(Locale.getDefault()).format(value / ONE_HUNDRED_PERCENT_VALUE); } }
package org.mybatis.spring.cache; /** * 缓存更新上下文,指定需要更新的地方,方便php java缓存同步 * @author lindezhi * 2015年12月10日 上午1:40:36 */ public class RedisCacheContext { private static ThreadLocal<Integer> update = new ThreadLocal<Integer>(); private static ThreadLocal<Integer> select = new ThreadLocal<Integer>(); public static int getOp(){ Integer op = update.get(); if(op!=null){ return op; }else{ op = UpdateOp.UPDATE_CACHE_AND_DB; update.set(op); } return op; } public static void setOp(int op){ update.set(op); } public static void clear(){ update.remove(); select.remove(); } public static void setSelectOp(int op){ select.set(op); } public static int getSelectOp(){ Integer op = select.get(); if(op!=null){ return op; }else{ op = SelectOp.SELECT_CACHE_OR_DB; select.set(op); } return op; } }
package org.got5.tapestry5.roo; public class TapestryUtils { public final static String createEmptyTemplateContent() { StringBuffer buffer = new StringBuffer(); buffer.append("<html t:type=\"layout\" xmlns:t=\"http://tapestry.apache.org/schema/tapestry_5_1_0.xsd\" " + " xmlns:p=\"tapestry:parameter\">"); buffer.append("</html>"); return buffer.toString(); } }
package com.nxtlife.mgs.enums; public enum ApprovalStatus { PENDING, VERIFIED, REJECTED ,FORWARDED; }
package fr.xebia.xkeakka.transcoder; import java.io.IOException; public class LameTranscoder extends Transcoder { @Override public void transcode(FileFormat input) { try { Process p = Runtime.getRuntime().exec(buildCommand(input)); p.waitFor(); } catch (Exception e) { throw new TranscodeException(e); } } private String buildCommand(FileFormat input) { return "./lame.sh " + input.master.getAbsolutePath() + " " + input.encodedFilePath; } }
/* * created 02.08.2005 by sell * * $Id: Messages.java 664 2007-09-28 17:28:39Z cse $ */ package com.byterefinery.rmbench.actions; import org.eclipse.osgi.util.NLS; /** * translatable strings for dialogs * * @author sell */ public class Messages extends NLS { private static final String BUNDLE_NAME = "com.byterefinery.rmbench.actions.Messages"; //$NON-NLS-1$ static { NLS.initializeMessages(BUNDLE_NAME, Messages.class); } public static String Layout_text; public static String Layout_description; public static String Delete_Label; public static String Delete_Tooltip; public static String Remove_Label; public static String Remove_Tooltip; public static String Delete_GroupLabel; public static String Remove_GroupLabel; public static String Print_Label; public static String Print_Tooltip; public static String ForeignKey_Label; public static String ForeignKey_Description; public static String TableType_None; public static String TablesDiagram_Label; public static String TablesDiagram_Description; public static String TableDetails_Label; public static String TableDetails_Description; public static String Cut_Label; public static String Copy_Label; public static String Paste_Label; public static String ToggleGrid_Label; public static String DiagramMenu_Label; public static String TableTypesSubmenu_ActionLabelText; public static String PageOutlineAction_Title; public static String PrinterSetupAction_Title; public static String Export_Label; public static String Export_Tooltip; public static String DiagramExportAction_Title; public static String AddStubbedTablesAction_Text; public static String No_PrimaryKey_matches; }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.swing; /** * Enumerates the different edit modes. * * @author Miquel Sas */ public enum EditMode { /** * Mode insert. */ Insert, /** * Mode update. */ Update, /** * Mode delete. */ Delete, /** * Mode read only. */ ReadOnly, /** * Mode filter. */ Filter, /** * Mode with no restriction. */ NoRestriction; }
/* Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.engedu.bstguesser; import android.graphics.Canvas; import java.util.ArrayList; import java.util.Collections; import java.util.jar.Pack200; public class BinarySearchTree { private TreeNode root = null; public BinarySearchTree() { } public void insert(int value) { if (root == null) { root = new TreeNode(value); return; } else { root.insert(value); } } public void positionNodes(int width) { if (root != null) root.positionSelf(0, width, 0); } public void draw(Canvas c) { root.draw(c); } public int click(float x, float y, int target) { return root.click(x, y, target); } private TreeNode search(int value) { TreeNode current = root; /** ** ** YOUR CODE GOES HERE ** **/ while(current.getValue()!=value) { if(value<current.getValue()) { current=current.left; } else{ current=current.right; } } return current; } public void invalidateNode(int targetValue) { TreeNode target = search(targetValue); target.invalidate(); } }
package com.emp.friskyplayer.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.KeyEvent; import com.emp.friskyplayer.utils.ServiceActionConstants; /** * Manages lock screen media button actions * @author empollica * */ public class MediaButtonReceiver extends BroadcastReceiver { final static String TAG = "MediaButton"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) { Log.d(TAG,"Media button pressed"); KeyEvent keyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT); if (keyEvent.getAction() != KeyEvent.ACTION_DOWN) return; switch (keyEvent.getKeyCode()) { case KeyEvent.KEYCODE_HEADSETHOOK: Log.d(TAG,"KEYCODE_HEADSETHOOK"); context.startService(new Intent(ServiceActionConstants.ACTION_TOGGLE_PLAYBACK)); break; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: Log.d(TAG,"KEYCODE_MEDIA_PLAY_PAUSE"); // send an intent to FriskyService to telling it to stop the audio context.startService(new Intent(ServiceActionConstants.ACTION_STOP)); break; } } } }
package Algorithm; //给定一个整数数组,其中第 i 个元素代表了第 i 天的股票价格 。​ // 设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票): // 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 // 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。 //[][0]拿着股票 [][1]没拿,可以买 [][2]没拿,不可以买 public class a309 { public int maxProfit(int[] prices) { if (prices.length==0)return 0; int[][] dp=new int[prices.length][3]; dp[0][0]=-prices[0]; for (int i=1;i<prices.length;i++){ dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]-prices[i]); dp[i][1]=Math.max(dp[i-1][2],dp[i-1][1]); dp[i][2]=dp[i-1][0]+prices[i]; } return Math.max(dp[prices.length-1][1],dp[prices.length-1][2]); } }
package x.format; import org.junit.Test; import x.java.JavaRulePath; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; public class RulePathTest { @Test public void matchesShouldMatch() { // given RulePath rulePath = new RulePath(); rulePath.enter("a"); rulePath.enter("b"); rulePath.enter("c"); // when / then assertThat(rulePath.matches("a", "c"), is(true)); assertThat(rulePath.matches("b", "c"), is(true)); assertThat(rulePath.matches("c", "a"), is(false)); assertThat(rulePath.matches("d"), is(false)); assertThat(rulePath.matches("a", "a"), is(false)); } }
package ej6; public class PruebaEntero { public static void main(String[] args) { // TODO Auto-generated method stub Entero e = new Entero(5); System.out.println("El numero ingresado es: " + e.getNumero()); System.out.println("El cuadrado de " + e.getNumero() + " es: " + e.cuadrado()); } }
package view.guicomponents.guiconsole; /** * Contains the last user input of a GUI console input text field. * * @author Andreas Fender */ public class ConsoleUserInput { private String input; private boolean awaiting; public ConsoleUserInput() { awaiting = false; } /** * Returns the recent user input. */ public String getInput() { return input; } /** * Sets the recent user input. */ public void setInput(String input) { this.input = input; } /** * Sets the wait state of this instance. */ public void setAwaiting(boolean awaiting) { this.awaiting = awaiting; } /** * Tells whether or not user input is awaited. */ public boolean isWaiting() { return awaiting; } }
package com.cachecats.domin.shop.model; import java.io.Serializable; import java.util.List; /** * Created by solo on 2018/1/18. * 商店对应的 model */ public class ShopModel implements Serializable{ private String id; private String name; private String logo; private String address; private String tel; private float serviceScore; private float perConsume; private String introduction; private String recommendDishes; private List<ShopGroupInfoModel> groupInfos; @Override public String toString() { return "ShopModel{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", logo='" + logo + '\'' + ", address='" + address + '\'' + ", tel='" + tel + '\'' + ", serviceScore=" + serviceScore + ", perConsume=" + perConsume + ", introduction='" + introduction + '\'' + ", recommendDishes='" + recommendDishes + '\'' + ", groupInfos=" + groupInfos + '}'; } public List<ShopGroupInfoModel> getGroupInfos() { return groupInfos; } public void setGroupInfos(List<ShopGroupInfoModel> groupInfos) { this.groupInfos = groupInfos; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public float getServiceScore() { return serviceScore; } public void setServiceScore(float serviceScore) { this.serviceScore = serviceScore; } public float getPerConsume() { return perConsume; } public void setPerConsume(float perConsume) { this.perConsume = perConsume; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getRecommendDishes() { return recommendDishes; } public void setRecommendDishes(String recommendDishes) { this.recommendDishes = recommendDishes; } }
package com.example.wsec.controller; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.print.attribute.standard.PagesPerMinute; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.annotation.PostMapping; import com.example.wsec.model.Message; import com.example.wsec.model.Page; import com.example.wsec.model.Role; import com.example.wsec.model.User; import com.example.wsec.service.UserService; import org.apache.logging.log4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @Controller @SessionAttributes({"user_role","user","user_pages"}) public class HomeController { @Autowired private UserService userService; @RequestMapping("/") public String showHome(ModelMap model, HttpSession session) { updateSession(null,null,Arrays.asList(new Page("Home"),new Page("About")), session); return "home"; } private void updateSession(User user, String userRole, List<Page> pages, HttpSession session) { session.setAttribute("user",user); session.setAttribute("user_role", userRole); session.setAttribute("user_pages", pages); } private void updateModel(User user, String userRole, List<Page> pages, ModelMap model) { model.addAttribute("user",user); model.addAttribute("user_role", userRole); model.addAttribute("user_pages", pages); } @RequestMapping("/showLogin") public String showLogin() { return "showLogin"; } @RequestMapping("/showRegistrationForm") public String showRegistrationForm() { return "showRegistrationForm"; } @RequestMapping (value = "/uu", method = RequestMethod.POST) public String doLoginUser(HttpServletRequest req, HttpServletResponse res, ModelMap model, HttpSession session) { System.out.println("un in post "+req.getParameter("userName")); System.out.println("pw in post "+req.getParameter("password")); User u=userService.findByUserName(req.getParameter("userName"),req.getParameter("password")); List<Role> roles=new ArrayList<Role>(); roles.addAll(u.getRole()); String role=roles.get(0).getRoleName(); if(u!=null) { Set<Page> pages=new HashSet<Page>(); for(Role r:u.getRole()) { pages.addAll(r.getPages()); } List<Page> pageList=new ArrayList<Page>(); pageList.addAll(pages); updateSession(u,role.toLowerCase(),pageList, session); updateModel(u,role.toLowerCase(),pageList, model); if(role.equals("USER")) return "redirect:user/home"; else return "redirect:admin/home"; } updateSession(null,null,Arrays.asList(new Page("Home"),new Page("About")), session); return "redirect:showLogin"; } @RequestMapping("/logout") public String userLogout(ModelMap model, HttpSession session) { updateSession(null,null,Arrays.asList(new Page("Home"),new Page("About")), session); model.clear(); return "home"; } @RequestMapping (value = "/doRegister", method = RequestMethod.POST) public String doRegister(HttpServletRequest req, HttpServletResponse res, ModelMap model, HttpSession session) { System.out.println("un in post "+req.getParameter("userName")); System.out.println("pw in post "+req.getParameter("password")); User u=userService.saveUser(req.getParameter("userName"),req.getParameter("password"), req.getParameter("confirmPassword")); System.out.println("user ++++++++++++++++"+u.getUserName()+" "+u.getRole()); List<Role> roles=new ArrayList<Role>(); roles.addAll(u.getRole()); String role=roles.get(0).getRoleName(); if(u!=null) { Set<Page> pages=new HashSet<Page>(); for(Role r:u.getRole()) { pages.addAll(r.getPages()); } List<Page> pageList=new ArrayList<Page>(); pageList.addAll(pages); updateSession(u,role.toLowerCase(),pageList, session); updateModel(u,role.toLowerCase(),pageList, model); if(role.equals("USER")) return "redirect:user/home"; else return "redirect:admin/home"; } updateSession(null,null,Arrays.asList(new Page("Home"),new Page("About")), session); return "redirect:showLogin"; } }
package com.tencent.mm.plugin.appbrand.menu; import android.content.Context; import com.tencent.mm.plugin.appbrand.menu.a.a; import com.tencent.mm.plugin.appbrand.page.p; import com.tencent.mm.plugin.appbrand.s.j; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.ui.base.l; public final class b extends a { b() { super(l.gjv - 1); } public final void a(Context context, p pVar, l lVar, String str) { if (!pVar.fdO.aaq() && pVar.fdO.fcz.gmM) { lVar.e(this.gjO, context.getString(j.app_brand_back_to_home)); } } public final void a(Context context, p pVar, String str, k kVar) { pVar.fdO.fcz.V(pVar.fdO.fcv.adU(), true); if (pVar.gns != null) { com.tencent.mm.plugin.appbrand.report.a.a(str, pVar.getURL(), 20, "", bi.VE(), 1, 0); } } }
package com.cse308.sbuify.playlist; import com.cse308.sbuify.customer.FollowedPlaylist; import com.cse308.sbuify.customer.FollowedPlaylistRepository; import com.cse308.sbuify.image.StorageService; import com.cse308.sbuify.image.Image; import com.cse308.sbuify.security.AuthFacade; import com.cse308.sbuify.security.SecurityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @Controller @RequestMapping(path = "/api/playlist-folders") public class PlaylistFolderController { @Autowired private AuthFacade authFacade; @Autowired private PlaylistFolderRepository folderRepo; @Autowired private FollowedPlaylistRepository followedPlaylistRepo; @Autowired private StorageService storageService; @Autowired private PlaylistRepository playlistRepo; /** * Create a playlist folder. * @param folder The folder to create. * @return a 201 response containing the saved playlist folder in the body. */ @PostMapping public ResponseEntity<?> create(@RequestBody PlaylistFolder folder) { folder.setOwner(authFacade.getCurrentUser()); PlaylistFolder saved = folderRepo.save(folder); return new ResponseEntity<>(saved, HttpStatus.CREATED); } /** * Update a playlist folder. * @param id Folder ID. * @param updated Updated playlist folder. * @return an 200 response containing the updated folder on success, otherwise a 404. */ @PatchMapping(path = "/{id}") public ResponseEntity<?> update(@PathVariable Integer id, @RequestBody PlaylistFolder updated) { Optional<PlaylistFolder> optionalFolder = folderRepo.findById(id); if (!optionalFolder.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } PlaylistFolder folder = optionalFolder.get(); if (!SecurityUtils.userCanEdit(folder)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } folder.setName(updated.getName()); folder = folderRepo.save(folder); return new ResponseEntity<>(folder, HttpStatus.OK); } /** * Delete a playlist folder. * @param id Folder ID. * @return an empty 200 response on success, otherwise a 404 if the folder ID is invalid or a 403 * if the current user can't edit the folder. */ @DeleteMapping(path = "/{id}") @Transactional public ResponseEntity<?> delete(@PathVariable Integer id) { Optional<PlaylistFolder> optionalFolder = folderRepo.findById(id); if (!optionalFolder.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } PlaylistFolder folder = optionalFolder.get(); if (!SecurityUtils.userCanEdit(folder)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } List<FollowedPlaylist> folderPlaylists = followedPlaylistRepo.findByParent(folder); for (FollowedPlaylist followedPlaylist: folderPlaylists) { Playlist playlist = followedPlaylist.getPlaylist(); if (!SecurityUtils.userCanEdit(playlist)) { // playlist isn't user owned -- don't delete it continue; } if (playlist.getImage() != null) { storageService.delete((Image) playlist.getImage()); } playlistRepo.delete(playlist); } followedPlaylistRepo.deleteAllByParent(folder); folderRepo.delete(folder); return new ResponseEntity<>(HttpStatus.OK); } /** * Get the playlists in a folder. * @param id Folder ID. * @return a 200 response containing a list of playlists on success, otherwise a 404 if the folder ID * is invalid or a 403 if the folder is not owned by the current user. */ @GetMapping(path = "/{id}") public ResponseEntity<?> read(@PathVariable Integer id) { Optional<PlaylistFolder> optionalFolder = folderRepo.findById(id); if (!optionalFolder.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } PlaylistFolder folder = optionalFolder.get(); if (!SecurityUtils.userCanEdit(folder)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } List<FollowedPlaylist> playlists = followedPlaylistRepo.findByParent(folder); return new ResponseEntity<>(playlists, HttpStatus.OK); } }
package com.example.patrick.rccar.listener; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorListener; import com.example.patrick.rccar.Steuerung; public class LenkungsListener implements SensorEventListener { private final Steuerung steuerung; public LenkungsListener(Steuerung steuerung) { this.steuerung = steuerung; } @Override public void onSensorChanged(SensorEvent event) { steuerung.setLenkText(event.values[1]); steuerung.sendMessageToBT(String.format("y%d", convertToHundretBaseInt(event.values[1]))); } private Integer convertToHundretBaseInt(float value) { return Float.valueOf(value*10).intValue(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
public class Round { public Round(Dealer dealer) { dealer.setCheckRoundCount(dealer.getCheckRoundCount()+1); } //region boolean _checkRoundType private boolean _RoundType; public boolean getCheckRoundType() { return _RoundType; } public void setCheckRoundType(boolean checkRoundType) { _RoundType = checkRoundType; } public void roundInformation(Player player1, Player player2, Dealer dealer) { System.out.print("ROUND " + dealer.getCheckRoundCount()); System.out.println("\t\t\tPlayer1\tPlayer2"); System.out.println("-----------------------------------------"); System.out.printf("ID :\t\t\t"); System.out.printf(player1.getId()); System.out.printf("\t\t"); System.out.println(player2.getId()); System.out.print("RestMoney :\t\t"); System.out.print(player1.getPlayerMoney()); System.out.printf("\t\t"); System.out.println(player2.getPlayerMoney()); System.out.print("SeletedCard :\t"); System.out.print(player1.getFirstCard().getNo()); if (player1.getFirstCard().getIsGwang()) System.out.print("광 "); else System.out.print(" "); System.out.print(player1.getSecondCard().getNo()); if (player1.getSecondCard().getIsGwang()) System.out.print("광 "); else System.out.print(" "); System.out.print("\t"); System.out.print(player2.getFirstCard().getNo()); if (player2.getFirstCard().getIsGwang()) System.out.print("광 "); else System.out.print(" "); System.out.print(" "); System.out.print(player2.getSecondCard().getNo()); if (player2.getSecondCard().getIsGwang()) System.out.print("광 "); else System.out.print(" "); System.out.println(""); } //endregion }
package com.dayuanit.shop.dto; import java.util.List; public class OrderDetailDTO { private Integer id; private Integer status; private String userRealName; private String createTime; private Integer payChannel; private String totalPrice; private String dtaAddress; private String provinceName; private String cityName; private String disbursements; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getUserRealName() { return userRealName; } public void setUserRealName(String userRealName) { this.userRealName = userRealName; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public Integer getPayChannel() { return payChannel; } public void setPayChannel(Integer payChannel) { this.payChannel = payChannel; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public String getDtaAddress() { return dtaAddress; } public void setDtaAddress(String dtaAddress) { this.dtaAddress = dtaAddress; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getDeliveryTime() { return deliveryTime; } public void setDeliveryTime(String deliveryTime) { this.deliveryTime = deliveryTime; } public String getFreight() { return freight; } public void setFreight(String freight) { this.freight = freight; } public List<OrderGoods> getOrderGoods() { return orderGoods; } public void setOrderGoods(List<OrderGoods> orderGoods) { this.orderGoods = orderGoods; } public String getDisbursements() { return disbursements; } public void setDisbursements(String disbursements) { this.disbursements = disbursements; } private String areaName; private String phone; private String deliveryTime; private String freight; private List<OrderGoods> orderGoods; public static class OrderGoods { private String goodsName; private String price; private Integer goodsAccount; public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public Integer getGoodsAccount() { return goodsAccount; } public void setGoodsAccount(Integer goodsAccount) { this.goodsAccount = goodsAccount; } } }
/* * The MIT License * * Copyright 2018 Edson Passos <edsonpassosjr@outlook.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package me.roinujnosde.wantednotification.commands; import java.util.Arrays; import java.util.List; import java.util.Objects; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import me.roinujnosde.wantednotification.WantedNotification; /** * * @author Edson Passos <edsonpassosjr@outlook.com> */ public class WNCommandExecutor implements CommandExecutor, TabCompleter { private final WantedNotification plugin; public WNCommandExecutor(WantedNotification plugin) { this.plugin = Objects.requireNonNull(plugin); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length >= 1) { try { String commandName = new Character(args[0].charAt(0)).toString().toUpperCase() + args[0].substring(1) + "Command"; @SuppressWarnings("unchecked") Class<WNCommand> clazz = (Class<WNCommand>) Class .forName("me.roinujnosde.wantednotification.commands." + commandName); WNCommand cmd = clazz.getConstructor(WantedNotification.class, CommandSender.class, String[].class) .newInstance(plugin, sender, args); return cmd.run(); } catch (Exception ignored) { } } return false; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if (args.length == 1) { //TODO: Testar return Arrays.asList("add", "help", "remove", "list"); } return null; } }
package com.tencent.mm.plugin.emoji.ui; import android.content.Intent; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.R; import com.tencent.mm.plugin.emoji.model.i; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ao; import com.tencent.mm.storage.emotion.EmojiGroupInfo; import com.tencent.mm.ui.base.h; import java.util.ArrayList; import java.util.Iterator; import java.util.List; class EmojiMineUI$2 implements OnMenuItemClickListener { final /* synthetic */ EmojiMineUI imi; EmojiMineUI$2(EmojiMineUI emojiMineUI) { this.imi = emojiMineUI; } public final boolean onMenuItemClick(MenuItem menuItem) { ArrayList cnt = i.aEA().igy.cnt(); List arrayList = new ArrayList(); Iterator it = cnt.iterator(); while (it.hasNext()) { EmojiGroupInfo emojiGroupInfo = (EmojiGroupInfo) it.next(); if (emojiGroupInfo.field_type != EmojiGroupInfo.TYPE_CUSTOM) { arrayList.add(emojiGroupInfo); } } if (arrayList.size() <= 1) { h.i(this.imi.mController.tml, R.l.emoji_cant_sort_tip, R.l.app_tip); } else if (ao.isConnected(ad.getContext())) { Intent intent = new Intent(); intent.setClass(this.imi, EmojiSortUI.class); this.imi.startActivity(intent); } else { EmojiMineUI.a(this.imi); } return true; } }
package myaop.java; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ExeTimeCalculator implements Calculator{ private Calculator delegate; static final Logger logger = LogManager.getLogger(App.class); public ExeTimeCalculator(Calculator cal){ delegate = cal; } public long factorial(long num) { long start = System.nanoTime(); long result = delegate.factorial(num); long end = System.nanoTime(); logger.info("실행시간 : " + (end-start)); return result; } }
package com.espendwise.manta.web.util; import com.espendwise.manta.util.alert.MessageType; import com.espendwise.manta.util.arguments.TypedArgument; public class WebMessage extends ActionMessage { public WebMessage(String key, TypedArgument[] arguments, String defaultMessage) { super(MessageType.MESSAGE, key, arguments, defaultMessage); } public WebMessage(String key, TypedArgument[] arguments) { super(MessageType.MESSAGE, key, arguments, null); } public WebMessage(String key) { super(MessageType.MESSAGE, key, null, null); } }
package com.mydemo.webtest.pages; import com.microsoft.playwright.Page; import com.mydemo.webtest.browser.BrowserConfig; public class LoginPage { Page page = BrowserConfig.localPage; private String txtUsername = "#username"; private String txtPassword = "#password"; private String btnSignIn = "button[data-test='signin-submit']"; private String linkSignUp = "a[data-test='signup']"; public HomePage logIn(String userName, String password) { page.fill(txtUsername, userName); page.fill(txtPassword, password); page.click(btnSignIn); return new HomePage(); } public SignUpPage openSignUpPage() { //add this fill just_placeholder to bypass the "broken" username null check // when clicking the Sign Up link page.fill(txtUsername, "just_placeholder"); page.click(linkSignUp); return new SignUpPage(); } }
package kr.ko.nexmain.server.MissingU.msgbox.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import kr.ko.nexmain.server.MissingU.common.model.CommReqVO; import kr.ko.nexmain.server.MissingU.msgbox.model.LnkMsgboxMsgVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgBoxConversSendVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgBoxConversVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgBoxVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgListReqVO; import kr.ko.nexmain.server.MissingU.msgbox.model.MsgVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; import org.springframework.stereotype.Repository; import com.ibatis.sqlmap.client.SqlMapClient; @Repository public class MsgBoxDaoImpl extends SqlMapClientDaoSupport implements MsgBoxDao{ public MsgBoxDaoImpl(){ super(); } @Autowired public MsgBoxDaoImpl(SqlMapClient sqlMapClient) { super(); setSqlMapClient(sqlMapClient); } ///----------------------------------------------------------------------------------------------------------------------------------------/// /// 새로 개발되는 쪽지함(시작) ///----------------------------------------------------------------------------------------------------------------------------------------/// /** 쪽지 리스트 조회 */ public List<Map<String,Object>> selectMessageBoxListByMemberId(Integer memberId) { return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("MsgBox.selectMessageBoxListByMemberId", memberId); } /** 쪽지 대화 리스트 조회 */ public List<Map<String,Object>> selectMessageBoxConversationByMemberId(MsgBoxConversVO inputVO) { return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("MsgBox.selectMessageBoxConversationByMemberId", inputVO); } /** 쪽지 모두 읽음 처리 */ public int updateMessageBoxReadAll(MsgBoxConversVO inputVO) { return getSqlMapClientTemplate().update("MsgBox.updateMessageBoxReadAll", inputVO); } /** 쪽지 발송 */ public long insertMessageBoxMsg(MsgBoxConversSendVO inputVO) { return (Long)getSqlMapClientTemplate().insert("MsgBox.insertMessageBoxMsg", inputVO); } /** 쪽지 발송 */ public long insertMessageBoxMsgEcho(MsgBoxConversSendVO inputVO) { return (Long)getSqlMapClientTemplate().insert("MsgBox.insertMessageBoxMsgEcho", inputVO); } /** 쪽지 삭제 */ public int deleteConversMsg(MsgBoxConversVO inputVO) { return getSqlMapClientTemplate().update("MsgBox.updateAfterMessageBoxMsgDelete", inputVO); } public Map<String, Object> selectMsgConvers(MsgBoxConversSendVO msgBoxConversSendVO) { return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("MsgBox.selectMessageBoxConversByMsgId", msgBoxConversSendVO); } ///----------------------------------------------------------------------------------------------------------------------------------------/// /// 새로 개발되는 쪽지함(끝) ///----------------------------------------------------------------------------------------------------------------------------------------/// /** 쪽지함 리스트 조회 */ public List<Map<String,Object>> selectMsgBoxListByMemberId(Integer memberId) { return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("MsgBox.selectMsgBoxListByMemberId", memberId); } /** 쪽지함 조회 */ public Map<String,Object> selectMsgboxByMemberIdAndSenderId(MsgBoxVO inputVO) { return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("MsgBox.selectMsgboxByMemberIdAndSenderId", inputVO); } /** 쪽지 리스트 조회 */ public List<Map<String,Object>> selectMsgListByMsgboxId(MsgListReqVO inputVO) { return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("MsgBox.selectMsgListByMsgboxId", inputVO); } /** 채팅방 생성 */ public Long insertIntoMsgbox(MsgBoxVO inputVO) { return (Long)getSqlMapClientTemplate().insert("MsgBox.insertIntoMsgbox", inputVO); } /** 메세지 Insert */ public Long insertIntoMsg(MsgVO inputVO) { return (Long)getSqlMapClientTemplate().insert("MsgBox.insertIntoMsg", inputVO); } /** 링크_쪽지함_쪽지 Insert*/ public int insertIntoLnkMsgboxMsg(LnkMsgboxMsgVO inputVO) { return getSqlMapClientTemplate().update("MsgBox.insertIntoLnkMsgboxMsg", inputVO); } /** 링크_쪽지함_쪽지 Delete*/ public int deleteLnkMsgboxMsgByMsgId(LnkMsgboxMsgVO inputVO) { return getSqlMapClientTemplate().update("MsgBox.deleteLnkMsgboxMsgByMsgId", inputVO); } /** 쪽지함 Status 업데이트*/ public int updateMsgboxStatus(MsgBoxVO inputVO) { return getSqlMapClientTemplate().update("MsgBox.updateMsgboxStatus", inputVO); } /** 쪽지 읽기여부 업데이트*/ public int updateMsgAsRead(Long msgboxId) { return getSqlMapClientTemplate().update("MsgBox.updateMsgAsRead", msgboxId); } /** 쪽지 읽기여부 업데이트*/ public int updateMsgAsReadByMsgId(Long msgId) { return getSqlMapClientTemplate().update("MsgBox.updateMsgAsReadByMsgId", msgId); } /** 쪽지 읽기여부 업데이트*/ public int updateMsgAsReadYNToogleByMsgId(Long msgId) { return getSqlMapClientTemplate().update("MsgBox.updateMsgAsReadYNToogleByMsgId", msgId); } /** 미확인 쪽지 수 조회*/ public Integer selectUnreadMsgCntByMemberId(Integer memberId) { return (Integer) getSqlMapClientTemplate().queryForObject("MsgBox.selectUnreadMsgCntByMemberId", memberId); } /** 내 쪽지 리스트 조회 */ public List<Map<String,Object>> selectMyMsgList(CommReqVO inputVO) { return (List<Map<String,Object>>) getSqlMapClientTemplate().queryForList("MsgBox.selectMyMsgList", inputVO); } /** 쪽지 조회 */ public Map<String,Object> selectMsgByMsgId(Long msgId) { return (Map<String,Object>) getSqlMapClientTemplate().queryForObject("MsgBox.selectMsgByMsgId", msgId); } /** 쪽지확인 여부 조회 */ public Integer selectUnreadMsgCntByMsgId(Long msgId) { return (Integer) getSqlMapClientTemplate().queryForObject("MsgBox.selectUnreadMsgCntByMsgId", msgId); } }
package de.dzmitry_lamaka.lesaratesttask.network.data; import android.support.annotation.NonNull; import com.google.gson.annotations.SerializedName; import java.util.List; public class Products { @NonNull private List<Product> products; @SerializedName("number_products") private int numberProducts; @SerializedName("number_pages") private int numberPages; @SerializedName("current_page") private int currentPage; @NonNull public List<Product> getProducts() { return products; } public int getNumberProducts() { return numberProducts; } public int getNumberPages() { return numberPages; } public int getCurrentPage() { return currentPage; } }
package com.example.remotestarvideonew; import android.os.Handler; import android.os.Looper; import androidx.lifecycle.Observer; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.gson.Gson; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; @RunWith(AndroidJUnit4.class) public class ViewModelTest { @Mock Call<VideoResponse> callResponse; @Mock ApiService apiService; @Mock Observer<VideoResponse> dataObserver; @Mock Observer<Boolean> apiStatusObserver; private RemoteStarViewModel viewModel; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); viewModel = new RemoteStarViewModel(apiService); } @Test public void testFetchVideoData_whenReturnData(){ //Assemble Call<VideoResponse> mockedCall = (new ApiServiceMock()).getVideos(Constants.API_KEY,null); doReturn(callResponse).when(apiService).getVideos(Constants.API_KEY,Constants.NO_CACHHE); Mockito.doAnswer(new Answer() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Callback<VideoResponse> callback = invocation.getArgument(0); String response = TestHelper.getJson(Constants.DUMMY_JSON); callback.onResponse(mockedCall, Response.success(new Gson().fromJson(response, VideoResponse.class))); return null; } }).when(callResponse).enqueue(any(Callback.class)); //Act (new Handler(Looper.getMainLooper())).post(new Runnable() { @Override public void run() { viewModel.getVideos().observeForever(dataObserver); } }); (new Handler(Looper.getMainLooper())).post(new Runnable() { @Override public void run() { viewModel.getApiStatus().observeForever(apiStatusObserver); } }); viewModel.fetchVideos(Constants.NO_CACHHE); //Verify VideoResponse finalData = (new Gson()).fromJson(TestHelper.getJson(Constants.DUMMY_JSON),VideoResponse.class); verify(apiStatusObserver).onChanged(true); verify(dataObserver).onChanged(finalData); } @Test public void testFetchVideoData_whenReturnFailed(){ //Assemble Call<VideoResponse> mockedCall = (new ApiServiceMock()).getVideos(Constants.API_KEY,null); doReturn(callResponse).when(apiService).getVideos(Constants.API_KEY,Constants.NO_CACHHE); Mockito.doAnswer(new Answer() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Callback<VideoResponse> callback = invocation.getArgument(0); callback.onFailure(mockedCall, new Exception("Fetch Failed")); return null; } }).when(callResponse).enqueue(any(Callback.class)); (new Handler(Looper.getMainLooper())).post(new Runnable() { @Override public void run() { viewModel.getApiStatus().observeForever(apiStatusObserver); } }); viewModel.fetchVideos(Constants.NO_CACHHE); verify(apiStatusObserver).onChanged(false); } }