blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
21d203d419fdd42f3cdf586723ff10aea2d18ec5
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_0966c2a29073a975939d115b5ad0d0fbc4e1e122/UserManagementController/2_0966c2a29073a975939d115b5ad0d0fbc4e1e122_UserManagementController_s.java
UTF-8
2,841
1.976563
2
[]
no_license
package eu.europeana.portal2.web.controllers.user; import java.util.Locale; import java.util.logging.Logger; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import eu.europeana.corelib.db.service.UserService; import eu.europeana.corelib.definitions.db.entity.relational.User; import eu.europeana.portal2.services.Configuration; import eu.europeana.portal2.web.presentation.PortalPageInfo; import eu.europeana.portal2.web.presentation.model.EmptyModelPage; import eu.europeana.portal2.web.util.ClickStreamLogger; import eu.europeana.portal2.web.util.ControllerUtil; @Controller public class UserManagementController { @Resource(name="corelib_db_userService") private UserService userService; @Resource(name="configurationService") private Configuration config; @Resource private ClickStreamLogger clickStreamLogger; private final Logger log = Logger.getLogger(getClass().getName()); @RequestMapping("/myeuropeana2.html") public ModelAndView myEuropeanaHandler( @RequestParam(value = "theme", required = false, defaultValue="") String theme, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { log.info("===== myeuropeana.html ======="); config.registerBaseObjects(request, response, locale); EmptyModelPage model = new EmptyModelPage(); config.injectProperties(model); User user = ControllerUtil.getUser(userService); model.setUser(user); ModelAndView page = ControllerUtil.createModelAndViewPage(model, locale, PortalPageInfo.MYEU); config.postHandle(this, page); clickStreamLogger.logUserAction(request, ClickStreamLogger.UserAction.MY_EUROPEANA); return page; } @RequestMapping("/logout-success.html") public String logoutSuccessHandler(HttpServletRequest request) throws Exception { clickStreamLogger.logUserAction(request, ClickStreamLogger.UserAction.LOGOUT); return "redirect:/login.html"; } @RequestMapping("/logout.html") public ModelAndView logoutHandler( HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception { config.registerBaseObjects(request, response, locale); EmptyModelPage model = new EmptyModelPage(); config.injectProperties(model); ModelAndView page = ControllerUtil.createModelAndViewPage(model, locale, PortalPageInfo.MYEU_LOGOUT); config.postHandle(this, page); clickStreamLogger.logUserAction(request, ClickStreamLogger.UserAction.LOGOUT); return page; } }
true
52d672e836c1b8aa1494261e1838cac2c599fcaa
Java
de-tu-berlin-tfs/Henshin-Editor
/org.eclipse.emf.henshin.model/src/org/eclipse/emf/henshin/model/staticanalysis/PathFinder.java
UTF-8
4,792
2.328125
2
[]
no_license
package org.eclipse.emf.henshin.model.staticanalysis; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.henshin.model.Edge; import org.eclipse.emf.henshin.model.Graph; import org.eclipse.emf.henshin.model.NestedCondition; import org.eclipse.emf.henshin.model.Node; /* * TODO Path finder and PAC checks need re-implementation */ public class PathFinder { public static Map<List<EReference>, Integer> findReferencePaths(Node source, Node target, boolean withPACs, boolean onlyPACs) { Map<List<EReference>, Integer> reflists = new LinkedHashMap<List<EReference>, Integer>(); for (Path path : findEdgePaths(source, target, true, withPACs)) { if (onlyPACs && !path.isViaNestedCondition()) { continue; } List<EReference> list = path.toReferenceList(true); if (list != null) { Integer count = reflists.get(list); if (count != null) { reflists.put(list, count + 1); } else { reflists.put(list, 1); } } } return reflists; } public static List<Path> findEdgePaths(Node source, Node target, boolean withInverse, boolean withPACs) { Graph graph = source.getGraph(); Path initial = new Path(); initial.nodes.add(source); List<Path> tempPaths = new ArrayList<Path>(); tempPaths.add(initial); List<Path> finalPaths = new ArrayList<Path>(); while (!tempPaths.isEmpty()) { List<Path> newTempPaths = new ArrayList<Path>(); for (Path path : tempPaths) { Node last = path.lastNode(); List<Path> steps = doStep(last, withInverse); if (withPACs) { for (NestedCondition pac : graph.getPACs()) { Node image = pac.getMappings().getImage(last, pac.getConclusion()); if (image != null) { steps.addAll(doStep(image, withInverse)); } } } for (Path step : steps) { step.retract(); Path extended = path.copy(); extended.append(step); if (extended.isCyclic()) { continue; } if (extended.lastNode() == target) { finalPaths.add(extended); } else { newTempPaths.add(extended); } } } tempPaths = newTempPaths; } return finalPaths; } private static List<Path> doStep(Node node, boolean withInverse) { List<Path> paths = new ArrayList<Path>(); for (Edge outgoing : node.getOutgoing()) { Path path = new Path(); path.nodes.add(node); path.edges.add(outgoing); path.nodes.add(outgoing.getTarget()); paths.add(path); } if (withInverse) { for (Edge incoming : node.getIncoming()) { Path path = new Path(); path.nodes.add(node); path.edges.add(incoming); path.nodes.add(incoming.getSource()); paths.add(path); } } return paths; } public static List<Path> findAllPaths(Graph graph, boolean withPACs) { List<Path> paths = new ArrayList<Path>(); for (int i = 0; i < graph.getNodes().size(); i++) { for (int j = 0; i < graph.getNodes().size(); i++) { paths.addAll(findEdgePaths(graph.getNodes().get(i), graph.getNodes().get(j), true, withPACs)); } } return paths; } public static boolean pacConsistsOnlyOfPaths(NestedCondition pac) { if (!pac.isPAC()) { return false; } // Collect reached edges and nodes: Set<Node> reachedPACNodes = new HashSet<Node>(); Set<Edge> reachedPACEdges = new HashSet<Edge>(); for (Path path : findAllPaths(pac.getHost(), true)) { if (path.toReferenceList(true) == null) { continue; } for (Node node : path.nodes) { if (node.getGraph() == pac.getConclusion()) { reachedPACNodes.add(node); } else { Node image = pac.getMappings().getImage(node, pac.getConclusion()); if (image != null) { reachedPACNodes.add(image); } } } for (Edge edge : path.edges) { if (edge.getGraph() == pac.getConclusion()) { reachedPACEdges.add(edge); } else { Edge image = pac.getMappings().getImage(edge, pac.getConclusion()); if (image != null) { reachedPACEdges.add(image); } } } } // Check if any of the PAC nodes or edges is missing: if (!reachedPACNodes.containsAll(pac.getConclusion().getNodes())) { return false; } if (!reachedPACEdges.containsAll(pac.getConclusion().getEdges())) { return false; } // Check if any node has an attribute: for (Node node : reachedPACNodes) { if (!node.getAttributes().isEmpty()) { return false; } } // Check if any of the node types does not match the LHS node type: for (Node node : reachedPACNodes) { Node origin = pac.getMappings().getOrigin(node); if (origin != null && origin.getType() != node.getType()) { return false; } } // Ok. return true; } }
true
9cd0141abba11808edd6c00575b19b9f9408af3d
Java
JiselaLondono/BDDBancolombiaUtest
/src/main/java/com/bancolombia/utest/userinterfaces/UtestMenu.java
UTF-8
342
1.726563
2
[]
no_license
package com.bancolombia.utest.userinterfaces; import net.serenitybdd.screenplay.targets.Target; public final class UtestMenu { public static final Target MENU_OPTION = Target.the("Menu option of UTest") .locatedBy("//div[contains (@class, 'unauthenticated-nav-bar__links')]//a[text()='{0}']"); public UtestMenu() {} }
true
458de209e50b3dbab099adaf8ee395842c45b2df
Java
yuanpneg/crawler-province-zhaobiao
/src/main/java/crawler_city/ZaozhuangThread.java
UTF-8
592
2.15625
2
[]
no_license
package crawler_city; import bean.Tender; import services_city.ZaozhuangService; import java.util.List; /** * 枣庄市 */ public class ZaozhuangThread implements Runnable { ZaozhuangService service = new ZaozhuangService(); @Override public void run() { System.out.println("枣庄市"); for (int i = 1; i < 20; i++) { String url = "http://www.zzggzy.com/TPFront/jyxx/070001/070001001/?Paging=" + i; List<Tender> list = service.getList(url); if (list.size() == 0) { break; } } } }
true
e9d041b95e83ced9a500f47c38612471f1b64c7a
Java
NationalSecurityAgency/ghidra
/Ghidra/Processors/x86/src/main/java/ghidra/app/util/bin/format/elf/relocation/X86_64_ElfRelocationConstants.java
UTF-8
5,194
1.554688
2
[ "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.app.util.bin.format.elf.relocation; public class X86_64_ElfRelocationConstants { public static final int R_X86_64_NONE = 0; /* No reloc */ /** S + A */ public static final int R_X86_64_64 = 1; /* Direct 64 bit */ /** S + A - P */ public static final int R_X86_64_PC32 = 2; /* PC relative 32 bit signed */ /** G + P */ public static final int R_X86_64_GOT32 = 3; /* 32 bit GOT entry */ /** L + A - P */ public static final int R_X86_64_PLT32 = 4; /* 32 bit PLT address */ /** ? */ public static final int R_X86_64_COPY = 5; /* Copy symbol at runtime */ /** S */ public static final int R_X86_64_GLOB_DAT = 6; /* Create GOT entry */ /** S */ public static final int R_X86_64_JUMP_SLOT = 7; /* Create PLT entry */ /** B + A */ public static final int R_X86_64_RELATIVE = 8; /* Adjust by program base */ /** G + GOT + A - P */ public static final int R_X86_64_GOTPCREL = 9; /* * 32 bit signed pc relative * offset to GOT */ /** S + A */ public static final int R_X86_64_32 = 10; /* Direct 32 bit zero extended */ /** S + A */ public static final int R_X86_64_32S = 11; /* Direct 32 bit sign extended */ /** S + A */ public static final int R_X86_64_16 = 12; /* Direct 16 bit zero extended */ /** S + A - P */ public static final int R_X86_64_PC16 = 13; /* * 16 bit sign extended pc * relative */ /** S + A */ public static final int R_X86_64_8 = 14; /* Direct 8 bit sign extended */ /** S + A - P */ public static final int R_X86_64_PC8 = 15; /* * 8 bit sign extended pc * relative */ /** * Calculates the object identifier of the * object containing the TLS symbol. */ public static final int R_X86_64_DTPMOD64 = 16; // ID of module containing symbol /** * Calculates the offset of the variable relative * to the start of the TLS block that contains the * variable. The computed value is used as an * immediate value of an addend and is not associated * with a specific register. * */ public static final int R_X86_64_DTPOFF64 = 17; // Offset in module's TLS block public static final int R_X86_64_TPOFF64 = 18; // offset in the initial TLS block public static final int R_X86_64_TLSGD = 19; // 32 bit signed PC relative offset to // two GOT entries for GD symbol public static final int R_X86_64_TLSLD = 20; // 32 bit signed PC relative offset to // two GOT entries for LD symbol public static final int R_X86_64_DTPOFF32 = 21; // offset in TLS block public static final int R_X86_64_GOTTPOFF = 22; // 32 bit signed pc relative offst to // GOT entry for IE symbol public static final int R_X86_64_TPOFF32 = 23; // offset in initial TLS block /** S + A - P */ public static final int R_X86_64_PC64 = 24; // PC relative 64 bit /** S + A - GOT */ public static final int R_X86_64_GOTOFF64 = 25; // 64 bit offset to GOT /** GOT + A + P */ public static final int R_X86_64_GOTPC32 = 26; // 32 bit signed pc relative offset to GOT public static final int R_X86_64_GOT64 = 27; // 64 bit GOT entry offset public static final int R_X86_64_GOTPCREL64 = 28; // 64 bit pc relative offset to GOT entry public static final int R_X86_64_GOTPC64 = 29; // 64 bit pc relative offset to GOT public static final int R_X86_64_GOTPLT64 = 30; // public static final int R_X86_64_PLTOFF64 = 31; // 64 bit GOT relative offset to PLT entry /** Z + A */ public static final int R_X86_64_SIZE32 = 32; // Size of symbol plus 32 bit addend /** Z + A */ public static final int R_X86_64_SIZE64 = 33; // Size of symbol plus 64 bit addend public static final int R_X86_64_GOTPC32_TLSDESC = 34; // GOT offset for TLS descriptor public static final int R_X86_64_TLSDESC_CALL = 35; // Marker for call through TLS descriptor public static final int R_X86_64_TLSDESC = 36; // TLS descriptor; word64 * 2 public static final int R_X86_64_IRELATIVE = 37; // Adjust indirectly by program base public static final int R_X86_64_RELATIVE64 = 38; // 64-bit adjust by program base public static final int R_X86_64_PC32_BND = 39; // deprecated public static final int R_X86_64_PLT32_BND = 40; // deprecated public static final int R_X86_64_GOTPCRELX = 41; // G + GOT + A - P public static final int R_X86_64_REX_GOTPCRELX = 42; //G + GOT + A - P public static final int R_X86_64_NUM = 43; public static final int R_X86_64_GNU_VTINHERIT = 250; public static final int R_X86_64_GNU_VTENTRY = 251; private X86_64_ElfRelocationConstants() { // no construct } }
true
68b59ea14dc6172d2b1fa093dfd85a71c7b09fa1
Java
indigo-iam/iam
/iam-login-service/src/test/java/it/infn/mw/iam/test/util/oauth/MockOAuth2Filter.java
UTF-8
2,292
1.921875
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2016-2021 * * 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 it.infn.mw.iam.test.util.oauth; import java.io.IOException; import java.util.Objects; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter; @SuppressWarnings("deprecation") public class MockOAuth2Filter extends OAuth2AuthenticationProcessingFilter { SecurityContext securityContext; public MockOAuth2Filter() { setAuthenticationManager(new AuthenticationManager() { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { authentication.setAuthenticated(true); return authentication; } }); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!Objects.isNull(securityContext)) { SecurityContextHolder.setContext(securityContext); } chain.doFilter(req, res); } public void setSecurityContext(SecurityContext securityContext) { this.securityContext = securityContext; } public void cleanupSecurityContext() { setSecurityContext(null); SecurityContextHolder.clearContext(); } }
true
8cc066dc4f02643a4e33e17f228ed09f9c1db2c7
Java
crackersamdjam/DMOJ-Solutions
/Uncategorized/dmpg18b2.java
UTF-8
365
2.890625
3
[ "MIT" ]
permissive
import java.io.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] str = in.readLine().split(" "); int n = Integer.parseInt(str[0]), m = Integer.parseInt(str[1]); System.out.println(n>=m ? m-1 : n); } }
true
73a5a320d76088d4f57b16cbc3b066adcacb7bde
Java
vladTelesh/Book
/ui/src/main/java/com/effectivesoft/bookservice/ui/view/NewBookView.java
UTF-8
14,044
2.015625
2
[]
no_license
package com.effectivesoft.bookservice.ui.view; import com.effectivesoft.bookservice.common.dto.BookDto; import com.effectivesoft.bookservice.ui.client.AuthorRestClient; import com.effectivesoft.bookservice.ui.client.BookRestClient; import com.effectivesoft.bookservice.ui.client.UserRestClient; import com.effectivesoft.bookservice.ui.component.AuthorComboBox; import com.effectivesoft.bookservice.ui.component.Header; import com.effectivesoft.bookservice.ui.config.AuthorComboBoxConverter; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.dependency.StyleSheet; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Hr; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.NumberField; import com.vaadin.flow.component.textfield.TextArea; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.data.binder.Binder; import com.vaadin.flow.data.binder.ValidationResult; import com.vaadin.flow.data.validator.StringLengthValidator; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.Objects; import java.util.Optional; @Route("new/book") @PageTitle("New book • Book-service") @StyleSheet(value = "styles/addViewStyle.css") public class NewBookView extends HorizontalLayout { private final UserRestClient userRestClient; private final BookRestClient bookRestClient; private final AuthorRestClient authorRestClient; private static final String TITLE_FIELD = "Title"; private static final String ADDITIONAL_AUTHORS_FIELD = "Additional authors"; private static final String ISBN_FIELD = "ISBN"; private static final String ISBN13_FIELD = "ISBN13"; private static final String PUBLISHER_FIELD = "Publisher"; private static final String BINDING_FIELD = "Binding"; private static final String PAGES_NUMBER_FIELD = "Pages number"; private static final String PUBLICATION_YEAR_FIELD = "Publication year"; private static final String ORIGINAL_PUBLICATION_YEAR_FIELD = "Original publication year"; private static final Logger logger = LoggerFactory.getLogger(NewAuthorView.class); public NewBookView(@Autowired UserRestClient userRestClient, @Autowired BookRestClient bookRestClient, @Autowired AuthorRestClient authorRestClient) throws IOException { this.userRestClient = userRestClient; this.bookRestClient = bookRestClient; this.authorRestClient = authorRestClient; this.load(); } private void load() throws IOException { getElement().removeAttribute("style"); setWidthFull(); setJustifyContentMode(JustifyContentMode.CENTER); setAlignItems(Alignment.CENTER); VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setClassName("main-layout"); mainLayout.setAlignItems(Alignment.CENTER); mainLayout.setJustifyContentMode(JustifyContentMode.CENTER); mainLayout.setWidth("70%"); Hr hr = new Hr(); hr.setClassName("hr"); mainLayout.add(new Header(userRestClient), hr); this.setLabel(mainLayout); this.setInputFields(mainLayout); add(mainLayout); } private void setLabel(VerticalLayout mainLayout) { HorizontalLayout labelLayout = new HorizontalLayout(); labelLayout.setWidthFull(); labelLayout.setClassName("label-layout"); labelLayout.setJustifyContentMode(JustifyContentMode.CENTER); labelLayout.setAlignItems(Alignment.CENTER); Label label = new Label("New book"); label.setClassName("label"); labelLayout.add(label); Hr hr = new Hr(); hr.setClassName("bottom-hr"); mainLayout.add(labelLayout, hr); } private void setInputFields(VerticalLayout mainLayout) { Binder<BookDto> binder = new Binder<>(BookDto.class); BookDto book = new BookDto(); VerticalLayout verticalLayout = new VerticalLayout(); verticalLayout.setClassName("fields-layout"); verticalLayout.getElement().removeAttribute("style"); verticalLayout.setJustifyContentMode(JustifyContentMode.CENTER); this.setTextFieldLayout(verticalLayout, "String", TITLE_FIELD, binder); this.setAuthorComboBoxLayout(verticalLayout, binder); this.setTextFieldLayout(verticalLayout, "String", ADDITIONAL_AUTHORS_FIELD, binder); this.setTextFieldLayout(verticalLayout, "String", ISBN_FIELD, binder); this.setTextFieldLayout(verticalLayout, "String", ISBN13_FIELD, binder); this.setTextFieldLayout(verticalLayout, "String", PUBLISHER_FIELD, binder); this.setTextFieldLayout(verticalLayout, "String", BINDING_FIELD, binder); this.setTextFieldLayout(verticalLayout, "Number", PAGES_NUMBER_FIELD, binder); this.setTextFieldLayout(verticalLayout, "Number", PUBLICATION_YEAR_FIELD, binder); this.setTextFieldLayout(verticalLayout, "Number", ORIGINAL_PUBLICATION_YEAR_FIELD, binder); MemoryBuffer buffer = new MemoryBuffer(); Upload upload = new Upload(buffer); this.setUploadLayout(verticalLayout, upload, buffer); VerticalLayout descriptionLayout = new VerticalLayout(); descriptionLayout.setWidthFull(); descriptionLayout.setJustifyContentMode(JustifyContentMode.CENTER); descriptionLayout.getElement().removeAttribute("theme"); Label descriptionLabel = new Label("Description:"); descriptionLabel.setWidth("10%"); descriptionLabel.setClassName("description-label"); TextArea description = new TextArea(); binder.forField(description) .bind(BookDto::getDescription, BookDto::setDescription); description.setWidth("100%"); descriptionLayout.add(descriptionLabel, description); HorizontalLayout createButtonLayout = new HorizontalLayout(); createButtonLayout.setJustifyContentMode(JustifyContentMode.CENTER); createButtonLayout.setAlignItems(Alignment.CENTER); createButtonLayout.setWidthFull(); Div button = new Div(); button.add("Create"); button.setClassName("create-button"); button.addClickListener(onClick -> { if (binder.validate().isOk()) { binder.writeBeanIfValid(book); try { Optional<BookDto> optionalBook = bookRestClient.createBook(book); optionalBook.ifPresent(bookDto -> { if (buffer.getFileData() != null && !upload.isUploading()) { try { if (!bookRestClient.updateBookImage(optionalBook.get().getId(), buffer.getFileName(), buffer.getFileData().getMimeType(), buffer.getInputStream().readAllBytes())) { logger.error("Error to create image!"); } } catch (IOException e) { logger.error(e.getMessage()); } } UI.getCurrent().navigate("book/" + optionalBook.get().getId()); }); } catch (IOException e) { e.printStackTrace(); } } }); createButtonLayout.add(button); verticalLayout.add(descriptionLayout, createButtonLayout); mainLayout.add(verticalLayout); } private void setTextFieldLayout(VerticalLayout verticalLayout, String type, String fieldType, Binder<BookDto> binder) { HorizontalLayout horizontalLayout = new HorizontalLayout(); horizontalLayout.setWidthFull(); horizontalLayout.setAlignItems(Alignment.CENTER); Label label = new Label(fieldType + ":"); label.setWidth("250px"); label.setClassName("add-book-field-label"); switch (type) { case "String": TextField stringField = new TextField(); switch (fieldType) { case TITLE_FIELD: binder.forField(stringField) .withValidator(Objects::nonNull, "Title can't be empty") .bind(BookDto::getTitle, BookDto::setTitle); break; case ADDITIONAL_AUTHORS_FIELD: binder.forField(stringField) .bind(BookDto::getAdditionalAuthors, BookDto::setAdditionalAuthors); break; case ISBN_FIELD: binder.forField(stringField) .withValidator(new StringLengthValidator( "ISBN must have 10 characters", 10, 10)) .bind(BookDto::getISBN, BookDto::setISBN); break; case ISBN13_FIELD: binder.forField(stringField) .withValidator(new StringLengthValidator( "ISBN13 must have 13 characters", 13, 13)) .bind(BookDto::getISBN13, BookDto::setISBN13); break; case PUBLISHER_FIELD: binder.forField(stringField) .bind(BookDto::getPublisher, BookDto::setPublisher); break; case BINDING_FIELD: binder.forField(stringField) .bind(BookDto::getBinding, BookDto::setBinding); break; } horizontalLayout.add(label, stringField); verticalLayout.add(horizontalLayout); break; case "Number": NumberField numberField = new NumberField(); switch (fieldType) { case PAGES_NUMBER_FIELD: binder.forField(numberField) .withConverter(Double::intValue, Integer::doubleValue, "Please enter a number") .withValidator(Objects::nonNull, "Pages number field can't be empty") .bind(BookDto::getPagesNumber, BookDto::setPagesNumber); break; case PUBLICATION_YEAR_FIELD: binder.forField(numberField) .withConverter(Double::intValue, Integer::doubleValue, "Please enter a number") .bind(BookDto::getPublicationYear, BookDto::setPublicationYear); break; case ORIGINAL_PUBLICATION_YEAR_FIELD: binder.forField(numberField) .withConverter(Double::intValue, Integer::doubleValue, "Please enter a number") .bind(BookDto::getOriginalPublicationYear, BookDto::setOriginalPublicationYear); break; } numberField.setHasControls(true); numberField.setWidth("50%"); horizontalLayout.add(label, numberField); verticalLayout.add(horizontalLayout); break; } } private void setAuthorComboBoxLayout(VerticalLayout verticalLayout, Binder<BookDto> binder) { HorizontalLayout horizontalLayout = new HorizontalLayout(); horizontalLayout.setWidthFull(); horizontalLayout.setAlignItems(Alignment.CENTER); Label label = new Label("Author" + ":"); label.setWidth("250px"); label.setClassName("add-book-field-label"); AuthorComboBox authorComboBox = new AuthorComboBox(binder, authorRestClient); binder.forField(authorComboBox) .withValidator((value, message) -> { if (value != null) { return ValidationResult.ok(); } else { return ValidationResult.error("Author field can't be empty!"); } }) .withConverter(new AuthorComboBoxConverter()) .bind(BookDto::getAuthorId, BookDto::setAuthorId); horizontalLayout.add(label, authorComboBox); verticalLayout.add(horizontalLayout); } private void setUploadLayout(VerticalLayout verticalLayout, Upload upload, MemoryBuffer buffer) { HorizontalLayout imageLayout = new HorizontalLayout(); imageLayout.setAlignItems(Alignment.CENTER); imageLayout.setWidthFull(); Label uploadLabel = new Label("Photo:"); uploadLabel.setClassName("photo-field-label"); uploadLabel.setWidth("10%"); Div uploadButton = new Div(); uploadButton.setClassName("upload-button"); uploadButton.add("Upload file"); upload.setWidthFull(); upload.setUploadButton(uploadButton); upload.setMaxFiles(1); upload.setAcceptedFileTypes("image/*"); imageLayout.add(uploadLabel, upload); verticalLayout.add(imageLayout); } }
true
01b770f491011a37220e3fd7b29b6278226c6426
Java
foxyuca/Importcolex
/src/main/java/co/com/importcolex/tejeduria/web/rest/mapper/FibrasTelaCrudaMapper.java
UTF-8
1,394
2.109375
2
[]
no_license
package co.com.importcolex.tejeduria.web.rest.mapper; import co.com.importcolex.tejeduria.domain.*; import co.com.importcolex.tejeduria.web.rest.dto.FibrasTelaCrudaDTO; import org.mapstruct.*; /** * Mapper for the entity FibrasTelaCruda and its DTO FibrasTelaCrudaDTO. */ @Mapper(componentModel = "spring", uses = {}) public interface FibrasTelaCrudaMapper { @Mapping(source = "inventarioFibras.id", target = "inventarioFibrasId") @Mapping(source = "inventarioFibras.lote", target = "inventarioFibrasLote") @Mapping(source = "telaCruda.id", target = "telaCrudaId") FibrasTelaCrudaDTO fibrasTelaCrudaToFibrasTelaCrudaDTO(FibrasTelaCruda fibrasTelaCruda); @Mapping(source = "inventarioFibrasId", target = "inventarioFibras") @Mapping(source = "telaCrudaId", target = "telaCruda") FibrasTelaCruda fibrasTelaCrudaDTOToFibrasTelaCruda(FibrasTelaCrudaDTO fibrasTelaCrudaDTO); default InventarioFibras inventarioFibrasFromId(Long id) { if (id == null) { return null; } InventarioFibras inventarioFibras = new InventarioFibras(); inventarioFibras.setId(id); return inventarioFibras; } default TelaCruda telaCrudaFromId(Long id) { if (id == null) { return null; } TelaCruda telaCruda = new TelaCruda(); telaCruda.setId(id); return telaCruda; } }
true
136196acdd67418e6efb4d68652dccce93c4b0ea
Java
Drrany/Algorithms_Code
/Java/Leetcode/11_Graph/133_CloneGraph.java
UTF-8
1,707
3.21875
3
[]
no_license
import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; class Node { public int val; public List<Node> neighbors; public Node() { val = 0; neighbors = new ArrayList<Node>(); } public Node(int _val) { val = _val; neighbors = new ArrayList<Node>(); } public Node(int _val, ArrayList<Node> _neighbors) { val = _val; neighbors = _neighbors; } } class CloneGraph { // BFS public Node cloneGraph(Node node) { if (node == null) return null; Node[] set = new Node[101]; set[node.val] = new Node(node.val, new ArrayList<>()); Deque<Node> q = new LinkedList<>(); q.offer(node); while (!q.isEmpty()) { Node tmp = q.poll(); for (Node p : tmp.neighbors) { if (set[p.val] == null) { q.offer(p); set[p.val] = new Node(p.val, new ArrayList<>()); } set[tmp.val].neighbors.add(set[p.val]); } } return set[node.val]; } // DFS public Node cloneGraph2(Node node) { Node[] set = new Node[101]; reCur(node, set); return node == null ? null : set[node.val]; } public static void reCur(Node n, Node[] set) { if (n == null) return; if (set[n.val] == null) set[n.val] = new Node(n.val, new ArrayList<>()); for (Node p : n.neighbors) { if (set[p.val] == null) reCur(p, set); set[n.val].neighbors.add(set[p.val]); } return; } }
true
abfc21112641904951244825ec5e0e0eb29b521d
Java
jcmartin2889/Repo
/EquationBuilder/src/com/misys/equation/common/ant/builder/core/EqDataType.java
UTF-8
389
1.539063
2
[]
no_license
package com.misys.equation.common.ant.builder.core; public class EqDataType { // This attribute is used to store cvs version information. public static final String _revision = "$Id: EqDataType.java 4741 2009-09-16 16:33:23Z esther.williams $"; public final static String TYPE_CHAR = "A"; public final static String TYPE_PACKED = "P"; public final static String TYPE_ZONED = "S"; }
true
851e60e147f620ed86d0c494189e1f400dd83f84
Java
hmalick4/CodesFromEclipse
/src/com/syntax/class10/TwoDArrays.java
UTF-8
1,029
4.0625
4
[]
no_license
package com.syntax.class10; public class TwoDArrays { public static void main(String[] args) { // TODO Auto-generated method stub int a; int[] b=new int[3]; //creating a twoD array int[][] c=new int [3][4]; //row 1 or first array c[0][0]=11; c[0][1]=12; c[0][2]=13; c[0][3]=14; //row 2 or second array c[1][0]=20; c[1][1]=30; c[1][2]=40; c[1][3]=50; //row 3 or third array c[2][0]=100; c[2][1]=200; c[2][2]=300; c[2][3]=400; System.out.println(c[1][3]); //50. to access, specify from which row index and column index System.out.println(c[2][1]); //200. to access, specify from which index array and what element index System.out.println("--------another way to create a 2D array-------"); int [][] myArray= { {11,12,13,14,15}, //first array {20,30,40}, //second array {100, 200, 300, 400} //third array }; System.out.println(myArray [0][4]); //15 System.out.println(myArray[1][0]); //20 } }
true
bef5d136045094f0287447f1084979aaf311b39e
Java
sfranklyn/segcounter
/src/main/java/com/galileoindonesia/schema/pnr/VndInfo.java
UTF-8
9,047
1.609375
2
[]
no_license
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-548 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2009.03.31 at 11:27:25 AM ICT // package com.galileoindonesia.schema.pnr; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}CarV"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}CarType1"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}CarType2"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}CarType3"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}CarType4"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}LocnCode"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}Rate"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}CDNum"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}DefFOPRef"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}MileMemberRefNum"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}DefSpcEquip"/> * &lt;element ref="{http://www.galileoindonesia.com/schema/PNR}DefSpecInfo"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "carV", "carType1", "carType2", "carType3", "carType4", "locnCode", "rate", "cdNum", "defFOPRef", "mileMemberRefNum", "defSpcEquip", "defSpecInfo" }) @XmlRootElement(name = "VndInfo") public class VndInfo implements Serializable { @XmlElement(name = "CarV", required = true) protected String carV; @XmlElement(name = "CarType1", required = true) protected String carType1; @XmlElement(name = "CarType2", required = true) protected String carType2; @XmlElement(name = "CarType3", required = true) protected String carType3; @XmlElement(name = "CarType4", required = true) protected String carType4; @XmlElement(name = "LocnCode", required = true) protected String locnCode; @XmlElement(name = "Rate", required = true) protected String rate; @XmlElement(name = "CDNum", required = true) protected String cdNum; @XmlElement(name = "DefFOPRef", required = true) protected String defFOPRef; @XmlElement(name = "MileMemberRefNum", required = true) protected String mileMemberRefNum; @XmlElement(name = "DefSpcEquip", required = true) protected String defSpcEquip; @XmlElement(name = "DefSpecInfo", required = true) protected String defSpecInfo; /** * Gets the value of the carV property. * * @return * possible object is * {@link String } * */ public String getCarV() { return carV; } /** * Sets the value of the carV property. * * @param value * allowed object is * {@link String } * */ public void setCarV(String value) { this.carV = value; } /** * Gets the value of the carType1 property. * * @return * possible object is * {@link String } * */ public String getCarType1() { return carType1; } /** * Sets the value of the carType1 property. * * @param value * allowed object is * {@link String } * */ public void setCarType1(String value) { this.carType1 = value; } /** * Gets the value of the carType2 property. * * @return * possible object is * {@link String } * */ public String getCarType2() { return carType2; } /** * Sets the value of the carType2 property. * * @param value * allowed object is * {@link String } * */ public void setCarType2(String value) { this.carType2 = value; } /** * Gets the value of the carType3 property. * * @return * possible object is * {@link String } * */ public String getCarType3() { return carType3; } /** * Sets the value of the carType3 property. * * @param value * allowed object is * {@link String } * */ public void setCarType3(String value) { this.carType3 = value; } /** * Gets the value of the carType4 property. * * @return * possible object is * {@link String } * */ public String getCarType4() { return carType4; } /** * Sets the value of the carType4 property. * * @param value * allowed object is * {@link String } * */ public void setCarType4(String value) { this.carType4 = value; } /** * Gets the value of the locnCode property. * * @return * possible object is * {@link String } * */ public String getLocnCode() { return locnCode; } /** * Sets the value of the locnCode property. * * @param value * allowed object is * {@link String } * */ public void setLocnCode(String value) { this.locnCode = value; } /** * Gets the value of the rate property. * * @return * possible object is * {@link String } * */ public String getRate() { return rate; } /** * Sets the value of the rate property. * * @param value * allowed object is * {@link String } * */ public void setRate(String value) { this.rate = value; } /** * Gets the value of the cdNum property. * * @return * possible object is * {@link String } * */ public String getCDNum() { return cdNum; } /** * Sets the value of the cdNum property. * * @param value * allowed object is * {@link String } * */ public void setCDNum(String value) { this.cdNum = value; } /** * Gets the value of the defFOPRef property. * * @return * possible object is * {@link String } * */ public String getDefFOPRef() { return defFOPRef; } /** * Sets the value of the defFOPRef property. * * @param value * allowed object is * {@link String } * */ public void setDefFOPRef(String value) { this.defFOPRef = value; } /** * Gets the value of the mileMemberRefNum property. * * @return * possible object is * {@link String } * */ public String getMileMemberRefNum() { return mileMemberRefNum; } /** * Sets the value of the mileMemberRefNum property. * * @param value * allowed object is * {@link String } * */ public void setMileMemberRefNum(String value) { this.mileMemberRefNum = value; } /** * Gets the value of the defSpcEquip property. * * @return * possible object is * {@link String } * */ public String getDefSpcEquip() { return defSpcEquip; } /** * Sets the value of the defSpcEquip property. * * @param value * allowed object is * {@link String } * */ public void setDefSpcEquip(String value) { this.defSpcEquip = value; } /** * Gets the value of the defSpecInfo property. * * @return * possible object is * {@link String } * */ public String getDefSpecInfo() { return defSpecInfo; } /** * Sets the value of the defSpecInfo property. * * @param value * allowed object is * {@link String } * */ public void setDefSpecInfo(String value) { this.defSpecInfo = value; } }
true
5c49eafe4e54b6eeb4a339de68de1b5da9a5b1fa
Java
maxcar1/maxcar
/market-tenant/market-tenant-interface/src/main/java/com/maxcar/tenant/pojo/IntegralEvaluation.java
UTF-8
3,001
1.734375
2
[]
no_license
package com.maxcar.tenant.pojo; import com.maxcar.base.pojo.PageBean; import java.io.Serializable; import java.util.Date; public class IntegralEvaluation extends PageBean implements Serializable { private String id; private String checkItems; // 具体标准 private Integer scoresAddSubtract;// 1加 2减 private String scopeUp; private String scopeDown; private String marketId; private Integer status; private String remark; private Integer isvalid; private Date insertTime; private String insertOperator; private Date updateTime; private String updateOperator; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getCheckItems() { return checkItems; } public void setCheckItems(String checkItems) { this.checkItems = checkItems == null ? null : checkItems.trim(); } public Integer getScoresAddSubtract() { return scoresAddSubtract; } public void setScoresAddSubtract(Integer scoresAddSubtract) { this.scoresAddSubtract = scoresAddSubtract; } public String getScopeUp() { return scopeUp; } public void setScopeUp(String scopeUp) { this.scopeUp = scopeUp == null ? null : scopeUp.trim(); } public String getScopeDown() { return scopeDown; } public void setScopeDown(String scopeDown) { this.scopeDown = scopeDown == null ? null : scopeDown.trim(); } public String getMarketId() { return marketId; } public void setMarketId(String marketId) { this.marketId = marketId == null ? null : marketId.trim(); } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public Integer getIsvalid() { return isvalid; } public void setIsvalid(Integer isvalid) { this.isvalid = isvalid; } public Date getInsertTime() { return insertTime; } public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } public String getInsertOperator() { return insertOperator; } public void setInsertOperator(String insertOperator) { this.insertOperator = insertOperator == null ? null : insertOperator.trim(); } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateOperator() { return updateOperator; } public void setUpdateOperator(String updateOperator) { this.updateOperator = updateOperator == null ? null : updateOperator.trim(); } }
true
fc114b261c484450ca6b8f72d2ac1896723c44e5
Java
yindongge/yindongge.github.io
/org/kjj/.svn/pristine/a4/a4b8bd02e40b911aab9c2e75d3baa4dcce9eb865.svn-base
UTF-8
560
1.5625
2
[]
no_license
package com.kjj.commserver.entity.order.aide; public class OrgReturnOrderConstant { public static final byte RETURN_STYLE_RETURN = 0; public static final byte RETURN_STYLE_CHANGE = 1; public static final byte TAKE_STYLE_TAKE = 0; public static final byte TAKE_STYLE_SELF = 1; public static final byte RETURN_STATUS_APPLY = 0; public static final byte RETURN_STATUS_REFUSE = 1; public static final byte RETURN_STATUS_WAIT_RETURN = 2; public static final byte RETURN_STATUS_FINISH = 3; public static final byte RETURN_SHOW = 1; }
true
21e16b2929305678c3d0cacbb561c7af678b5b19
Java
kwon37xi/springnote-notetaker
/src/com/springnote/notetaker/TempPageMeta.java
UTF-8
546
2.375
2
[]
no_license
package com.springnote.notetaker; import rath.toys.springnote.PageMeta; public class TempPageMeta { private PageMeta pageMeta = null; public TempPageMeta(PageMeta pageMeta) { this.pageMeta = pageMeta; } public int getId() { return pageMeta.getId(); } public String getName() { return pageMeta.getName(); } public String toString() { final int MAX_LENGTH = 30; String name = getName(); if (name.length() > MAX_LENGTH) { name = name.substring(0, MAX_LENGTH) + "..."; } return name + " [" + getId() + "]" ; } }
true
8d56c3bdcae9d86ba67eb7e19ae852dd55cc9cd4
Java
KimPhuong99/QLHS
/QuanLyHocSinh/src/quanlyhocsinh/PanelRetriever.java
UTF-8
2,145
2.984375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quanlyhocsinh; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PanelRetriever{ Box panel1; JPanel panel2; public PanelRetriever(final JFrame frame){ //Build the first login panel panel1 = Box.createVerticalBox(); panel1.setBackground(Color.orange); panel1.setOpaque(true); panel1.add(Box.createVerticalGlue()); panel1.add(new JTextField(10)); JButton login = new JButton("Login"); login.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { frame.setContentPane(getPanel2()); frame.validate(); }}); panel1.add(login); panel1.add(Box.createVerticalGlue()); //Build second panel panel2 = new JPanel(); panel2.setBackground(Color.blue); panel2.setOpaque(true); JButton logout = new JButton("Logout"); logout.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { frame.setContentPane(getPanel1()); frame.validate(); }}); panel2.add(logout, BorderLayout.CENTER); } public Container getPanel1(){ return panel1; } public Container getPanel2(){ return panel2; } public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); PanelRetriever pr = new PanelRetriever(frame); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setContentPane(pr.getPanel1()); frame.setPreferredSize(new Dimension(500, 400)); frame.pack(); frame.setVisible(true); } }); } }
true
53d8093461ea952e2958d2dcba916bfb8634b565
Java
Buttyx/LocActiTracker-Sensing
/mobile/src/main/java/ch/fhnw/locactitrackermobile/model/ActivityType.java
UTF-8
462
2.671875
3
[]
no_license
package ch.fhnw.locactitrackermobile.model; /** * List of supported activity */ public enum ActivityType { COOKING("Cooking"), DINNING("Dinning"), SPORT("Sport"), SHOPPING("Shopping"), ENTERTAINMENT("Entertainment"), STUDYING("Studying"), TRANSPORTATION("Transportation"); private String label; ActivityType(String label) { this.label = label; } public String getLabel(){ return label; } }
true
09e90a85397752c167a80fde5a234459eb87e79f
Java
yangfeilongCode/EveryDayNews
/app/src/main/java/feicui/edu/everydaynews/entity/LoginData.java
UTF-8
895
2.4375
2
[]
no_license
package feicui.edu.everydaynews.entity; /** * Created by Administrator on 2016/10/9. */ public class LoginData { public int result; //登录状态 public String explain; //登陆成功 public String token; //用户令牌 public int getResult() { return result; } public void setResult(int result) { this.result = result; } public String getExplain() { return explain; } public void setExplain(String explain) { this.explain = explain; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Override public String toString() { return "LoginData{" + "result=" + result + ", explain='" + explain + '\'' + ", token='" + token + '\'' + '}'; } }
true
1ca3fb9365173a11874f6ce5a7a0db6ca2a704cd
Java
senioroman4uk/tickets-accounting
/src/main/java/org/kpi/senioroman4uk/tickets_accounting/domain/Employee.java
UTF-8
2,203
2.609375
3
[]
no_license
package org.kpi.senioroman4uk.tickets_accounting.domain; import org.springframework.format.annotation.DateTimeFormat; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; import java.util.Date; /** * Created by Vladyslav on 22.11.2015. * */ public class Employee implements Serializable, ViewModel { public enum EmployeePosition { MAIN_CASIER(5), CASIER(1), CONDUCTOR(3); private int id; EmployeePosition(int id) { this.id = id; } public int getId() { return id; } } private Integer id; @NotNull private Position position; @Size(min = 2, max = 50) private String firstname; @Size(min = 2, max = 50) private String lastname; @Size(min = 1, max = 50) private String middlename; @DateTimeFormat(pattern = "y-M-d") @NotNull private Date birthDate; // private String login; // private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getMiddlename() { return middlename; } public void setMiddlename(String middlename) { this.middlename = middlename; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getFullname() { return String.format("%s %s %s", lastname, firstname, middlename); } public boolean isNew() { return id == null; } @Override public String toString() { return getFullname(); } }
true
1fd42662f956f277fde80d431bdd5d420856b646
Java
RA19204001/Pizza_Cat
/src/bean/OrderHistoryList.java
UTF-8
438
2.3125
2
[]
no_license
package bean; import java.util.ArrayList; public class OrderHistoryList implements Bean { private ArrayList<OrderHistory> orderHistoryList = new ArrayList<OrderHistory>(); public OrderHistoryList() {} public ArrayList<OrderHistory> getOrderHistoryList(){ return orderHistoryList; } public void setOrderHistoryList(ArrayList<OrderHistory> orderHistoryList) { this.orderHistoryList = orderHistoryList; } }
true
3f28d9161adae3854f0fe471aad8eab5d1661a5b
Java
xangqun/swagger-maven-plugin
/src/main/java/com/github/kongchen/swagger/docgen/reader/ResponseDtoProperty.java
UTF-8
2,880
2.296875
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2017-2025 Evergrande Group. */ package com.github.kongchen.swagger.docgen.reader; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.refs.GenericRef; import io.swagger.models.refs.RefFormat; import io.swagger.models.refs.RefType; /** * @author laixiangqun * @since 2018-6-21 */ public class ResponseDtoProperty extends RefProperty { private Property property; private GenericRef genericRef; private String responseContainer; public ResponseDtoProperty(Property property,String responseContainer) { this(); this.property = property; this.responseContainer=responseContainer; } public ResponseDtoProperty() { setType(TYPE); } public static boolean isType(String type, String format) { if (TYPE.equals(type)) { return true; } else { return false; } } @Override public RefProperty asDefault(String ref) { this.set$ref(RefType.DEFINITION.getInternalPrefix() + ref); return this; } @Override public RefProperty description(String description) { this.setDescription(description); return this; } @Override @JsonIgnore public String getType() { return this.type; } @Override @JsonIgnore public void setType(String type) { this.type = type; } @Override public String get$ref() { return genericRef.getRef(); } @Override public void set$ref(String ref) { this.genericRef = new GenericRef(RefType.DEFINITION, ref); } @Override @JsonIgnore public RefFormat getRefFormat() { if (genericRef != null) { return this.genericRef.getFormat(); } else { return null; } } @Override @JsonIgnore public String getSimpleRef() { if (genericRef != null) { return this.genericRef.getSimpleRef(); } else { return null; } } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((genericRef == null) ? 0 : genericRef.hashCode()); return result; } @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } if (!(obj instanceof ResponseDtoProperty)) { return false; } ResponseDtoProperty other = (ResponseDtoProperty) obj; if (genericRef == null) { if (other.genericRef != null) { return false; } } else if (!genericRef.equals(other.genericRef)) { return false; } return true; } }
true
b6a822d8f256c6a6a2553aeb18eb1267f4ef18f0
Java
rlaeodyd17/java
/0903/src/exception/Ex1.java
UTF-8
911
3.734375
4
[]
no_license
package exception; import java.util.Random; public class Ex1 { //Exception 예외처리는 try~catch 구문으로 처리합니다. //Exception이 발생하는 구문에 적용 public static void main(String[] args) { //System.out.println(5/0); //컴파일 에러는 없다(정수/정수 이므로) //자바스크립트 Random 함수 //Math.floor(Math.random()*갯수))+시작수 //Java의 난수 발생 Random ran = new Random(); // //ran.nextInt(갯수)+시작수; //5~10까지 난수를 100번 발생 //0~5까지 난수를 100번 발생 for(int i=0;i<100 ;i++){ int num = ran.nextInt(6)+0; try { //예외발생할만한 코드를 작성 System.out.println(i+" 번째 "+10/num); }catch(Exception e) { //예외가 발생할때 작동되는 곳 e.printStackTrace(); } } // for end }//main() end }//Ex1 end
true
3d8d5fc25124b4bc29fc895bebcc28d5c36a135b
Java
Nabefumi/wmad_Assignment8
/problem3/Shape3.java
UTF-8
288
2.5625
3
[]
no_license
package ca.ciccc.wmad202.assignment8.problem3; abstract class Shape3 { public abstract float perimeter(); public abstract float area(); ApplicationDriver3.ShapeType type; public Shape3(ApplicationDriver3.ShapeType st, int[] s1Sides) { this.type = st; } }
true
86ea9f504f367d7799f1a751beba551d44a58e93
Java
MerylLiu/jdark
/src/core/com/iptv/core/utils/JsonUtil.java
UTF-8
1,091
2.34375
2
[ "Apache-2.0" ]
permissive
package com.iptv.core.utils; import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtil { public static String getJson(Object data) { ObjectMapper mapper = new ObjectMapper(); String res = ""; try { res = mapper.writeValueAsString(data); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } public static Object getObject(String json) { try { ObjectMapper objectMapper = new ObjectMapper(); Object result = objectMapper.readValue(json, Object.class); return result; } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonMappingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
true
aa77f6d776716a29824fb13b85c62750fb43a263
Java
NJUASI/Quantour
/src/main/java/com/edu/nju/asi/utilities/enums/Market.java
UTF-8
1,529
3.0625
3
[]
no_license
package com.edu.nju.asi.utilities.enums; /** * Created by cuihua on 2017/3/4. * * 股票证券市场 * 以防之后新的证券市场出现 */ public enum Market { SZ(0), SH(1); private int repre; Market(int repre) { this.repre = repre; } /** * * @return 该枚举相对应的文件中形式 * * enum TO int * 便于写入数据库 */ public int getRepre() { return repre; } /** * * @return 该类型对应的枚举代码 * * String TO enum * 便于从数据库读入 */ public static Market getEnum(int a) { for (Market thisEnum : Market.values()){ if (thisEnum.repre == a){ return thisEnum; } } return null; } // private int representNum; // // private Market(int representNum) { // this.representNum = representNum; // } // // /** // * // * @return 该枚举相对应的汉字 // * // * enum TO int // * 便于写入数据库 // */ // public int getRepresentNum() { // return representNum; // } // // /** // * // * @return 该类型对应的枚举代码 // * // * int TO enum // * 便于从数据库读入 // */ // public static Market getEnum(int a) { // for (Market thisEnum : Market.values()){ // if (thisEnum.representNum == a){ // return thisEnum; // } // } // return null; // } }
true
713d665bffad3039aea2e3df36f37546a68df782
Java
YAldyan/Java-Effective
/src/_02_CreatingDestroyingObject/Item_03/ElvisEnum.java
UTF-8
173
2.375
2
[]
no_license
package _02_CreatingDestroyingObject.Item_03; //Enum singleton - the preferred approach public enum ElvisEnum { INSTANCE; public void leaveTheBuilding() {}; }
true
935e0a901c8fcce45a6428cfe00ea8c208ad43cc
Java
gitter-badger/DOP
/src/main/java/ee/hm/dop/utils/ConfigurationProperties.java
UTF-8
2,312
1.679688
2
[]
no_license
package ee.hm.dop.utils; public interface ConfigurationProperties { // Database String DATABASE_URL = "db.url"; String DATABASE_USERNAME = "db.username"; String DATABASE_PASSWORD = "db.password"; // Server String SERVER_PORT = "server.port"; String SERVER_ADDRESS = "server.address"; String COMMAND_LISTENER_PORT = "command.listener.port"; // Search String SEARCH_SERVER = "search.server"; // TAAT String TAAT_SSO = "taat.sso"; String TAAT_CONNECTION_ID = "taat.connectionId"; String TAAT_ASSERTION_CONSUMER_SERVICE_INDEX = "taat.assertionConsumerServiceIndex"; String TAAT_METADATA_FILEPATH = "taat.metadata.filepath"; String TAAT_METADATA_ENTITY_ID = "taat.metadata.entityID"; // Keystore for TAAT and signing user data for estonian publisher // repositories String KEYSTORE_FILENAME = "keystore.filename"; String KEYSTORE_PASSWORD = "keystore.password"; String KEYSTORE_SIGNING_ENTITY_ID = "keystore.signingEntityID"; String KEYSTORE_SIGNING_ENTITY_PASSWORD = "keystore.signingEntityPassword"; // Mobile ID String MOBILEID_ENDPOINT = "mobileID.endpoint"; String MOBILEID_SERVICENAME = "mobileID.serviceName"; String MOBILEID_NAMESPACE_PREFIX = "mobileID.namespace.prefix"; String MOBILEID_NAMESPACE_URI = "mobileID.namespace.uri"; String MOBILEID_MESSAGE_TO_DISPLAY = "mobileID.messageToDisplay"; // EHIS String XTEE_NAMESPACE_PREFIX = "xtee.namespace.prefix"; String XTEE_NAMESPACE_URI = "xtee.namespace.uri"; String EHIS_ENDPOINT = "ehis.endpoint"; String EHIS_INSTITUTION = "ehis.institution"; String EHIS_SYSTEM_NAME = "ehis.system.name"; String EHIS_SERVICE_NAME = "ehis.service.name"; // EKool String EKOOL_CLIENT_ID = "ekool.client.id"; String EKOOL_CLIENT_SECRET = "ekool.client.secret"; String EKOOL_URL_AUTHORIZE = "ekool.url.authorize"; String EKOOL_URL_TOKEN = "ekool.url.token"; String EKOOL_URL_GENERALDATA = "ekool.url.generaldata"; // Stuudium String STUUDIUM_CLIENT_ID = "stuudium.client.id"; String STUUDIUM_CLIENT_SECRET = "stuudium.client.secret"; String STUUDIUM_URL_AUTHORIZE = "stuudium.url.authorize"; String STUUDIUM_URL_GENERALDATA = "stuudium.url.generaldata"; String MAX_FILE_SIZE = "file.upload.max.size"; }
true
d79e7cf13959fd5782f74410041c21a1d25219f3
Java
moutainhigh/xcdv1
/msk-dev/msk-so/src/main/java/com/msk/so/rs/ISO151433RsController.java
UTF-8
1,984
2.0625
2
[]
no_license
package com.msk.so.rs; import com.msk.core.annotation.Validator; import com.msk.core.bean.RsRequest; import com.msk.core.bean.RsResponse; import com.msk.core.web.base.BaseRsController; import com.msk.core.web.consts.BusinessConst; import com.msk.so.bean.ISO151433RsResult; import com.msk.so.bean.ISO151433RsParam; import com.msk.so.logic.ISO151433Logic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by sunjiaju on 2016/7/14. */ @RestController public class ISO151433RsController extends BaseRsController { private static Logger logger = LoggerFactory.getLogger(ISO151433RsController.class); @Autowired private ISO151433Logic iso151433Logic; @RequestMapping(value = "/api/v1/so/sdo/shipment/cancel", method = RequestMethod.POST, produces = { MediaType.APPLICATION_XML_VALUE },consumes = { MediaType.APPLICATION_XML_VALUE }) @Validator(validatorClass = "com.msk.so.validator.ISO151433Validator") public RsResponse<ISO151433RsResult> halfMonthOrder(@RequestBody RsRequest<ISO151433RsParam> request){ logger.info("订单发货取消回传接口!"); request.getParam().setUpdId(request.getLoginId()); RsResponse<ISO151433RsResult> response = new RsResponse<ISO151433RsResult>(); ISO151433RsResult iso151433RsResult = iso151433Logic.cancelShipment(request.getParam()); response.setStatus(BusinessConst.RsStatus.SUCCESS); response.setResult(iso151433RsResult); response.setMessage("订单发货取消成功!"); logger.info("订单发货取消结束!"); return response; } }
true
6eb1c457ab0caf6fb31dcface21d43cda4b573e8
Java
STAMP-project/dspot-usecases-output
/OW2/Sat4j/20181029/dspot-out/org/sat4j/tools/TestGateTranslator.java
UTF-8
1,148
2.203125
2
[]
no_license
package org.sat4j.tools; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.sat4j.core.VecInt; import org.sat4j.minisat.SolverFactory; import org.sat4j.specs.ContradictionException; import org.sat4j.specs.ISolver; import org.sat4j.specs.TimeoutException; public class TestGateTranslator { private ISolver solver; private GateTranslator gator; @Before public void startUp() { this.solver = SolverFactory.newDefault(); this.gator = new GateTranslator(this.solver); } @Test(timeout = 10000) public void testSATIfThen3() throws Exception, ContradictionException, TimeoutException { gator.it(1, 2, 3); boolean o_testSATIfThen3__2 = this.gator.isSatisfiable(new VecInt(new int[]{ 1, -2, 3 })); Assert.assertTrue(o_testSATIfThen3__2); } @Test(timeout = 10000) public void testSATIfThen5() throws Exception, ContradictionException, TimeoutException { gator.it(1, 2, 3); boolean o_testSATIfThen5__2 = this.gator.isSatisfiable(new VecInt(new int[]{ -1, 2, 3 })); Assert.assertFalse(o_testSATIfThen5__2); } }
true
42ed0cc8a7e97ffe0389467cdd19d3feb7dc3184
Java
pig13/algorithm
/niuke/src/algorithm_array/ZigZagPrintMatrix.java
UTF-8
1,313
3.765625
4
[]
no_license
package algorithm_array; public class ZigZagPrintMatrix { public static void ZigZagPrintMatrix(int[][] matrix) { if (matrix == null || matrix.length == 0) { return; } int row = matrix.length - 1; int col = matrix[0].length - 1; int row1 = 0; int col1 = 0; int row2 = 0; int col2 = 0; boolean isUp = true; while (col2 <= col) { ZigZagprint(matrix, row1, col1, row2, col2, isUp); isUp = !isUp; if (col1 < col) { col1++; } else { row1++; } if (row2 < row) { row2++; } else { col2++; } } } public static void ZigZagprint(int[][] matrix, int row1, int col1, int row2, int col2, boolean isUp) { if (isUp) { while (col2 != col1 + 1) { System.out.print(matrix[row2--][col2++] + " "); } } else { while (row1 != row2 + 1) { System.out.print(matrix[row1++][col1--] + " "); } } } public static void main(String[] args) { int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; ZigZagPrintMatrix(matrix); } }
true
576bd55e722e0f1507bedef4fe5a18139082f760
Java
young999999/young
/springBootDemo/src/test/java/com/example/demo/dao/ElasticsearchDao.java
UTF-8
426
1.585938
2
[]
no_license
package com.example.demo.dao; import com.example.demo.bean.ElasticsearchBean; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; /** * @author young * @create 2020-01-14 11:28 */ @Repository public interface ElasticsearchDao extends ElasticsearchRepository<ElasticsearchBean, String> { void sava(ElasticsearchBean elasticsearchBean); }
true
24daeb20e5c64cf102bfbd26c259ba6e128e3e1b
Java
rick0815/Metrik
/src/de/medieninformatik/prog3/PaintArea.java
UTF-8
3,425
3.671875
4
[]
no_license
package de.medieninformatik.prog3; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Ellipse2D; import static java.lang.String.valueOf; /** * Containing all Methods for the displaying circles, lines and calculating and displaying coordinates */ public class PaintArea extends Canvas implements MouseListener { int current_x=0, current_y=0; int new_x, new_y; int clickCount = 0; //counter for mouseclick float width = 20.0F; float height = 20.0F; public PaintArea() { setSize(400, 300); addMouseListener(this); } /** * Method that prints a Circle on given coordinates * clears the circles after the third call * @param g Graphics */ @Override public void paint(Graphics g) { Ellipse2D ellipse2D; ellipse2D = new Ellipse2D.Float( new_x-10.0F, new_y-10.0F,// Koordinaten 20.0F, 20.0F); // Größen Graphics2D gd2 = (Graphics2D)g; //Version 1.2.1 int distance = calculateDistance(current_x, current_y, new_x, new_y); //System.out.println(distance); gd2.drawString("Distance: " + distance, (current_x-30), (current_y-30)); if(new_x > 0) { gd2.draw(ellipse2D); if(current_x > 0){ gd2.drawLine(new_x,new_y, current_x,current_y); // draws line between the coordinates } gd2.drawString((new_x + " " + new_y), new_x, new_y); clickCount++; //System.out.println("newx " + new_x + " newy " + new_y + " currx " + current_x + " curry " + current_y); if (clickCount == 3) { clickCount = 0; PaintArea.this.repaint(); gd2.clearRect(new_x - 10, new_y - 10, 40, 40); gd2.clearRect(current_x - 10, current_y - 10, 40, 40); current_y = 0; current_x = 0; new_y = 0; new_x = 0; } else { current_x = new_x; current_y = new_y; } } } /** * Calculating the distance between two points. According to (https://www.baeldung.com/java-distance-between-two-points) * the distance is the root of the difference between point 1's x and y coordinates and point 2's coordinates. * @param x1 point 1's x * @param y1 point 1's y * @param x2 point 2's x * @param y2 point 2's y * @return the difference between the points, casted to int */ public static int calculateDistance(int x1, int y1, int x2, int y2) { return (int) Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1)); } /** * Method that saves the coordinates of a Mouse click and calls the paint-Method through the repaint-Method * @param e MouseEvent */ @Override public void mouseClicked(MouseEvent e) { new_x = e.getX(); new_y = e.getY(); Graphics g = this.getGraphics(); // Graphics from Canvas paint(g); // Paint-Method with g //this.repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
true
315015abde67555ea8e86b0b222dab83a920c63d
Java
programmerr47/discogs-api-java
/src/library/com/github/programmerr47/discogs/requestparams/SearchParams.java
UTF-8
8,931
2.3125
2
[ "MIT" ]
permissive
package library.com.github.programmerr47.discogs.requestparams; import library.com.github.programmerr47.discogs.utils.SearchType; /** * Class for representing search params in Discogs search requests. * <strong>See:</strong> http://www.discogs.com/developers/#page:database,header:database-search-get * * @author Michael Spitsin * @since 2014-08-15 */ @SuppressWarnings("unused") public class SearchParams extends PaginationParams{ private static final String SEARCH_QUERY_PARAM_NAME = "query"; private static final String TYPE_PARAM_NAME = "type"; private static final String TITLE_PARAM_NAME = "title"; private static final String RELEASE_TITLE_PARAM_NAME = "release_title"; private static final String RELEASE_CREDIT_PARAM_NAME = "credit"; private static final String ARTIST_TITLE_PARAM_NAME = "artist"; private static final String ARTIST_ANV_PARAM_NAME = "anv"; private static final String LABEL_TITLE_PARAM_NAME = "label"; private static final String GENRE_TITLE_PARAM_NAME = "genre"; private static final String STYLE_QUERY_PARAM_NAME = "style"; private static final String RELEASE_COUNTRY_PARAM_NAME = "country"; private static final String RELEASE_YEAR_PARAM_NAME = "year"; private static final String FORMAT_PARAM_NAME = "format"; private static final String CATALOG_NUMBER_PARAM_NAME = "catno"; private static final String BARCODE_PARAM_NAME = "barcode"; private static final String TRACK_TITLE_PARAM_NAME = "track"; private static final String SUBMITTER_PARAM_NAME = "submitter"; private static final String CONTRIBUTOR_PARAM_NAME = "contributor"; private String searchQuery; private SearchType type; private String title; private String releaseTitle; private String releaseCredit; private String artistTitle; private String artistANV; private String labelTitle; private String genreTitle; private String styleTitle; private String releaseCountry; private String releaseYear; private String format; private String catalogNumber; private String barcode; private String track; private String submitter; private String contributor; protected SearchParams(Builder builder) { super(builder); this.searchQuery = builder.searchQuery; this.type = builder.type; this.title = builder.title; this.releaseTitle = builder.releaseTitle; this.releaseCredit = builder.releaseCredit; this.artistTitle = builder.artistTitle; this.artistANV = builder.artistANV; this.labelTitle = builder.labelTitle; this.genreTitle = builder.genreTitle; this.styleTitle = builder.styleTitle; this.releaseCountry = builder.releaseCountry; this.releaseYear = builder.releaseYear; this.format = builder.format; this.catalogNumber = builder.catalogNumber; this.barcode = builder.barcode; this.track = builder.track; this.submitter = builder.submitter; this.contributor = builder.contributor; } @Override public String getQuery() { StringBuilder result = new StringBuilder(super.getQuery()); ParamUtils.addParameterIfNeed(result, SEARCH_QUERY_PARAM_NAME, searchQuery); ParamUtils.addParameterIfNeed(result, TYPE_PARAM_NAME, type); ParamUtils.addParameterIfNeed(result, TITLE_PARAM_NAME, title); ParamUtils.addParameterIfNeed(result, RELEASE_TITLE_PARAM_NAME, releaseTitle); ParamUtils.addParameterIfNeed(result, RELEASE_CREDIT_PARAM_NAME, releaseCredit); ParamUtils.addParameterIfNeed(result, ARTIST_TITLE_PARAM_NAME, artistTitle); ParamUtils.addParameterIfNeed(result, ARTIST_ANV_PARAM_NAME, artistANV); ParamUtils.addParameterIfNeed(result, LABEL_TITLE_PARAM_NAME, labelTitle); ParamUtils.addParameterIfNeed(result, GENRE_TITLE_PARAM_NAME, genreTitle); ParamUtils.addParameterIfNeed(result, STYLE_QUERY_PARAM_NAME, styleTitle); ParamUtils.addParameterIfNeed(result, RELEASE_COUNTRY_PARAM_NAME, releaseCountry); ParamUtils.addParameterIfNeed(result, RELEASE_YEAR_PARAM_NAME, releaseYear); ParamUtils.addParameterIfNeed(result, FORMAT_PARAM_NAME, format); ParamUtils.addParameterIfNeed(result, CATALOG_NUMBER_PARAM_NAME, catalogNumber); ParamUtils.addParameterIfNeed(result, BARCODE_PARAM_NAME, barcode); ParamUtils.addParameterIfNeed(result, TRACK_TITLE_PARAM_NAME, track); ParamUtils.addParameterIfNeed(result, SUBMITTER_PARAM_NAME, submitter); ParamUtils.addParameterIfNeed(result, CONTRIBUTOR_PARAM_NAME, contributor); return ParamUtils.removeFirstCharacterIfDelimiter(result.toString()); } public static class Builder extends PaginationParams.Builder { private String searchQuery; private SearchType type; private String title; private String releaseTitle; private String releaseCredit; private String artistTitle; private String artistANV; private String labelTitle; private String genreTitle; private String styleTitle; private String releaseCountry; private String releaseYear; private String format; private String catalogNumber; private String barcode; private String track; private String submitter; private String contributor; @SuppressWarnings("unused") public Builder setSearchQuery(String searchQuery) { this.searchQuery = searchQuery; return this; } @SuppressWarnings("unused") public Builder setType(SearchType type) { this.type = type; return this; } @SuppressWarnings("unused") public Builder setTitle(String title) { this.title = title; return this; } @SuppressWarnings("unused") public Builder setReleaseTitle(String releaseTitle) { this.releaseTitle = releaseTitle; return this; } @SuppressWarnings("unused") public Builder setReleaseCredit(String releaseCredit) { this.releaseCredit = releaseCredit; return this; } @SuppressWarnings("unused") public Builder setArtistTitle(String artistTitle) { this.artistTitle = artistTitle; return this; } @SuppressWarnings("unused") public Builder setArtistANV(String artistANV) { this.artistANV = artistANV; return this; } @SuppressWarnings("unused") public Builder setLabelTitle(String labelTitle) { this.labelTitle = labelTitle; return this; } @SuppressWarnings("unused") public Builder setGenreTitle(String genreTitle) { this.genreTitle = genreTitle; return this; } @SuppressWarnings("unused") public Builder setStyleTitle(String styleTitle) { this.styleTitle = styleTitle; return this; } @SuppressWarnings("unused") public Builder setReleaseCountry(String releaseCountry) { this.releaseCountry = releaseCountry; return this; } @SuppressWarnings("unused") public Builder setReleaseYear(String releaseYear) { this.releaseYear = releaseYear; return this; } @SuppressWarnings("unused") public Builder setFormat(String format) { this.format = format; return this; } @SuppressWarnings("unused") public Builder setCatalogNumber(String catalogNumber) { this.catalogNumber = catalogNumber; return this; } @SuppressWarnings("unused") public Builder setBarcode(String barcode) { this.barcode = barcode; return this; } @SuppressWarnings("unused") public Builder setTrack(String track) { this.track = track; return this; } @SuppressWarnings("unused") public Builder setSubmitter(String submitter) { this.submitter = submitter; return this; } @SuppressWarnings("unused") public Builder setContributor(String contributor) { this.contributor = contributor; return this; } @Override public Builder setCurrentPage(int currentPage) { return (Builder) super.setCurrentPage(currentPage); } @Override public Builder setItemCountPerPage(int itemCountPerPage) { return (Builder) super.setItemCountPerPage(itemCountPerPage); } public SearchParams build() { return new SearchParams(this); } } }
true
2a2bb14bff1696a7fe55f7cdc840e2231eca401a
Java
KyleAMathews/intex2k
/Intex2/src/edu/byu/isys413/cbb54/intex2/data/tester.java
UTF-8
30,895
2.921875
3
[]
no_license
/* * tester.java * * Created on February 21, 2007, 4:18 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package edu.byu.isys413.cbb54.intex2.data; import java.math.RoundingMode; import java.sql.*; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.*; /** * A simple tester class for my data layer. * * @author Conan C. Albrecht */ public class tester { public void main(String args[]) { try { // clear out the database (you'd never do this in production) Connection conn = ConnectionPool.getInstance().get(); Statement stmt = conn.createStatement(); stmt.executeUpdate("DELETE FROM \"customer\" "); stmt.executeUpdate("DELETE FROM \"membership\" "); stmt.executeUpdate("DELETE FROM \"interest\" "); stmt.close(); conn.commit(); ConnectionPool.getInstance().release(conn); /** * * TEST CUSTOMERS * */ System.out.println("CUSTOMER TESTING"); // create a test customer Customer cust1 = CustomerDAO.getInstance().create(); cust1.setFname("Test"); cust1.setLname("Entry"); cust1.setAddress1("123 Somewhere"); cust1.setAddress2(null); cust1.setCity("Over The"); cust1.setState("Rainbow"); cust1.setZip("12345"); cust1.setPhone("5555555555"); cust1.setEmail("jollypeople@mymonkeylovesme.com"); CustomerDAO.getInstance().save(cust1); Customer cust2 = CustomerDAO.getInstance().create(); cust2.setFname("Test"); cust2.setLname("Entry"); cust2.setAddress1("123 Somewhere"); cust2.setAddress2(null); cust2.setCity("Over The"); cust2.setState("Rainbow"); cust2.setZip("12345"); cust2.setPhone("3456443454"); CustomerDAO.getInstance().save(cust2); // test that the exact same object will come out of the cache if asked for Customer cust3 = CustomerDAO.getInstance().read(cust1.getId()); System.out.println("cust1==cust2 -> " + (cust1 == cust3)); // test if all three customer objects are in the Cache System.out.println("cust1 in Cache -> " + Cache.getInstance().containsKey(cust1.getId()) ); System.out.println("cust2 in Cache -> " + Cache.getInstance().containsKey(cust2.getId()) ); System.out.println("cust3 in Cache -> " + Cache.getInstance().containsKey(cust3.getId()) ); // test the update(save) cust2.setFname("Tester"); cust2.setPhone("1234567890"); CustomerDAO.getInstance().save(cust2); // test getAll() List allCustomers = (List)CustomerDAO.getInstance().getAll(); System.out.println(allCustomers.size()); for(int i = 0; i < allCustomers.size(); i++){ List temp = (List)allCustomers.get(i); System.out.println( temp.get(1).toString() + " " + temp.get(2).toString() + " " + temp.get(3).toString()); } // test getByName() List testCustomer = (List)CustomerDAO.getInstance().getByName("Test","Entry"); for(int i = 0; i < testCustomer.size(); i++){ Customer custTest = (Customer)testCustomer.get(i); System.out.println("Finding customer by name \"Test Entry\" :" + custTest.getFname() + " " + custTest.getLname() ); } // test getByPhone() List testCustPhone = (List)CustomerDAO.getInstance().getByPhone("1234567890"); for(int i = 0; i < testCustPhone.size(); i++){ Customer custPhone = (Customer)testCustPhone.get(i); System.out.println("Finding Customer by phone \"1234567890\" :" + custPhone.getFname() + " " + custPhone.getLname() ); } /** * * TEST MEMBERSHIP * */ System.out.println("\n\nMEMBERSHIP TESTING"); // create a test customer Membership mem1 = MembershipDAO.getInstance().create(cust1.getId()); mem1.setStartDate("1-jul-2006"); mem1.setEndDate("1-jul-2007"); mem1.setCreditCard("1234567890123456"); mem1.setCcExpiration("06/07"); mem1.setCustomer(cust1); mem1.setNewsletter(true); mem1.setBackupSize(2); mem1.setBackupExpDate(System.currentTimeMillis() + 123123); mem1.setInterests(null); MembershipDAO.getInstance().save(mem1); cust1.setMembership(mem1); Membership mem2 = MembershipDAO.getInstance().create(cust2.getId()); mem2.setStartDate("1-jul-2006"); mem2.setEndDate("1-jul-2007"); mem2.setCreditCard("9934567890123456"); mem2.setCcExpiration("06/07"); mem2.setCustomer(cust2); mem1.setBackupSize(2); mem1.setBackupExpDate(System.currentTimeMillis() + 123123); mem2.setNewsletter(true); mem2.setInterests(null); MembershipDAO.getInstance().save(mem2); // test that the exact same object will come out of the cache if asked for Membership mem3 = MembershipDAO.getInstance().read(mem1.getId()); System.out.println("mem1==mem3 -> " + (mem1 == mem3)); // test if all three customer objects are in the Cache System.out.println("mem1 in Cache -> " + Cache.getInstance().containsKey(mem1.getId()) ); System.out.println("mem2 in Cache -> " + Cache.getInstance().containsKey(mem2.getId()) ); System.out.println("mem3 in Cache -> " + Cache.getInstance().containsKey(mem3.getId()) ); // test the update(save) mem2.setEndDate("never"); MembershipDAO.getInstance().save(mem2); // test getByCustomerID() Membership testMembership = (Membership)MembershipDAO.getInstance().getByCustomerID(cust1.getId(),conn); System.out.println("The membership retrieved from cust1's ID is " + testMembership.getId()); /** * * TEST INTERESTS * */ System.out.println("\n\nINTERESTS"); // create a test interests Interest interest1 = InterestDAO.getInstance().create(); interest1.setTitle("B&W Photography"); interest1.setDescription("The art of black and white photography"); InterestDAO.getInstance().save(interest1); Interest interest2 = InterestDAO.getInstance().create(); interest2.setTitle("HDR photographs"); interest2.setDescription("The technique of High Dynamic Range photographs"); InterestDAO.getInstance().save(interest2); // test that the exact same object will come out of the cache if asked for Interest interest3 = InterestDAO.getInstance().read(interest1.getId()); System.out.println("interest1==interest3 -> " + (interest1 == interest3)); // test if all three customer objects are in the Cache System.out.println("interest1 in Cache -> " + Cache.getInstance().containsKey(interest1.getId()) ); System.out.println("interest2 in Cache -> " + Cache.getInstance().containsKey(interest2.getId()) ); System.out.println("interest3 in Cache -> " + Cache.getInstance().containsKey(interest3.getId()) ); // test the update(save) interest2.setTitle("HDR Photography"); InterestDAO.getInstance().save(interest2); // test getAll() List allInterests = (List)InterestDAO.getInstance().getAll(); System.out.println(allInterests.size()); for(int i = 0; i < allInterests.size(); i++){ List temp = (List)allInterests.get(i); System.out.println( temp.get(0).toString() + " " + temp.get(1).toString() + " " + temp.get(2).toString()); } /** * * TEST MEMBER/INTERESTS * */ System.out.println("\n\nTEST MEMBER/INTERESTS"); // create a test interest list List<String> intList = new LinkedList<String>(); intList.add(interest1.getId()); intList.add(interest2.getId()); // send list with membership 1 MemberInterestDAO.getInstance().create(mem1.getId(), intList); // retrieve interests for membership 1 List<String> mem1list = MemberInterestDAO.getInstance().read(mem1.getId(),conn); System.out.println("Interests for Member 1 :"); for(int i = 0; i < mem1list.size(); i++){ Interest interest = InterestDAO.getInstance().read(mem1list.get(i)); System.out.println("\t" + interest.getTitle()); } /** * TESTING THE RESAVE OF CASCADE * */ System.out.println("\n\nTESTING THE CASCADE"); try{ MembershipDAO.getInstance().save(mem1); CustomerDAO.getInstance().save(cust2); System.out.println("Success"); }catch (Exception e1){ throw new Exception(e1); } /** * * TESTING THE CREATION AND RETRIEVALE OF EMPLOYEE */ System.out.println("\n\nEMPLOYEE\n"); System.out.println("Reading Employee from the database"); Employee emp = EmployeeDAO.getInstance().read("000001117284553c0014b10a500442"); System.out.println("Employee name: " + emp.getFname() +" " + emp.getLname()); System.out.println("\nCreating new employee"); Employee NewEmp = EmployeeDAO.getInstance().create(); NewEmp.setFname("New"); NewEmp.setLname("Employee"); NewEmp.setAddress1("123 Another Street"); NewEmp.setAddress2("Appartment 3"); NewEmp.setCity("Orem"); NewEmp.setState("Utah"); NewEmp.setZip("84569"); NewEmp.setPhone("801-666-7777"); NewEmp.setEmail("New@Employee.com"); NewEmp.setSsNumber("0987-65-4321"); NewEmp.setHireDate("05/04"); NewEmp.setSalary(4578.00); NewEmp.setStoreID("000001117284553c0014b20a500442"); EmployeeDAO.getInstance().save(NewEmp); System.out.println("New employee name: " + NewEmp.getFname() + " " + NewEmp.getLname()); /** * * Testing the STORE * */ System.out.println("\n\nSTORE\n"); Store store = StoreDAO.getInstance().read("000001117284553c0014b20a500442"); System.out.println("Reading store from the database"); System.out.println(store.getName()); System.out.println("\nCreating new Store"); Store NewStore = StoreDAO.getInstance().create(); NewStore.setName("Orem Central"); NewStore.setAddress1("457 Center Street"); NewStore.setAddress2("Suite 5"); NewStore.setCity("Orem"); NewStore.setState("Utah"); NewStore.setZip("25686"); NewStore.setPhone("456-756-3446"); NewStore.setFax("342-443-4343"); NewStore.setManagerID(NewEmp.getId()); StoreDAO.getInstance().save(NewStore); System.out.println("New Store name: " + NewStore.getName()); Employee manager = EmployeeDAO.getInstance().read(NewStore.getManagerID()); System.out.println("New Store manager: " + manager.getFname() + " " + manager.getLname()); /** * * TESTING THE SESSION * */ System.out.println("\n\nSESSION\n"); System.out.println("Creating new Session"); Session session = new Session(NewStore, NewEmp); System.out.println("New session store: " + session.getStore().getName() + " \nNew Session Employee: " + session.getEmployee().getFname() + " " + session.getEmployee().getLname()); /** * * TESTING THE TRANSACTION * */ System.out.println("\n\nTRANSACTION\n"); System.out.println("Creating new Transaction"); Transaction tx = TransactionDAO.getInstance().create(); tx.setCustomer(cust1); tx.setEmployee(session.getEmployee()); tx.setStore(session.getStore()); tx.setStatus("pending"); tx.setType("Sale"); /** * * TESTING TRANSACTIONLINE * */ /* System.out.println("Creating a new backup TransactionLine"); TransactionLine txLine1 = TransactionLineDAO.getInstance().create(tx, "ba"); System.out.println("Creating a new Photo Order TransactionLine"); TransactionLine txLine2 = TransactionLineDAO.getInstance().create(tx, "po"); System.out.println("Creating a new Rental TransactionLine"); TransactionLine txLine3 = TransactionLineDAO.getInstance().create(tx, "rn"); System.out.println("Creating a new Repair TransactionLine"); TransactionLine txLine5 = TransactionLineDAO.getInstance().create(tx, "rp"); System.out.println("Creating a new Sale TransactionLine"); TransactionLine txLine6 = TransactionLineDAO.getInstance().create(tx, "34820842342"); System.out.println("Adding TransactionLines to Transaction"); List<TransactionLine> txLineList = new LinkedList<TransactionLine>(); txLineList.add(txLine1); txLineList.add(txLine2); tx.setTxLines(txLineList); /** * * TESTING REVENUESOURCE * */ /* System.out.println("\n\nTESTING REVENUESOURCE\n"); System.out.println("\n"); //System.out.println("Read backupRS = orignal: " + (txLine1.getRevenueSource().getId() == ((RevenueSource)Cache.getInstance().get(txLine1.getRevenueSource())).getId())); System.out.println("Read backupRS = orignal: " + (txLine1.getRevenueSource().getId() == RevenueSourceDAO.getInstance().read(txLine1.getRevenueSource().getId()).getId())); System.out.println("Read PhotoOrderRS = orginal: " + (txLine2.getRevenueSource().getId() == RevenueSourceDAO.getInstance().read(txLine2.getRevenueSource().getId()).getId())); System.out.println("Read RentalRS = orginal: " + (txLine3.getRevenueSource().getId() == RevenueSourceDAO.getInstance().read(txLine3.getRevenueSource().getId()).getId())); System.out.println("Read RepairRS = orginal: " + (txLine5.getRevenueSource().getId() == RevenueSourceDAO.getInstance().read(txLine5.getRevenueSource().getId()).getId())); System.out.println("Read SaleRS = orginal: " + (txLine6.getRevenueSource().getId() == RevenueSourceDAO.getInstance().read(txLine6.getRevenueSource().getId()).getId())); txLine1.getRevenueSource().setPrice(12); System.out.println("Saving backupRS: "); RevenueSourceDAO.getInstance().save(txLine1.getRevenueSource()); */ /** *TESTING PrintOrder (includes PhotoSet, PrintFormat) * */ PhotoSet ps = PhotoSetDAO.getInstance().create(); ps.setDescription("Test photoset"); ps.setNumPhotos(3); //PhotoSetDAO.getInstance().save(ps); PhotoSet ps2 = PhotoSetDAO.getInstance().create(); ps2.setDescription("Test photoset 2"); ps2.setNumPhotos(5); PhotoSetDAO.getInstance().save(ps2); PhotoSet ps3 = PhotoSetDAO.getInstance().read(ps2.getId()); System.out.println("ps2==ps3 -> " + (ps2 == ps3)); // test if all three customer objects are in the Cache System.out.println("ps in Cache -> " + Cache.getInstance().containsKey(ps.getId()) ); System.out.println("ps2 in Cache -> " + Cache.getInstance().containsKey(ps2.getId()) ); System.out.println("ps3 in Cache -> " + Cache.getInstance().containsKey(ps3.getId()) ); // test the update(save) ps.setDescription("HDR Photography"); PhotoSetDAO.getInstance().save(ps); //PRINT FORMAT printFormat pf = printFormatDAO.getInstance().create(); pf.setSize("3x5"); pf.setPaperType("Glossy"); pf.setSourceType("Film"); pf.setPrice(.30); printFormatDAO.getInstance().save(pf); printFormat pf2 = printFormatDAO.getInstance().create(); pf2.setSize("4x6"); pf2.setPaperType("matte"); pf2.setSourceType("Digital"); pf2.setPrice(.33); printFormatDAO.getInstance().save(pf2); printFormat pf3 = printFormatDAO.getInstance().read(pf2.getId()); System.out.println("pf2==pf3 -> " + (pf2 == pf3)); // test if all three customer objects are in the Cache System.out.println("pf in Cache -> " + Cache.getInstance().containsKey(pf.getId()) ); System.out.println("pf2 in Cache -> " + Cache.getInstance().containsKey(pf2.getId()) ); System.out.println("pf3 in Cache -> " + Cache.getInstance().containsKey(pf3.getId()) ); pf2.setPaperType("Other"); printFormatDAO.getInstance().save(pf2); //PRINT ORDER printOrder po = (printOrder)PrintOrderDAO.getInstance().create(); po.setPhotoSet(PhotoSetDAO.getInstance().read(ps.getId())); po.setPrintFormat(printFormatDAO.getInstance().read(pf.getId())); po.setQuantity(3); po.setPrice((po.getPrintFormat().getPrice() * po.getQuantity())); RevenueSourceDAO.getInstance().save(po); /* *Testing ConversionOrder (includes conversiontype) */ conversionTypeBO ct = conversionTypeDAO.getInstance().create(); ct.setDestinationType("DVD"); ct.setSourceType("VHS"); ct.setPrice(.1); conversionTypeDAO.getInstance().save(ct); conversionTypeBO ct2 = conversionTypeDAO.getInstance().create(); ct.setDestinationType("MP4"); ct.setSourceType("VHS"); ct.setPrice(.4); conversionTypeDAO.getInstance().save(ct); conversionTypeBO ct3 = conversionTypeDAO.getInstance().read(ct2.getId()); System.out.println("ct2==ct3 -> " + (ct2 == ct3)); // test if all three customer objects are in the Cache System.out.println("ct in Cache -> " + Cache.getInstance().containsKey(ct.getId()) ); System.out.println("ct2 in Cache -> " + Cache.getInstance().containsKey(ct2.getId()) ); System.out.println("ct3 in Cache -> " + Cache.getInstance().containsKey(ct3.getId()) ); ct.setDestinationType("Gold"); conversionTypeDAO.getInstance().save(ct); conversionBO conv = (conversionBO)ConversionDAO.getInstance().create(); conv.setConversionType(ct); conv.setQuantity(60); conv.setPrice((conv.getQuantity() * conv.getConversionType().getPrice())); RevenueSourceDAO.getInstance().save(conv); // /** // * // * TESTING COUPON // * // */ // // System.out.println("Creating a new Coupon"); // // Coupon c = CouponDAO.getInstance().create(); // c.setAmount(0.50); // // System.out.println("Apply coupon to transaction => txLine1"); // txLine1.setCoupon(c); // // /** // * // * TESTING THE CALCULATION METHODS // * // */ // // double subtotal = Math.floor( tx.calculateSubtotal() * 100 + .5) / 100; // double tax = Math.floor( tx.calculateTax() * 100 + .5) / 100; // double total = tax + subtotal; // System.out.println("Subtotal = \t$" + fmt(subtotal)); // System.out.println("Tax = \t\t$" + fmt(tax)); // System.out.println("Total = \t$" + fmt(total)); // // /** // * // * TESTING PAYMENT // * // */ // // System.out.println("\nCreating a new Payment"); // Payment p = PaymentDAO.getInstance().create(tx, 15.00, "cash"); // // System.out.println("Payment Amount:\t$" + fmt(p.getAmount())); // System.out.println("Change:\t\t$" + fmt(p.getChange())); // // System.out.println("Setting payment to Transaction"); // tx.setPayment(p); // // tx.setStatus("complete"); // UpdateController.getInstance().saveTransaction(tx); // // // // // // /** // * // * TESTING THE TRANSACTION HOLD // * // */ // // System.out.println("\n\nTRANSACTION HOLD\n"); // System.out.println("Creating new Transaction"); // // Transaction txH = TransactionDAO.getInstance().create(); // txH.setCustomer(cust1); // txH.setEmployee(session.getEmployee()); // txH.setStore(session.getStore()); // txH.setStatus("pending"); // txH.setType("Sale"); // // /** // * // * TESTING REVENUESOURCE // * // */ // // System.out.println("Creating a new RevenueSource"); // //RevenueSource rsH = new RevenueSource("00000111760997ae0166c80a0446dd"); // // /** // * // * TESTING TRANSACTIONLINE // * // */ // // System.out.println("Creating a new TransactionLine"); // TransactionLine txHLine1 = TransactionLineDAO.getInstance().create(txH); // //txHLine1.setRevenueSource(rs); // // System.out.println("Adding TransactionLines to Transaction"); // List<TransactionLine> txHLineList = new LinkedList<TransactionLine>(); // // txHLineList.add(txHLine1); // // txH.setTxLines(txHLineList); // // /** // * // * TESTING THE CALCULATION METHODS // * // */ // // double subtotalH = Math.floor( txH.calculateSubtotal() * 100 + .5) / 100; // double taxH = Math.floor( txH.calculateTax() * 100 + .5) / 100; // double totalH = taxH + subtotalH; // System.out.println("Subtotal = \t$" + fmt(subtotalH)); // System.out.println("Tax = \t\t$" + fmt(taxH)); // System.out.println("Total = \t$" + fmt(totalH)); // // System.out.println("Saving transaction Hold"); // // UpdateController.getInstance().saveTransaction(txH); // // // System.out.println("\n\nRetrieving the hold Transaction"); // Transaction txH1 = TransactionDAO.getInstance().read(txH.getId()); // // double subtotalH1 = Math.floor( txH1.calculateSubtotal() * 100 + .5) / 100; // double taxH1 = Math.floor( txH1.calculateTax() * 100 + .5) / 100; // double totalH1 = taxH1 + subtotalH1; // System.out.println("Subtotal = \t$" + fmt(subtotalH1)); // System.out.println("Tax = \t\t$" + fmt(taxH1)); // System.out.println("Total = \t$" + fmt(totalH1)); // // // /** // * // * TESTING PAYMENT // * // */ // // System.out.println("\nCreating a new Payment"); // Payment pH = PaymentDAO.getInstance().create(txH1, 3.00, "Cash"); // // System.out.println("Setting payment to Transaction"); // tx.setPayment(pH); // // System.out.println("Payment Amount:\t$" + fmt(pH.getAmount())); // System.out.println("Change:\t\t$" + fmt(pH.getChange())); // // txH1.setStatus("complete"); // UpdateController.getInstance().saveTransaction(txH1); // // // /** // * // * TESTING THE TRANSACTION VOID // * // */ // // System.out.println("\n\nTRANSACTION VOID\n"); // System.out.println("Creating new Transaction"); // // Transaction txV = TransactionDAO.getInstance().create(); // txV.setCustomer(cust1); // txV.setEmployee(session.getEmployee()); // txV.setStore(session.getStore()); // txV.setStatus("pending"); // txV.setType("Sale"); // // /** // * // * TESTING REVENUESOURCE // * // */ // // System.out.println("Creating a new RevenueSource"); // //RevenueSource rsV = new RevenueSource("00000111760997ae0166c80a0446dd"); // // /** // * // * TESTING TRANSACTIONLINE // * // */ // // System.out.println("Creating a new TransactionLine"); // TransactionLine txLineV = TransactionLineDAO.getInstance().create(txV); // //txLineV.setRevenueSource(rs); // // System.out.println("Adding TransactionLines to Transaction"); // List<TransactionLine> txLineListV = new LinkedList<TransactionLine>(); // // txLineListV.add(txLineV); // // // txV.setTxLines(txLineListV); // // /** // * // * TESTING THE CALCULATION METHODS // * // */ // // double subtotalV = Math.floor( txV.calculateSubtotal() * 100 + .5) / 100; // double taxV = Math.floor( txV.calculateTax() * 100 + .5) / 100; // double totalV = taxV + subtotalV; // System.out.println("Subtotal = \t$" + fmt(subtotalV)); // System.out.println("Tax = \t\t$" + fmt(taxV)); // System.out.println("Total = \t$" + fmt(totalV)); // // System.out.println("Setting the transaction as VOID"); // txV.setStatus("void"); // System.out.println("Saving transaction Void"); // // UpdateController.getInstance().saveTransaction(txV); // // /** // * RETURN TEST // * // */ // // System.out.println("\n\nReturn Test"); // Transaction org = TransactionDAO.getInstance().read(txH1.getId()); // // Transaction rtn = TransactionDAO.getInstance().create(org); // // System.out.println("Returning transactionLine #1"); // TransactionLine orl = rtn.getOrig().getTxLines().get(0); // TransactionLine rtl = TransactionLineDAO.getInstance().create(rtn); // // System.out.println("Creating new Return RevenueSource"); // //RevenueSource rrs = new RevenueSource("9874928374982374"); // //rrs.setType("return"); // double origPrice = -orl.getRevenueSource().getPrice(); // //rrs.setPrice(origPrice); // // System.out.println("Applying return RevenueSource to return TransactionLine"); // //rtl.setRevenueSource(rrs); // // System.out.println("Applying the TransactionLine to the Transaction"); // List<TransactionLine> txLineListR = new LinkedList<TransactionLine>(); // txLineListR.add(rtl); // rtn.setTxLines(txLineListR); // // double subtotalR = Math.floor( rtn.calculateSubtotal() * 100 + .5) / 100; // double taxR = Math.floor( rtn.calculateTax() * 100 + .5) / 100; // double totalR = taxR + subtotalR; // System.out.println("Subtotal = \t$" + fmt(subtotalR)); // System.out.println("Tax = \t\t$" + fmt(taxR)); // System.out.println("Total = \t$" + fmt(totalR)); // // System.out.println("\nCreating a new Payment"); // Payment pr = PaymentDAO.getInstance().create(rtn, totalR, "Cash"); // // System.out.println("Setting payment to Transaction"); // rtn.setPayment(pr); // // System.out.println("Payment Amount:\t$" + fmt(pr.getAmount())); // System.out.println("Change:\t\t$" + fmt(pr.getChange())); // // // //System.out.println("Setting the transaction as VOID"); // System.out.println("Saving return transaction"); // // rtn.setStatus("complete"); // UpdateController.getInstance().saveTransaction(rtn); // /** // * // * TIME TEST // * // */ // System.out.println("\n\nCURRENT DAY"); // SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yy", Locale.US); // System.out.println(fmt.format(System.currentTimeMillis()) + " "); }catch(Exception e) { e.printStackTrace(); } }//main private String fmt(double number) { DecimalFormat formatter = new DecimalFormat("###,##0.00"); return formatter.format(number); } }//class
true
c9429c0b3fdeba8a5e79437cdd294f107699ac03
Java
t0mk0us/algorithms
/Factorial.java
UTF-8
939
3.609375
4
[]
no_license
package tomkous.algos; import java.util.Scanner; public class Factorial { public static int findFactorial(int number){ int resNumber=number; for(int i = number-1; i > 1; i--){ resNumber = resNumber * i; } return resNumber; } public static int findFactorialRecursive(int number){ int resNumber=number; number -= 1; if (number > 1) resNumber = resNumber * findFactorialRecursive(number); return resNumber; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("please enter a number"); int nmbr = Integer.valueOf(sc.nextLine()); System.out.println("iteration " + findFactorial(nmbr)); System.out.println("recursion " + findFactorialRecursive(nmbr)); } }
true
0ef0d40e4e79d15f704d8e1c07b7868a304f44fb
Java
otonglet/genesis
/src/main/java/be/genesis/dto/Company.java
UTF-8
781
2.09375
2
[]
no_license
package be.genesis.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.util.HashSet; import java.util.Set; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Company { @NotBlank @Pattern(regexp = "^\\d{10}$") private String vatNr; @Builder.Default @NotNull @Valid private Set<@Valid Contact> contacts = new HashSet<>(); // TODO add validation that at least one address is the HQ @Builder.Default @NotNull @Valid private Set<CompanyAddress> addresses = new HashSet<>(); }
true
7f233eca5f63e3f037aad308f042de7831d77e66
Java
MagicalHorse/Android_App_Studio
/joybar/src/main/java/com/shenma/yueba/baijia/view/PubuliuManager.java
UTF-8
10,201
2.1875
2
[]
no_license
package com.shenma.yueba.baijia.view; import java.util.List; import com.shenma.yueba.R; import com.shenma.yueba.application.MyApplication; import com.shenma.yueba.baijia.modle.MyFavoriteProductListInfo; import com.shenma.yueba.baijia.modle.MyFavoriteProductListPic; import com.shenma.yueba.util.HttpControl; import com.shenma.yueba.util.HttpControl.HttpCallBackInterface; import com.shenma.yueba.util.ToolsUtil; import com.umeng.socialize.utils.Log; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.TextView; /** * @author gyj * @version 创建时间:2015-6-9 下午2:48:26 * 程序的简单说明 瀑布流管理 */ public class PubuliuManager { Context context; View parent; //瀑布流 左右布局 LinearLayout pubuliy_left_linearlayout,pubuliy_right_linearlayout; int leftHeight;//左侧高度 int rightHeight;//右侧高度 HttpControl httpControl=new HttpControl(); PubuliuInterfaceListener pubuliuInterfaceListener; public PubuliuInterfaceListener getPubuliuInterfaceListener() { return pubuliuInterfaceListener; } public void setPubuliuInterfaceListener(PubuliuInterfaceListener pubuliuInterfaceListener) { this.pubuliuInterfaceListener = pubuliuInterfaceListener; } public PubuliuManager(Context context,View parent) { this.context=context; this.parent=parent; initView(); } /*** * 加载视图 * **/ void initView() { pubuliy_left_linearlayout=(LinearLayout)parent.findViewById(R.id.pubuliy_left_linearlayout); pubuliy_right_linearlayout=(LinearLayout)parent.findViewById(R.id.pubuliy_right_linearlayout); } /**** * 设置刷新 * @param item List<MyFavoriteProductListInfo> * ***/ public void onResher(List<MyFavoriteProductListInfo> item) { leftHeight=0; rightHeight=0; pubuliy_left_linearlayout.removeAllViews(); pubuliy_right_linearlayout.removeAllViews(); addItem(item); } /**** * 加载数据 * @param item List<MyFavoriteProductListInfo> * ****/ public void onaddData(List<MyFavoriteProductListInfo> item) { addItem(item); } /******* * 设置 瀑布流的 高度 * * *****/ void addItem(List<MyFavoriteProductListInfo> item) { if(item!=null) { for(int i=0;i<item.size();i++) { MyFavoriteProductListInfo bean=item.get(i); //左侧布局的宽度(即内部图片的 宽度) int witdh=pubuliy_left_linearlayout.getWidth(); MyFavoriteProductListPic myFavoriteProductListPic=bean.getPic(); if(myFavoriteProductListPic==null) { myFavoriteProductListPic=new MyFavoriteProductListPic(); } //根据 图片的宽高比 计算出 图片的 高度 int height=(int)(witdh*myFavoriteProductListPic.getRatio()); //图片的布局对象 View parentview=LinearLayout.inflate(context, R.layout.pubuliu_item_layout, null); //价格 TextView pubuliu_item_layout_pricevalue_textview=(TextView)parentview.findViewById(R.id.pubuliu_item_layout_pricevalue_textview); pubuliu_item_layout_pricevalue_textview.setText(bean.getPrice()+""); //商品名称 TextView pubuliu_item_layout_name_textview=(TextView)parentview.findViewById(R.id.pubuliu_item_layout_name_textview); pubuliu_item_layout_name_textview.setText(bean.getName()); //收藏 LinearLayout pubuliu_item_layout_like_linearlayout=(LinearLayout)parentview.findViewById(R.id.pubuliu_item_layout_like_linearlayout); TextView pubuliu_item_layout_like_textview=(TextView)parentview.findViewById(R.id.pubuliu_item_layout_like_textview); ImageView pubuliu_item_layout_like_imageview=(ImageView)parentview.findViewById(R.id.pubuliu_item_layout_like_imageview); pubuliu_item_layout_like_linearlayout.setOnClickListener(onClickListener); pubuliu_item_layout_like_imageview.setSelected(bean.isIsFavorite()); pubuliu_item_layout_like_textview.setText(Integer.toString(bean.getFavoriteCount())); pubuliu_item_layout_like_linearlayout.setTag(bean); /*if(bean.getLikeUser()!=null) { MyFavoriteProductListLikeUser likeuser=bean.getLikeUser(); pubuliu_item_layout_like_textview.setSelected(likeuser.isIsLike()); pubuliu_item_layout_like_textview.setText(likeuser.getCount()+""); pubuliu_item_layout_like_textview.setTag(bean); }*/ ImageView iv=(ImageView)parentview.findViewById(R.id.pubuliu_item_layout_imageview); if(height>0) { Log.i("TAG", "height="+height +" witdh="+witdh +"ration="+myFavoriteProductListPic.getRatio()); //设置 图片的高度 iv.getLayoutParams().height=height; }else { height=witdh; Log.i("TAG", "height="+height +" witdh="+witdh +"ration="+myFavoriteProductListPic.getRatio()); //设置 图片的高度 iv.getLayoutParams().height=height; } iv.setTag(bean); iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(v.getTag()==null) { return; } MyFavoriteProductListInfo bean=(MyFavoriteProductListInfo)v.getTag(); ToolsUtil.forwardProductInfoActivity(context,bean.getId()); } }); iv.setImageResource(R.drawable.default_pic); iv.setScaleType(ScaleType.CENTER_CROP); android.util.Log.i("TAG", "leftHeight="+leftHeight+" rightHeight="+rightHeight); //根据 左右高度判断 if(leftHeight<=rightHeight) { leftHeight+=height; pubuliy_left_linearlayout.addView(parentview, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); }else { rightHeight+=height; pubuliy_right_linearlayout.addView(parentview, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); } ToolsUtil.setFontStyle(context, parentview, R.id.pubuliu_item_layout_pricevalue_textview,R.id.pubuliu_item_layout_name_textview,R.id.pubuliu_item_layout_like_textview,R.id.pubuliu_item_layout_price_textview); initPic(ToolsUtil.getImage(ToolsUtil.nullToString(myFavoriteProductListPic.getPic()), 320, 0), iv); } } } OnClickListener onClickListener=new OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.pubuliu_item_layout_like_linearlayout: if(v.getTag()!=null && v.getTag() instanceof MyFavoriteProductListInfo) { MyFavoriteProductListInfo bean=(MyFavoriteProductListInfo)v.getTag(); if(bean.isIsFavorite()) { submitAttention(0,bean,v); }else { submitAttention(1,bean,v); } } break; } } }; /**** * 加载图片 * */ void initPic(final String url, final ImageView iv) { MyApplication.getInstance().getBitmapUtil().display(iv, url); } /**** * 提交收藏与取消收藏商品 * @param type int 0表示取消收藏 1表示收藏 * @param brandCityWideInfo BrandCityWideInfo 商品对象 * @param v View 商品对象 * **/ void submitAttention(final int Status,final MyFavoriteProductListInfo bean,final View v) { httpControl.setFavor(bean.getId(), Status, new HttpCallBackInterface() { @Override public void http_Success(Object obj) { /*if(v!=null && v instanceof TextView) { MyFavoriteProductListLikeUser myFavoriteProductListLikeUser=bean.getLikeUser(); if(myFavoriteProductListLikeUser!=null) { int count=bean.getLikeUser().getCount(); switch(Status) { case 0: count--; if(count<0) { count=0; } bean.getLikeUser().setCount(count); v.setSelected(false); ((TextView)v).setText(count+""); myFavoriteProductListLikeUser.setIsLike(false); break; case 1: count++; bean.getLikeUser().setCount(count); ((TextView)v).setText(count+""); v.setSelected(true); myFavoriteProductListLikeUser.setIsLike(true); break; } } }*/ if(v!=null ) { TextView pubuliu_item_layout_like_textview=(TextView)v.findViewById(R.id.pubuliu_item_layout_like_textview); ImageView pubuliu_item_layout_like_imageview=(ImageView)v.findViewById(R.id.pubuliu_item_layout_like_imageview); //MyFavoriteProductListLikeUser myFavoriteProductListLikeUser=bean.getLikeUser(); int count=bean.getFavoriteCount(); switch(Status) { case 0: count--; if(count<0) { count=0; } bean.setFavoriteCount(count); if(pubuliu_item_layout_like_imageview!=null) { pubuliu_item_layout_like_imageview.setSelected(false); } if(pubuliu_item_layout_like_textview!=null) { pubuliu_item_layout_like_textview.setText(count+""); } bean.setIsFavorite(false); break; case 1: count++; bean.setFavoriteCount(count); bean.setIsFavorite(true); if(pubuliu_item_layout_like_imageview!=null) { pubuliu_item_layout_like_imageview.setSelected(true); } if(pubuliu_item_layout_like_textview!=null) { pubuliu_item_layout_like_textview.setText(count+""); } break; } } if(pubuliuInterfaceListener!=null) { switch(Status) { case 0: pubuliuInterfaceListener.UnFavorSucess(bean.getId(),v); break; case 1: pubuliuInterfaceListener.FavorSucess(bean.getId(),v); break; } } } @Override public void http_Fails(int error, String msg) { MyApplication.getInstance().showMessage(context, msg); } }, context); } public interface PubuliuInterfaceListener { /** * 收藏成功 回调 * **/ void FavorSucess(int _id,View v); /**** * 取消收藏成功 回调 * **/ void UnFavorSucess(int _id,View v); } }
true
6496f977d22d34e75bb2b3660c469b941bf59dc8
Java
saberus/Java_2d_game
/GameOne/src/com/saber/gameOne/graphics/Assets.java
WINDOWS-1251
810
3.015625
3
[]
no_license
package com.saber.gameOne.graphics; import java.awt.image.BufferedImage; import com.saber.gameOne.util.ImageLoader; public class Assets { public static final int WIDTH = 32; public static final int HEIGHT = 32; public static BufferedImage grass1, sand1, grass2, sand2, dirt1, stone1, dirt2, air; public static void init() { SpriteSheet sheet = new SpriteSheet(ImageLoader.loadImage("/textures/tiles.png")); //TODO: grass1 = sheet.crop(0, 96, WIDTH, HEIGHT); sand1 = sheet.crop(33, 96, 32, 32); grass2 = sheet.crop(64, 96, 32, 32); sand2= sheet.crop(96, 96, 32, 32); dirt1 = sheet.crop(0, 128, 32, 32); stone1 = sheet.crop(33, 128, 32, 32); dirt2 = sheet.crop(64, 128, 32, 32); air = sheet.crop(96, 128, 32, 32); } }
true
be360a8715d5bbc14194595714993e268b9f6f98
Java
DiegoRicardo26/Parcial1
/Parcial/src/Modelo/Helicoptero.java
UTF-8
2,707
2.453125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Modelo; /** * * @author joseg */ public class Helicoptero extends Vehiculo_aereo{ private String rotor_antipar, patines_aterrizaje, turbinas, helices; public Helicoptero(){} public Helicoptero(String rotor_antipar, String patines_aterrizaje, String turbinas, String helices, String asientos, String piloto_automatico, String ventanas, String tanques, String modelo, String marca, String linea, String motor, String color, String cilindros, String tipo, String precio_venta) { super(asientos, piloto_automatico, ventanas, tanques, modelo, marca, linea, motor, color, cilindros, tipo, precio_venta); this.rotor_antipar = rotor_antipar; this.patines_aterrizaje = patines_aterrizaje; this.turbinas = turbinas; this.helices = helices; } public String getRotor_antipar() { return rotor_antipar; } public void setRotor_antipar(String rotor_antipar) { this.rotor_antipar = rotor_antipar; } public String getPatines_aterrizaje() { return patines_aterrizaje; } public void setPatines_aterrizaje(String patines_aterrizaje) { this.patines_aterrizaje = patines_aterrizaje; } public String getTurbinas() { return turbinas; } public void setTurbinas(String turbinas) { this.turbinas = turbinas; } public String getHelices() { return helices; } public void setHelices(String helices) { this.helices = helices; } @Override public void encender() { System.out.println("Lamentablemente no hay mucha informacion de como encender una helicoptero"); } /////////// @Override public void apagar() { System.out.println("Lamentablemente no hay mucha informacion de como apagar un helicoptero"); } //////////// @Override public void despegar() { System.out.println("Eleve el mando coletivo, y operar adecuadamente los pedales del timon"); } //////////// @Override public void aterrizar() { System.out.println("Pongase sobre el area, baje el mando colectivo para bajar y maniobre adecuadamente los pedales"); } ///////////// @Override public void modo_emergencia() { System.out.println("Al detectar anormalidades este helicoptero activara luz roja"); } ///////////// @Override public void planear() { System.out.println("Para mantener estatico el helicoptero"); } }
true
e9cbeff0c10a0958253f95dc735f6fcbc86b9b80
Java
vbevans94/reades
/app/src/main/java/ua/org/cofriends/reades/ui/books/BookPagerAdapter.java
UTF-8
1,520
2.1875
2
[]
no_license
package ua.org.cofriends.reades.ui.books; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import java.util.List; import ua.org.cofriends.reades.R; import ua.org.cofriends.reades.entity.Book; import ua.org.cofriends.reades.ui.read.PageView; import ua.org.cofriends.reades.utils.Logger; public class BookPagerAdapter extends PagerAdapter { private static final String TAG = Logger.makeLogTag(BookPagerAdapter.class); private final Context mContext; public BookPagerAdapter(Context context) { mContext = context; } public Book.SourceType getItem(int position) { return Book.SourceType.values()[position]; } @Override public Object instantiateItem(ViewGroup container, int position) { View view = View.inflate(mContext, getItem(position).getViewId(), null); container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); Logger.d(TAG, "destroyed at " + position); } @Override public CharSequence getPageTitle(int position) { return mContext.getString(getItem(position).getTitleString()); } @Override public int getCount() { return Book.SourceType.values().length; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } }
true
546742a5675a77e00fc82387e6a2a8caa95887c0
Java
hangxiang147/learngit
/study/src/com/zhizaolian/staff/vo/CommonSubjectTaskVo.java
UTF-8
252
1.585938
2
[]
no_license
package com.zhizaolian.staff.vo; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) public class CommonSubjectTaskVo extends TaskVO { private String title_; private String route; private String type; }
true
dd3325dd54e315fcab9f44f6fb25e996410d9ff2
Java
dohack-io/capgemini-challenge
/backend/src/main/java/io/dohack/challenge/controller/ChallengeController.java
UTF-8
1,745
2.359375
2
[]
no_license
package io.dohack.challenge.controller; import io.dohack.challenge.domain.DailyChallenge; import io.dohack.challenge.dto.CreateChallengeDto; import io.dohack.challenge.service.challenge.CreateChallengeService; import io.dohack.challenge.service.challenge.ReadChallengesService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; import java.util.List; import java.util.Optional; @RestController @RequiredArgsConstructor public class ChallengeController { private final CreateChallengeService createChallengeService; private final ReadChallengesService readChallengesService; @GetMapping("challenge/daily") Optional<DailyChallenge> getDailyChallenge() { Optional<DailyChallenge> dailyChallenge = readChallengesService.readTodayChallenge(); if (dailyChallenge.isPresent()) { return dailyChallenge; } throw new ResourceNotFoundException(); } @GetMapping("challenge/all") List<DailyChallenge> getAllDailyChallenge() { return readChallengesService.readAllDailyChallenges(); } @GetMapping("challenge/date/{date}") Optional<DailyChallenge> getDailyChallengeByDate(@PathVariable("date") String date) { LocalDate localDate = LocalDate.parse(date); Optional<DailyChallenge> dailyChallenge = readChallengesService.readChallengeByDate(localDate); if (dailyChallenge.isPresent()) { return dailyChallenge; } throw new ResourceNotFoundException(); } @PostMapping("challenge/create") DailyChallenge createDailyChallenge(@RequestBody CreateChallengeDto dto) { return createChallengeService.createDailyChallenge(dto); } }
true
69d81dde08548b720de83acd5bce59a58a491f84
Java
endeavourhealth/Api
/src/main/java/org/endeavourhealth/coreui/endpoints_public/WellKnownEndpoint.java
UTF-8
1,498
2.140625
2
[ "Apache-2.0" ]
permissive
package org.endeavourhealth.coreui.endpoints_public; import org.endeavourhealth.coreui.framework.config.ConfigService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/wellknown") public final class WellKnownEndpoint { private static final Logger LOG = LoggerFactory.getLogger(WellKnownEndpoint.class); @GET @Produces(MediaType.APPLICATION_JSON) @Path("/authconfig") public Response authconfig() { // IMPORTANT: Do NOT put anything sensitive in this config return, // it is intended to be used to configure the front-end // app by passing configuration stored on disk or in // a database return Response .ok() .entity(ConfigService.instance().getAuthConfig()) .build(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("/authconfigraw") public Response authconfigRaw() { // IMPORTANT: Do NOT put anything sensitive in this config return, // it is intended to be used to configure the front-end // app by passing configuration stored on disk or in // a database return Response .ok() .entity(ConfigService.instance().getAuthConfigRaw()) .build(); } }
true
5f4f7e4b03e78839334f3c245320d632653eb3f0
Java
AnEmortalKid/ImgProcPlayground
/src/main/java/com/anemortalkid/imgutils/Imshow.java
UTF-8
3,309
3.28125
3
[]
no_license
package com.anemortalkid.imgutils; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; import org.opencv.imgproc.Imgproc; /** * Imshow is a java based implementation of the OpenCV imshow() function, since * OpenCV for java did not include this function under {@link Highgui}, or * {@link Imgproc}, I decided to write my own. It basically just renders a * BufferedImage on a JFrame * * @author jan_monterrubio * */ public class Imshow { /** * Displays the given {@link Mat} in a frame of the default size * * @param matrix * the {@link Mat} to display */ public static void show(Mat matrix) { BufferedImage image = ImgHelper.toBufferedImage(matrix); show(image); } /** * Displays the given {@link BufferedImage} in a frame of the default size * * @param image * the {@link BufferedImage} to display */ public static void show(BufferedImage image) { JFrame imshowFrame = getFrameWithImage(image); imshowFrame.setVisible(true); } /** * Displays the given {@link Mat} in a frame of the default size with the * given title * * @param matrix * the {@link Mat} to display * @param title * the title of the frame */ public static void show(Mat matrix, String title) { BufferedImage image = ImgHelper.toBufferedImage(matrix); show(image, title); } /** * Displays the given {@link BufferedImage} in a frame of the default size * with the given title * * @param image * the {@link BufferedImage} to display * * @param title * the title of the frame */ public static void show(BufferedImage image, String title) { JFrame imshowFrame = getFrameWithImage(image); imshowFrame.setTitle(title); imshowFrame.setVisible(true); } /* * Constructs a JFrame with an ImShowPanel and returns it so we can * customize it further */ private static JFrame getFrameWithImage(BufferedImage image) { ImgShowPanel panel = new ImgShowPanel(image); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(true); frame.setLayout(new BorderLayout()); frame.add(panel, BorderLayout.CENTER); frame.setSize(new Dimension(600, 800)); return frame; } /** * An {@link ImgShowPanel} is a {@link JPanel} which renders the given * {@link BufferedImage} to the size of its container * * @author jan_monterrubio * */ private static class ImgShowPanel extends JPanel { /** * Generated Serial Version */ private static final long serialVersionUID = -9051069073482301836L; /** * Image to reference */ private BufferedImage image; /** * Constructs an {@link ImgShowPanel} with the given * {@link BufferedImage} * * @param image * the {@link BufferedImage} to display within this * {@link ImgShowPanel} */ private ImgShowPanel(BufferedImage image) { this.image = image; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null); } } }
true
84ff804011d725f74bd27458168fb9c93d1a23a9
Java
807728462/O-MVP
/basemvp/src/main/java/com/oyf/basemvp/test/LoginActivity.java
UTF-8
1,300
1.929688
2
[]
no_license
package com.oyf.basemvp.test; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.oyf.basemvp.R; import com.oyf.basemvp.view.BaseView; /** * @创建者 oyf * @创建时间 2019/11/28 11:37 * @描述 **/ public class LoginActivity extends BaseView<LoginPresenter, LoginContract.LoginView> implements LoginContract.LoginView { @Override protected int getLayoutId() { return R.layout.layout_login; } @Override protected LoginContract.LoginView getContract() { return this; } @Override public void initView(Bundle savedInstanceState) { Button bt = findViewById(R.id.bt); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //mPresenter.getContract().executeLogin("name", "123"); mPresenter.getContract().sendVerificationCode("123"); } }); } @Override public void initData(Bundle savedInstanceState) { } @Override protected LoginPresenter creatPresenter() { return new LoginPresenter(this); } @Override public void responseLogin(int resultCode, String data) { showToast(data); } }
true
7ea21d3aba44256c0e8ec99e89071feacdff3390
Java
ujszaszik/hu.ak_akademia.renovating_app
/src/gui/Selection.java
UTF-8
640
2.46875
2
[]
no_license
package gui; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; public class Selection { private Selection() { } protected static Selection isChecked(CheckBox checkbox, Label labelToPutText, String textToLabel, Label cumulatedMessage, String textToCumulatedLabel, double sumOfPrice) { if (checkbox.isSelected()) { labelToPutText.setText(textToLabel); Result.addStringAndPriceForCumulatedCalculation(textToCumulatedLabel, sumOfPrice); } else { labelToPutText.setText(""); } Result.setMessageForCumulatedPrice(cumulatedMessage); return new Selection(); } }
true
04fb696db35a5212b5f229f2d2c55d1c40bcd1c1
Java
hankctc21/FamilyMap-usingSQL-
/Service/LoginService.java
UTF-8
1,502
2.375
2
[]
no_license
package cs240.Service; import java.sql.SQLException; import cs240.DAO.DAOManager; import cs240.DAO.Generate; import cs240.DAO.UserDao; import cs240.Model.User; import cs240.Request.LoginRequest; import cs240.Result.LoginResult; /** * Created by Jeong Suk(Jerry) Han on 2017-10-12. */ public class LoginService { User u = new User(); UserDao UD= new UserDao(); public LoginService() { } /** * Logs in the user and get an auth token */ public LoginResult login(LoginRequest r) throws SQLException { DAOManager DM = new DAOManager(); UserDao UD = new UserDao(); LoginResult LR = new LoginResult(); if(SetUser(r)){ User user = UD.getUser(u); LR.setUserName(user.getUserName()); LR.setPersonID(user.getPersonID()); LR.setAuthToken(user.getAuthToken()); } return LR; } public boolean SetUser(LoginRequest r) throws SQLException { Generate gen = new Generate(); u.setUserName(r.getUserName()); u.setPassWord(r.getPassword()); if(!(UD.findUser(u))){ if((!UD.findPassword(u))){ throw new SQLException("Error in addUser"); } }else if((UD.findUser(u))){ if((!UD.findPassword(u))) { throw new SQLException("Error in addUser"); } } return true; } }
true
16f438bad1d9c4c93c787926deb5f54e3868a0e9
Java
KhushtarAnsari/Traffic-Car-Game
/src/java_game/GameSetUp.java
UTF-8
2,298
2.765625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package java_game; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java_display.Display; import java_manager.GameManager; /** * * @author kavyareddy */ public class GameSetUp implements Runnable{ private Thread thread; private Display display; private String title; private int width, height; private BufferStrategy buffer; private Graphics g; private int y; private GameManager manager; public GameSetUp(String title, int width, int height) { this.title=title; this.width=width; this.height=height; } public void init() { display = new Display(title,width,height); manager = new GameManager(); manager.init(); } public synchronized void start() { if(thread == null) { thread = new Thread(this); thread.start(); } } public synchronized void stop() { try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void tick() { manager.tick(); } public void render() { buffer = display.canvas.getBufferStrategy(); if(buffer == null) { display.canvas.createBufferStrategy(3); return; } g = buffer.getDrawGraphics(); g.clearRect(0,0,width,height); manager.render(g); buffer.show(); g.dispose(); } @Override public void run() { init(); int fps=50; double timePerTick = 1000000000/fps; double delta = 0; long current = System.nanoTime(); while(true) { delta = delta+(System.nanoTime()-current)/timePerTick; current = System.nanoTime(); if(delta>=1) { tick(); render(); delta--; } } } }
true
970e76f7a91219d22ed061331524249b233df67c
Java
Shagevan/UnipointMerchant-App
/app/src/main/java/com/example/shagee/unipoint/LastTransactionAdapter.java
UTF-8
2,432
2.328125
2
[]
no_license
package com.example.shagee.unipoint; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.shagee.unipoint.Model.TransactionHistory; import java.util.ArrayList; import java.util.List; public class LastTransactionAdapter extends RecyclerView.Adapter<LastTransactionAdapter.ViewHolder> { private Context ctx; private List<TransactionHistory> lastTransactions = new ArrayList<>(); public LastTransactionAdapter(Context ctx, List<TransactionHistory> lastTransactions) { this.ctx = ctx; this.lastTransactions = lastTransactions; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView phoneNumber; public TextView pointsAwarded; public TextView billValue; public TextView invoiceNumber; public TextView date; public ViewHolder(View v) { super(v); phoneNumber = (TextView) v.findViewById(R.id.LastTransactionPhoneNumber); pointsAwarded = (TextView) v.findViewById(R.id.LastTransactionPointsAwarded); billValue = (TextView) v.findViewById(R.id.LastTransactionBillValue); invoiceNumber = (TextView) v.findViewById(R.id.LastTransactionInvoiceNumber); date = (TextView) v.findViewById(R.id.LastTransactionDate); } } @Override public LastTransactionAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.last_transaction_row, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.phoneNumber.setText(String.valueOf(lastTransactions.get(position).getPhoneNumber())); holder.pointsAwarded.setText(String.valueOf(lastTransactions.get(position).getPointsAwarded())); holder.billValue.setText(String.valueOf(lastTransactions.get(position).getBillValue())); holder.invoiceNumber.setText(lastTransactions.get(position).getInvoiceNumber()); holder.date.setText(lastTransactions.get(position).getTransactionDateTime()); } @Override public int getItemCount() { return lastTransactions.size(); } }
true
179111e2a572a50e0ed24e3cdb3c7ccc67c726a4
Java
mAlaliSy/AlgorithmsProjectVisualization
/app/src/main/java/com/malalisy/routingalgorithmvisualizer/AppConstants.java
UTF-8
350
1.898438
2
[]
no_license
package com.malalisy.routingalgorithmvisualizer; /** * Created by MohammadAL-Ali on 26/04/17. */ public final class AppConstants { public static final int DEFAULT_NUMBER_OF_VERTICES = 5; public static final int MAX_NUMBER_OF_VERTICES = 20; public static final int MIN_NUMBER_OF_VERTICES = 5; private AppConstants() { } }
true
141399217e83aa8cf896012145a7ea29e396d478
Java
ALLENnan/Allen-Study
/src/算法题/_1去重与排序.java
UTF-8
1,842
3.6875
4
[]
no_license
package 算法题; import java.util.Iterator; import java.util.Scanner; import java.util.TreeSet; /** * @author Allen Lin * @date 2016-8-25 * @desc * 明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字 * , 只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成 * “去重”与“排序”的工作。 Input Param n 输入随机数的个数 inputArray n个随机整数组成的数组 Return * Value OutputArray 输出处理后的随机整数 */ public class _1去重与排序 { public static void main(String[] args) { Scanner cin = new Scanner(System.in); TreeSet<Integer> ts = new TreeSet<Integer>(); // TreeSet<People> ts = new TreeSet<People>(new Comparator<People>() { // public int compare(People p1, People p2) { // if (p1.getAge() > p2.getAge()) // return -1; // else if (p1.getAge() < p2.getAge()) // return 1; // else { // return 0; // } // } // // }); // ts.add(new People(2)); // ts.add(new People(9)); // ts.add(new People(4)); int n = cin.nextInt(); for (int i = 0; i < n; i++) { ts.add(cin.nextInt()); } Iterator<Integer> it = ts.iterator(); while (it.hasNext()) { System.out.println(it.next()); } // for (Integer i : ts) { // System.out.println(i); // } } } // class People { // int age; // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public People(int age) { // this.age = age; // } // }
true
45a501261a60880ec23ea25ae39193325f39c0a7
Java
bushi-go/katas-designPatterns
/src/main/java/katas/creationnal/abstractfactory/factorymethodmaze/enums/WallType.java
UTF-8
131
1.953125
2
[]
no_license
package katas.creationnal.abstractfactory.factorymethodmaze.enums; public enum WallType{ BRIQ, WOOD, STONE, MUD; }
true
9b0bd68f4bd33477b93c2dd1fe679efc6e7cabd3
Java
mlj127/zy2
/src/main/java/jiuyue/Woman.java
UTF-8
194
1.992188
2
[]
no_license
package jiuyue; public class Woman extends zaoren{ @Override public void makepeople(){ System.out.println("女娲创造了一个女人!"); super.makepeople(); } }
true
335d5fd739958520621e6a4dd0f877982a9ef564
Java
YoonSung/softwareArchitectingPractice
/IOCPractice/src/SortFactory.java
UTF-8
804
2.640625
3
[]
no_license
import java.io.File; import java.lang.reflect.Constructor; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; public class SortFactory { public static Sort getInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException { Serializer serializer = new Persister(); File source = new File("./etc/setting.xml"); XMLParser parser = null; Constructor<?> constructor = null; Sort instance = null; try { parser = serializer.read(XMLParser.class, source); constructor = Class.forName(parser.getSortName()).getDeclaredConstructor(new Class[0]); constructor.setAccessible(true); instance = (Sort) constructor.newInstance(new Object[0]); } catch (Exception e) { e.printStackTrace(); } return instance; } }
true
45f3520f9885dbad619e0138269dda07c5862e1b
Java
puratchidasan/glarimy-java-patterns
/glarimy-factory/src/com/glarimy/ComponentImpl.java
UTF-8
150
2.265625
2
[]
no_license
package com.glarimy; public class ComponentImpl implements Component { public void service() { System.out.println("ComponentImpl::service"); } }
true
341b0fee5d85316b59573e5e8dc3726db055fff3
Java
marlus/jpericia
/org.jpericia.objeto/src/org/jpericia/objeto/actions/EvidenciaRemoverAction.java
UTF-8
815
2.25
2
[]
no_license
package org.jpericia.objeto.actions; import org.eclipse.jface.action.Action; import org.jpericia.core.exception.BusinessDelegateException; import org.jpericia.objeto.businessdelegate.EvidenciaDelegate; import org.jpericia.objeto.views.EvidenciaView; public class EvidenciaRemoverAction extends Action { private EvidenciaView evidenciaView; public EvidenciaRemoverAction(EvidenciaView evidenciaView, String text) { super(text); this.evidenciaView = evidenciaView; } public void run() { try { EvidenciaDelegate.getInstance().remover(evidenciaView.getEvidencia()); evidenciaView.getViewer().setInput(EvidenciaDelegate.getInstance().pesquisar()); evidenciaView.getViewer().refresh(); } catch (BusinessDelegateException e) { // TODO tratar erro e.printStackTrace(); } } }
true
06ce417c00cea79b2ed6886d77c159222d477622
Java
15254714507/springboot-dubbo-provider-
/src/main/java/com/ssm/service/UserService.java
UTF-8
216
1.632813
2
[]
no_license
/** * */ package com.ssm.service; import java.util.List; import com.ssm.pojo.User; /** * @author 作者 * @data 2019年7月31日 */ public interface UserService { List<User> getAllUser() throws Exception; }
true
6a2b268f8273da7f0188e4539710aff6c612ae32
Java
FractalXX/user_rest
/src/main/java/com/example/userrest/data/util/RoleName.java
UTF-8
566
2.828125
3
[]
no_license
package com.example.userrest.data.util; public enum RoleName { DEFAULT("DEFAULT"), ADMIN("ADMIN"); private String name; private RoleName(String name) { this.name = name; } public String getName() { return this.name; } public static RoleName fromName(String name) { for (RoleName roleName : RoleName.values()) { if (name.equalsIgnoreCase(roleName.getName())) { return roleName; } } throw new IllegalArgumentException("RoleName representation of " + name + " was not found."); } }
true
01d5faf0448953d7b48171d31adca09cca1e1dea
Java
BubbleDomain/BubbleNotes
/algorithms/Java/src/algorithm/union_find/UnionFind.java
UTF-8
561
3.234375
3
[]
no_license
package algorithm.dynamic_programming; /** * @author: batteria * @version: 1.0 * @since: 2021/3/16 * @description: UnionFind */ class UnionFind { int count; private int[] parents; public UnionFind(int cnt) { count = cnt; parents = new int[cnt]; for (int i = 0; i < cnt; i++) parents[i] = i; } public int find(int p) { while (p != parents[p]) { parents[p] = parents[parents[p]]; p = parents[p]; } return p; } public void union(int a, int b) { a = find(a); b = find(b); if (a == b) return; count--; parents[a] = b; } }
true
bf53b88579c8b33400b399da17b9d691a1372827
Java
K1ntsugi/OOP_I
/uebung/uebung_10/Lotto/TestLotto.java
UTF-8
831
3.421875
3
[]
no_license
/* Erstellen Sie eine Klasse Lottoziehung. Erstellen Sie die Methode zieheZahl(), die eine Zufallszahl zwischen 1 und 49 (einschließlich) zurückgibt. Erstellen Sie eine Methode samstagsZiehung(), die ein Array mit sechs Zufallszahlen (1-49) ermittelt und als Attribut Ihrer Klasse speichert. Verwenden Sie zur Umsetzung auch ihre Methode zieheZahl(). Achten Sie darauf, dass keine Zahl im Array doppelt vorkommt. Sie benötigen dazu wahrscheinlich eine weitere Methode boolean pruefeArrayAufZahl(int zahl). Erstellen Sie ein Objekt Ihrer Klasse und geben Sie die Zahlen der Samstagsziehung aus. */ package Lotto; public class TestLotto { public static void main(String[] args) { LottoSpiel heute = new LottoSpiel(); System.out.println("Ziehung der Lottozahlen: "); heute.samstagsziehung(); } }
true
ec82e115fa74379186478f03f553492e89bba82a
Java
mudasirahmed123/Mudasir-Ahmed-18SW68
/lab 8/Fax.java
UTF-8
1,098
4.25
4
[]
no_license
//Task 1: Create an interface AdvancedArithmetic which contains a method signature int sumOfFactors(int n). You need to write a class called MyCalculator which implements the interface. sumOfFactors function just takes an integer as input and return the sum of all its factors. For example factors of 6 are 1, 2, 3 and 6, so sumOfFactors should return 12. The value of n will be at most 1000 import java.util.*; interface AdvancedArithmetic { public int sumOfFactors(int n); } class SumOfFactors implements AdvancedArithmetic { public int sumOfFactors(int n) { int i=1; int sum=0; while(i<=n) { if(n%i==0) sum=sum+i; i++; } return sum; } } class Main{ public static void main(String args[]) { SumOfFactors f=new SumOfFactors(); Scanner sc=new Scanner(System.in); System.out.println("Plase Enter a Number"); int n=sc.nextInt(); System.out.println("Sum of Factors of "+n+" are: "+f.sumOfFactors(n)); } }
true
2a435885ddba0a7fdc2a7a531b9f9e42035c39fb
Java
AcidC0de/Referenzen
/[Mine503] BungeeClan/src/Clan/Listener/QuitListener.java
WINDOWS-1250
1,110
2.234375
2
[]
no_license
package Clan.Listener; import java.util.List; import Clan.Main.Data; import Clan.MySQL.ClanManager; import Clan.Util.InviteManager; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PlayerDisconnectEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; public class QuitListener implements Listener { @EventHandler public void onQuit(PlayerDisconnectEvent e) { ProxiedPlayer p = (ProxiedPlayer) e.getPlayer(); if (InviteManager.invites.containsKey(p.getUniqueId().toString())) { InviteManager.removePlayer(p.getUniqueId().toString()); } List members = ClanManager.getMembers(ClanManager.getClanName(p.getUniqueId().toString())); for (int i = 0; i < members.size(); i++) { ProxiedPlayer t = ProxyServer.getInstance().getPlayer((String) ClanManager.getMembers(ClanManager.getClanName(p.getUniqueId().toString())).get(i)); if (t != null) { t.sendMessage(Data.prefix + "e" + p.getName() + " 7ist nun cOffline7."); } } } }
true
453fdddfdd0654fa3d18884d681d755c226f5726
Java
1ud0/TrocAndCo
/TAC_POM/TAC_Business_API/src/main/java/com/tac/business/api/IServiceEnvie.java
UTF-8
369
1.804688
2
[]
no_license
package com.tac.business.api; import java.util.List; import com.tac.entity.Envie; import com.tac.entity.Liste; import com.tac.entity.Membre; public interface IServiceEnvie { Envie addEnvie(Envie envie); void deleteEnvie(Envie envie); Envie getEnvie(int idEnvie); List<Envie> getByList(Liste liste); List<Envie> getByMembre(Membre membre); }
true
30badd99614e61fedfb3dd2c308b47cfdb0c034a
Java
Rockspringa/Muebleria_JSSJ
/Muebleria/src/main/java/edu/obj/Usuario.java
UTF-8
1,423
3.203125
3
[]
no_license
package edu.obj; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class Usuario { private final String username; private final String pass; private final int nivel; private boolean cancelado = false; private Usuario(String user, String pass, int nivel) { this.username = user; this.pass = pass; this.nivel = nivel; } public static Usuario construct(String user, String pass, int nivel) throws PatternSyntaxException { Usuario out = null; Pattern pat = Pattern.compile("^([\\w ])+$"); Matcher matchUser = pat.matcher(user); Matcher matchPass = pat.matcher(pass); if (matchUser.matches() && matchPass.matches() && nivel < 4 && nivel > 0) { out = new Usuario(user, pass, nivel); } else { throw new PatternSyntaxException("Existen simbolos en las cadenas", "", -1); } return out; } public String getUsername() { return username; } public String getPass() { return pass; } public int getNivel() { return nivel; } public boolean isCancelado() { return cancelado; } public void cancelar() { if (!this.cancelado) this.cancelado = !this.cancelado; } @Override public String toString() { return this.username; } }
true
1eed962c224b6e5060829def1a6594af131b128e
Java
IoniUTDT/contornos
/core/src/com/turin/tur/main/diseno/Trial.java
UTF-8
15,741
1.921875
2
[]
no_license
package com.turin.tur.main.diseno; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.TimeUtils; import com.turin.tur.main.diseno.Boxes.AnswerBox; import com.turin.tur.main.diseno.Boxes.Box; import com.turin.tur.main.diseno.Boxes.StimuliBox; import com.turin.tur.main.diseno.Boxes.TrainingBox; import com.turin.tur.main.diseno.Enviables.STATUS; import com.turin.tur.main.diseno.ExperimentalObject.JsonResourcesMetaData; import com.turin.tur.main.util.Constants; import com.turin.tur.main.util.Constants.Resources.Categorias; import com.turin.tur.main.util.builder.Builder; import com.turin.tur.main.util.FileHelper; import com.turin.tur.main.util.Constants.Diseno.DISTRIBUCIONESenPANTALLA; import com.turin.tur.main.util.Constants.Diseno.TIPOdeTRIAL; public class Trial { public int Id; // Id q identifica al trial public JsonTrial jsonTrial; // objetos que se cargan en el load o al inicializar public Array<ExperimentalObject> elementos = new Array<ExperimentalObject>(); public ExperimentalObject rtaCorrecta; public Level levelActivo; public User userActivo; public float levelTime = 0; public Array<TrainingBox> trainigBoxes = new Array<TrainingBox>(); public Array<AnswerBox> answerBoxes = new Array<AnswerBox>(); public StimuliBox stimuliBox; public Array<Box> allBox = new Array<Box>(); public Array<Integer> orden = new Array<Integer>(); // Variable que tiene que ver con el estado del trial public boolean trialCompleted = false; public boolean alreadySelected = false; // indica si ya se elecciono algo o no // Variables que llevan el registro public TrialLog log; public RunningSound runningSound; // constantes public static final String TAG = Trial.class.getName(); public Trial(int Id) { this.Id = Id; initTrial(Id); createElements(); } private void createElements() { // Crea un orden random o no segun corresponda for (int i = 0; i < this.jsonTrial.distribucion.distribucion.length; i++) { orden.add(i); } if (this.jsonTrial.randomSort) { orden.shuffle(); } // Crea las cajas segun corresponda a su tipo if (this.jsonTrial.modo == Constants.Diseno.TIPOdeTRIAL.EJEMPLOS) { for (ExperimentalObject elemento : this.elementos) { TrainingBox box = new TrainingBox(elemento); box.SetPosition(jsonTrial.distribucion.X(orden.get(this.elementos.indexOf(elemento, true))), jsonTrial.distribucion.Y(orden.get(this.elementos.indexOf(elemento, true)))); this.trainigBoxes.add(box); } } if (this.jsonTrial.modo == Constants.Diseno.TIPOdeTRIAL.TEST){ for (ExperimentalObject elemento : this.elementos) { AnswerBox box = new AnswerBox(elemento,this.jsonTrial.feedback); box.SetPosition(jsonTrial.distribucion.X(orden.get(this.elementos.indexOf(elemento, true))) + Constants.Box.SHIFT_MODO_SELECCIONAR, jsonTrial.distribucion.Y(orden.get(this.elementos.indexOf(elemento, true)))); this.answerBoxes.add(box); } stimuliBox = new StimuliBox(rtaCorrecta); stimuliBox.SetPosition(0 + Constants.Box.SHIFT_ESTIMULO_MODO_SELECCIONAR, 0); allBox.add(stimuliBox); } // Junta todas las cajas en una unica lista para que funcionen los // update, etc. for (Box box : answerBoxes) { allBox.add(box); } for (Box box : trainigBoxes) { allBox.add(box); } } private void initTrial(int Id) { Gdx.app.log(TAG, "Cargando info del trial"); // Carga la info en bruto JsonTrial jsonTrial = JsonTrial.LoadTrial(Id); this.jsonTrial = jsonTrial; // Carga la info a partir de los Ids for (int elemento : this.jsonTrial.elementosId) { this.elementos.add(new ExperimentalObject(elemento)); } boolean rtaEntreOpciones = false; for (int i: this.jsonTrial.elementosId) { if (this.jsonTrial.rtaCorrectaId == i){ rtaEntreOpciones = true; } } if ((this.jsonTrial.rtaRandom) && (rtaEntreOpciones)){ // Pone una random solo si esta seteada como random y la rta esta entre las figuras this.rtaCorrecta = new ExperimentalObject(this.jsonTrial.elementosId[MathUtils.random(this.jsonTrial.elementosId.length-1)]); } else { this.rtaCorrecta = new ExperimentalObject(this.jsonTrial.rtaCorrectaId); } if (new ExperimentalObject(this.jsonTrial.rtaCorrectaId).categorias.contains(Categorias.Nada, false)) { // Pone si o si una respuesta random si la rta es nada. this.rtaCorrecta = new ExperimentalObject(this.jsonTrial.elementosId[MathUtils.random(this.jsonTrial.elementosId.length-1)]); } // Crea el log que se carga en el controller this.log = new TrialLog(); } public void update(float deltaTime) { // Actualiza las boxes for (Box box : allBox) { box.update(deltaTime, this); } } public boolean checkTrialCompleted() { // Se encarga de ver si ya se completo trial o no if (this.jsonTrial.modo == TIPOdeTRIAL.EJEMPLOS) { boolean allCheck = true; for (TrainingBox box : trainigBoxes) { if (box.alreadySelected == false) { allCheck = false; } } if (allCheck) { trialCompleted = true; } else { trialCompleted = false; } } //Agrega al log el estado de trial this.log.trialCompleted=trialCompleted; return trialCompleted; } // Seccion encargada de guardar y cargar info de trials // devuelve la info de la metadata public static class ParametrosSetup { public int R; public int D; } public static class JsonTrial { public String caption; // Texto que se muestra debajo public int Id; // Id q identifica al trial public String title; // Titulo optativo q describe al trial public TIPOdeTRIAL modo; // Tipo de trial public int[] elementosId; // Lista de objetos del trial. public int rtaCorrectaId; // Respuesta correcta en caso de que sea test. public boolean rtaRandom; // Determina si se elije una rta random public DISTRIBUCIONESenPANTALLA distribucion; // guarda las posiciones // de los elementos a // mostrar public boolean feedback=false; // Sirve para configurar que en algunos test no haya feedback public boolean randomSort; public int resourceVersion; public String identificador; public ParametrosSetup parametros; public static void CreateTrial(JsonTrial jsonTrial, String path) { Json json = new Json(); json.setUsePrototypes(false); FileHelper.writeFile(path + "trial" + jsonTrial.Id + ".meta", json.toJson(jsonTrial)); } public static JsonTrial LoadTrial(int Id) { String savedData = FileHelper.readFile("experimentalsource/" + Constants.version() + "/trial" + Id + ".meta"); if (!savedData.isEmpty()) { Json json = new Json(); json.setUsePrototypes(false); return json.fromJson(JsonTrial.class, savedData); } Gdx.app.error(TAG, "No se a podido encontrar la info del objeto experimental " + Id); return null; } } // Seccion de logs public static class TouchLog { // Todas las cosas se deberian generar al mismo tiempo public long touchInstance; // Instancia que identyifica a cada toque public long trialInstance; // Instancia q identifica al trial en el cual se toco public int trialId; // Id del trial en el que se toco public ResourceId idResourceTouched; // Id del recurso que se toco public Array<Categorias> categorias = new Array<Categorias>(); // Lista de categorias a las que pertenece el elemento tocado public TIPOdeTRIAL tipoDeTrial; // Tipo de trial (entrenamiento test, etc) public boolean isTrue; // Indica si se toco el recurso que era la respuesta public boolean isStimuli; // indica si el recurso tocado es el estimulo (en general se lo toca para que se reproduzca) public float timeSinceTrialStarts; // Tiempo desde que se muestra el trial public long soundInstance; // Intancia del ultimo sonido en ejecucion public boolean soundRunning; // indica si se esta ejecutando algun sonido public float timeLastStartSound; // Tiempo (en el trial) en que comenzo el ultimo sonido public float timeLastStopSound; // Tiempo (en el trial en que terimo el ultimo sonido public int numberOfSoundLoops; // Cantidad de veces que re reprodujo el ultimo sonido public Array<Integer> soundIdSecuenceInTrial; // Ids de todos los sonidos que se reprodujeron en el trial public long levelInstance; // Registra el level en el que se toco public long sessionInstance; // Registra la session en que se toco public JsonResourcesMetaData jsonMetaDataTouched; // Guarda la info completa de la meta data del objeto tocado } public static class SoundLog { // Variables que se crean con el evento public long soundInstance; // identificador de la instancia de sonido en particular public ResourceId soundId; // Id al recurso del cual se escucha el sonido public Array<Categorias> categorias = new Array<Categorias>(); // Categorias a las que pertenece el sonido en reproduccion public long trialInstance; // instancia del Trial en la que se reproduce el sonido public int trialId; // Id del trial en el que se reproduce el sonido public boolean fromStimuli; // Indica si el sonido viene de un estimulo o no (sino viene de una caja de entrenamiento) public TIPOdeTRIAL tipoDeTrial; // Tipo de trial en el que se reproduce este sonido public int numberOfLoop; // Numero de loop que corresponde a la reproduccion de este sonido public float startTimeSinceTrial; // tiempo en que se inicia la reproduccion del sonido desde que comenzo el trial public int numberOfSoundInTrial; // Cantidad de sonidos reproducidos previamente public Array<Integer> soundSecuenceInTrial; // Listado de sonidos reproducidos // Variables que se generan una vez creado el evento public float stopTime; // tiempo en que se detiene el sonido public boolean stopByExit; // Indica si se detuvo el sonido porque se inicio alguna secuencia de cierre del trial (porque se completo el trial, el level, etc) public boolean stopByUnselect; // Indica si se detuvo el sonido porque el usuario selecciono algo como parte de la dinamica del juego public boolean stopByEnd; // Indica si el sonido se detuvo porque se completo la reproduccion prevista (por ahora esta determinada por el tiempo preestablecido de duracion de los sonidos en 5s. No es el tiempo en que de verdad termina el sonido) public long sessionInstance; // Indica la instancia de session en que se reproduce este sonido public long levelInstance; // Indica la instancia de level en que se reproduce este sonido } public static class TrialLog { // Info del envio public STATUS status=STATUS.CREADO; public long idEnvio; // Info de arbol del evento public long sessionId; // Instancia de la session a la que este trial pertence public long levelInstance; // Intancia del nivel al que este trial pertenece public long trialInstance; // identificador de la instancia de este trial. // Info del usuario y del trial public int trialId; // Id del trial activo public long userId; // Id del usuario activo public Array<Categorias> categoriasElementos = new Array<Categorias>(); // Listado de categorias existentes en este trial public Array<Categorias> categoriasRta = new Array<Categorias>(); // Listado de categorias a las que pertenece la rta valida / estimulo de este trial si la hay public ResourceId idRtaCorrecta; // id del recurso correspondiente a la rta correcta para este trial public int indexOfTrialInLevel; // posicion de este trial dentro del nivel public int trialsInLevel; // Cantidad total de trials en el nivel activo public JsonResourcesMetaData jsonMetaDataRta; // Info de la metadata del estimulo/rta public long timeTrialStart; // Marca temporal absoluta de cuando se inicia el trial public long timeExitTrial; // Marca temporal absoluta de cuando se sale del trial public Array<Integer> resourcesIdSort = new Array<Integer>(); // Ids de los recursos en orden segun se completan en la distribucion. Esto es importante porque el orden puede estar randomizado instancia a instancia public DISTRIBUCIONESenPANTALLA distribucionEnPantalla; // Distribucion en pantalla de los recursos public TIPOdeTRIAL tipoDeTrial; // Tipo de trial (test, entrnamiento, etc) public float version = Constants.VERSION; // Version del programa. Esto es super importante porque de version a version pueden cambiar los recursos (es decir que el mismo id lleve a otro recurso) y tambien otras cosas como la distribucion en pantalla, etc public float resourcesVersion = Builder.ResourceVersion; // Version de los recursos generados // Informacion de lo que sucede durante la interaccion del usuario // public float timeStartTrialInLevel; // Tiempo en que se crea el trial en relacion al nivel public float timeStopTrialInLevel; // Tiempo en que se termina el trial en relacion al nivel public float timeInTrial; // tiempo transcurrido dentro del trial public boolean trialCompleted; //Por ahora solo se puede completar un trial en modo training. En modo test no tiene sentido completar el nivel. Este dato se carga de cuando sehace el checkTrialCompleted public Array<ResourceId> resourcesIdSelected = new Array<ResourceId>(); // Lista de elementos seleccionados public Array<TouchLog> touchLog = new Array<TouchLog>(); // Secuencia de la info detallada de todos los touch public Array<SoundLog> soundLog = new Array<SoundLog>(); // Secuencia de la info detallada de todos los sounds public boolean trialExitRecorded; // registra que se guardo la informacion de salida del trial. public String trialTitle; public JsonTrial jsonTrial; // Json con toda la info que viene del archivo con los datos del trial public TrialLog() { this.trialInstance = TimeUtils.millis(); } } public static class ResourceId { public int id; public int resourceVersion; } public void newLog(Session session, Level levelInfo) { // Carga la info general del contexto this.log.levelInstance = levelInfo.levelLog.levelInstance; this.log.sessionId = session.sessionLog.id; this.log.timeTrialStart = TimeUtils.millis(); this.log.trialId = this.Id; this.log.trialTitle = this.jsonTrial.title; this.log.userId = session.sessionLog.userID; // Agrega las categorias de la rta correcta o estimulo if (this.rtaCorrecta!=null) { for (Categorias categoria: this.rtaCorrecta.categorias) { this.log.categoriasRta.add(categoria); } // Agrega el json de la rta correcta/estimulo this.log.jsonMetaDataRta = JsonResourcesMetaData.Load(this.rtaCorrecta.resourceId.id); } // Agrega las categorias de todas las cajas for (Box box: this.allBox) { for (Categorias categoria: box.contenido.categorias){ this.log.categoriasElementos.add(categoria); } } this.log.idRtaCorrecta = this.rtaCorrecta.resourceId; this.log.indexOfTrialInLevel = levelInfo.activeTrialPosition; this.log.trialsInLevel = levelInfo.secuenciaTrailsId.size; // Recupera los Id de los recursos en el orden que estan en pantalla for (int orden : this.orden) { this.log.resourcesIdSort.add(this.elementos.get(orden).resourceId.id); // Recupera los ids de los recursos segun el orden en que esten } this.log.distribucionEnPantalla = this.jsonTrial.distribucion; this.log.tipoDeTrial = this.jsonTrial.modo; this.log.jsonTrial = this.jsonTrial; this.log.jsonMetaDataRta = JsonResourcesMetaData.Load(this.rtaCorrecta.resourceId.id); } }
true
e7019c8bf13490de0065019c0d39d1687d3f8f95
Java
fras2560/Tangent-L
/src/search/SearchResult.java
UTF-8
4,490
2.625
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2017 Dallas Fraser * * 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 search; import java.io.BufferedWriter; import java.io.IOException; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import query.MathQuery; /** * A class to hold the search results for a query. * * @author Dallas Fraser * @since 2017-11-06 */ public class SearchResult { public TopDocs results; public MathQuery mathQuery; public Query query; public int size; /** * Class Constructor. * * @param results the documents returned by the query * @param mathQuery the Math Query * @param size the number of documents returned by the query * @param query the Lucene Query */ public SearchResult(TopDocs results, MathQuery mathQuery, int size, Query query) { this.results = results; this.mathQuery = mathQuery; this.size = size; this.query = query; } /** * Returns the maximum number of documents that could be returned by the search. * * @return int the size of the results */ public int getSize() { return this.size; } /** * Returns the results. * * @return TopDocs the top documents of the results */ public TopDocs getResults() { return this.results; } /** Sets the results. */ public void setResults(TopDocs docs) { this.results = docs; } /** * Returns the Math Query. * * @return MathQuery the math query of the result */ public MathQuery getMathQuery() { return this.mathQuery; } /** * Returns the Query. * * @return Query the query that was used when searching */ public Query getQuery() { return this.query; } /** * Returns the number of documents returned by the search. * * @return the number of hits. */ public int hitsNumber() { int hits = 0; if (this.results != null) { hits = this.results.totalHits; } return hits; } /* * Returns a String representation of the object * @return a String representation * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { String result = this.mathQuery.getQueryName(); if (this.results != null) { final ScoreDoc[] hits = this.results.scoreDocs; System.out.println(hits); for (final ScoreDoc hit : hits) { System.out.println("Hit: " + hit); result = result + " " + hit.doc + ":" + hit.score; } } return result; } /** * Explain the results. * * @param searcher the searcher used * @throws IOException - issue while dealing with a file */ public void explainResults(IndexSearcher searcher) throws IOException { if (this.results != null) { final ScoreDoc[] hits = this.results.scoreDocs; for (final ScoreDoc hit : hits) { System.out.println( searcher.doc(hit.doc).get("path") + " " + hit.toString() + ":" + searcher.explain(this.query, hit.doc)); } } else { System.out.println("Query had no terms or results"); } } /** * Explains the results and outputs the explanation to a file. * * @param searcher the searcher used * @param output the file to output to * @throws IOException - issue while dealing with a file */ public void explainResults(IndexSearcher searcher, BufferedWriter output) throws IOException { if (this.results != null) { final ScoreDoc[] hits = this.results.scoreDocs; for (final ScoreDoc hit : hits) { output.write( searcher.doc(hit.doc).get("path") + " " + hit.toString() + ":" + searcher.explain(this.query, hit.doc)); output.newLine(); } } else { output.write("Query had no terms or results"); } } }
true
219bd59120e979fd2ce66ec379674562b62e4aba
Java
jifalops/DeviceInfoOld
/src/com/jphilli85/deviceinfo/element/Properties.java
UTF-8
465
1.96875
2
[]
no_license
package com.jphilli85.deviceinfo.element; import java.util.LinkedHashMap; import android.content.Context; import com.jphilli85.deviceinfo.ShellHelper; public class Properties extends Element { public Properties(Context context) { super(context); } @Override public LinkedHashMap<String, String> getContents() { // LinkedHashMap<String, String> contents = new LinkedHashMap<String, String>(); return ShellHelper.getProp(); // return contents; } }
true
61780323366ec0b85ca2615ad0a81594f2d59d4d
Java
yuzhaocai/shoppingCartPromotion
/src/test/java/test/TestContains.java
UTF-8
13,599
2.265625
2
[ "BSD-3-Clause" ]
permissive
package test; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.script.ScriptException; import static org.hamcrest.core.IsEqual.equalTo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import scpc.Calculator; import scpc.model.BonusItem; import scpc.model.CartItem; import scpc.model.CurrentItem; import scpc.model.IItem; import scpc.model.IRule; import scpc.model.LiquidPaper; import scpc.model.OneCentDiscount; import scpc.model.Stapler; import scpc.model.WaterSolubleBrightPinkFabricMarkerPen; import scpc.model.WaterSolublePurpleFabricMarkerPen; import scpc.rule.BaseRule; import static test.TestBase.SHOW_CART; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsIterableContaining.hasItem; /** * * @author Kent Yeh */ @Test(groups = "debug") public class TestContains extends TestBase { private static final Logger logger = LoggerFactory.getLogger(TestContains.class); @Parameters(SHOW_CART) public void testBuy2PensGet1FreeOffer(@Optional String showCart) throws ScriptException { CartItem purplePen = new WaterSolublePurpleFabricMarkerPen().buy(3); CartItem briPinkPen = new WaterSolubleBrightPinkFabricMarkerPen().buy(2); Set<IItem<CartItem>> cartItems = new HashSet<>(); cartItems.add(purplePen); cartItems.add(briPinkPen); cartItems.add(new LiquidPaper().buy(2)); cartItems.add(new Stapler().buy(2)); List<IRule<CartItem>> rules = new ArrayList(); rules.add(new BaseRule("Buy two pens get free one offer!", BaseRule.JS_EVAL, "N%2==0", "1", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return CurrentItem.getInstance(); } }); Collection<BonusItem<CartItem>> bonuses = Calculator.calcBonus(rules, cartItems); List<CartItem> itemList = Calculator.purification(bonuses); assertThat("can't found purle pen free offer!", itemList, hasItem(purplePen)); assertThat("can't found birhgt pink pen free offer!", itemList, hasItem(briPinkPen)); long quantity = 0; for (CartItem bonus : itemList) { quantity += bonus.getQuantity(); } assertThat("Should got 2 pens", quantity, is(equalTo(2l))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuy2PensGet1FreeOffer", cartItems, bonuses)); } } @Parameters(SHOW_CART) public void testBuyPensWhen3Then1AndWhen5Then2AndWhen7Then3AndWhen10Then5PctDiscount(@Optional String showCart) throws ScriptException { CartItem purplePen = new WaterSolublePurpleFabricMarkerPen().buy(2); CartItem briPinkPen = new WaterSolubleBrightPinkFabricMarkerPen().buy(2); Set<IItem<CartItem>> cartItems = new HashSet<>(); cartItems.add(purplePen); cartItems.add(briPinkPen); cartItems.add(new LiquidPaper().buy(2)); cartItems.add(new Stapler().buy(1)); List<IRule<CartItem>> rules = new ArrayList(); rules.add(new BaseRule("Buy massive pens get different discount!", BaseRule.SPEL_EVAL, true, true, "N>1", "SCSP*(N>9?5:N>6?3:N>4?2:N>2?1:0)", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); Collection<BonusItem<CartItem>> bonuses = Calculator.calcBonus(rules, cartItems); double spent = purplePen.getSalePrice() * purplePen.getQuantity() + briPinkPen.getSalePrice() * briPinkPen.getQuantity(); long saving = Math.round(Math.floor(spent)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuyMassivePensGetDiffDiscount", cartItems, bonuses)); } purplePen = purplePen.buy(3); briPinkPen = briPinkPen.buy(3); rules.clear(); rules.add(new BaseRule("Buy massive pens get different discount!", BaseRule.JS_EVAL, true, true, "N>1", "SCSP*(N>9?5:N>6?3:N>4?2:N>2?1:0)", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); bonuses = Calculator.calcBonus(rules, cartItems); spent = purplePen.getSalePrice() * purplePen.getQuantity() + briPinkPen.getSalePrice() * briPinkPen.getQuantity(); saving = Math.round(Math.floor(spent * 2)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuyMassivePensGetDiffDiscount", cartItems, bonuses)); } purplePen = purplePen.buy(6); briPinkPen = briPinkPen.buy(5); rules.clear(); rules.add(new BaseRule("Buy massive pens get different discount!", BaseRule.SPEL_EVAL, true, true, "N>1", "SCSP*(N>9?5:N>6?3:N>4?2:N>2?1:0)", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); bonuses = Calculator.calcBonus(rules, cartItems); spent = purplePen.getSalePrice() * purplePen.getQuantity() + briPinkPen.getSalePrice() * briPinkPen.getQuantity(); saving = Math.round(Math.floor(spent * 5)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuyMassivePensGetDiffDiscount", cartItems, bonuses)); } } @Parameters(SHOW_CART) public void test2PensGetPrice30PctDiscount(@Optional String showCart) throws ScriptException { CartItem purplePen = new WaterSolublePurpleFabricMarkerPen().buy(3); CartItem briPinkPen = new WaterSolubleBrightPinkFabricMarkerPen().buy(3); Set<IItem<CartItem>> cartItems = new HashSet<>(); cartItems.add(purplePen); cartItems.add(briPinkPen); cartItems.add(new LiquidPaper().buy(3)); cartItems.add(new Stapler().buy(3)); List<IRule<CartItem>> rules = new ArrayList(); rules.add(new BaseRule("2 Pens Get RegPrice 30% discount!", BaseRule.SPEL_EVAL, true, true, "N%2==0", "(SCSP*10-SCOP*7)", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); Collection<BonusItem<CartItem>> bonuses = Calculator.calcBonus(rules, cartItems); long saving = Math.round(Math.floor( (briPinkPen.getSalePrice() + purplePen.getSalePrice()) * 3 * 10 - (briPinkPen.getRegularPrice() + purplePen.getRegularPrice()) * 3 * 7)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("Test2PensGetRegularPrice30PctDiscount", cartItems, bonuses)); } rules.clear(); rules.add(new BaseRule("2 Pens Get SalePrice 30% discount!", BaseRule.SPEL_EVAL, true, true, "N%2==0", "SCSP*3", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); bonuses = Calculator.calcBonus(rules, cartItems); saving = Math.round(Math.floor((briPinkPen.getSalePrice() + purplePen.getSalePrice()) * 3 * 3)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("Test2PensGetSalePrice30PctDiscount", cartItems, bonuses)); } } @Parameters(SHOW_CART) public void testBuy1Get3PctSalePriceAndBuy10Get3PctRegularPricePctDiscount(@Optional String showCart) throws ScriptException { CartItem purplePen = new WaterSolublePurpleFabricMarkerPen().buy(1); CartItem briPinkPen = new WaterSolubleBrightPinkFabricMarkerPen().buy(1); Set<IItem<CartItem>> cartItems = new HashSet<>(); cartItems.add(purplePen); cartItems.add(briPinkPen); cartItems.add(new LiquidPaper().buy(3)); cartItems.add(new Stapler().buy(3)); List<IRule<CartItem>> rules = new ArrayList(); rules.add(new BaseRule("less 10 Pens Get SalePrice 30% discount!", BaseRule.JS_EVAL, true, true, "true", "(N<10?SCSP:SCOP)*3", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); Collection<BonusItem<CartItem>> bonuses = Calculator.calcBonus(rules, cartItems); long saving = Math.round(Math.floor((briPinkPen.getSalePrice() + purplePen.getSalePrice()) * 3)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuy1Get3PctSalePriceAndBuy10Get3PctRegularPricePctDiscount", cartItems, bonuses)); } purplePen = purplePen.buy(5); briPinkPen = briPinkPen.buy(5); rules.clear(); rules.add(new BaseRule("10 Pens Get RegPrice 30% discount!", BaseRule.JS_EVAL, true, true, "true", "(N<10?SCSP:SCOP)*3", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }); bonuses = Calculator.calcBonus(rules, cartItems); saving = Math.round(Math.floor((briPinkPen.getRegularPrice() + purplePen.getRegularPrice()) * 5 * 3)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuy1Get3PctSalePriceAndBuy10Get3PctRegularPricePctDiscount", cartItems, bonuses)); } } @Parameters(SHOW_CART) public void testbundle1Stapler_2LiquidPaper_3PensGet10PctDiscount(@Optional String showCart) throws ScriptException { CartItem stapler = new Stapler().buy(2); CartItem liquidPaper = new LiquidPaper().buy(4); CartItem purplePen = new WaterSolublePurpleFabricMarkerPen().buy(3 + 3); CartItem briPinkPen = new WaterSolubleBrightPinkFabricMarkerPen().buy(3); Set<IItem<CartItem>> cartItems = new HashSet<>(); cartItems.add(stapler); cartItems.add(liquidPaper); cartItems.add(purplePen); cartItems.add(briPinkPen); List<IRule<CartItem>> rules = new ArrayList(); rules.add(new BaseRule("1S2L3PGet10%Discount", BaseRule.JS_EVAL, false, false, "true", "", 0, Stapler.CODE) { @Override public IItem<CartItem> getBonus() { throw new UnsupportedOperationException("Not supported yet."); } }.setNext(new BaseRule("", BaseRule.SPEL_EVAL, false, false, "N%2==0", "", 0, LiquidPaper.CODE) { @Override public IItem<CartItem> getBonus() { throw new UnsupportedOperationException("Not supported yet."); } }.setNext(new BaseRule("", BaseRule.JS_EVAL, "N%3==0", "(SCSP+PSCSP+PPSCSP)*10", 0, WaterSolublePurpleFabricMarkerPen.CODE, WaterSolubleBrightPinkFabricMarkerPen.CODE) { @Override public IItem<CartItem> getBonus() { return new OneCentDiscount(); } }))); Collection<BonusItem<CartItem>> bonuses = Calculator.calcBonus(rules, cartItems); long saving = Math.round(Math.floor(stapler.getSalePrice() * 20 + liquidPaper.getSalePrice() * 40 + briPinkPen.getSalePrice() * 30 + purplePen.getSalePrice() * 30)); assertThat(String.format("Should save %,d cents", saving), bonuses.iterator().next().getQuantity(), is(equalTo(saving))); if ("true".equalsIgnoreCase(showCart)) { logger.info("\n{}", showCart("TestBuy1Stapler_2LiquidPaper_3PensGet10%Discount", cartItems, bonuses)); } } }
true
828f80f8aba396d248dfeff76e459d7aef7f0d8d
Java
ayushinrupeek/springboot-cabbooikg
/src/main/java/main/services/CabServices.java
UTF-8
812
2.328125
2
[]
no_license
package main.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import main.entity.Cab; import main.entity.TripBooking; import main.repository.CabRepository; @Service public class CabServices { @Autowired private CabRepository cabRepo; public void insertCab(Cab cab) { cabRepo.save(cab); } public void updateCab(Cab cab) { cabRepo.save(cab); } public void deleteCab(Integer id) { cabRepo.deleteById(id); } public int countCab(String carType) { return cabRepo.countCab(carType); } public List<Cab> viewCab(String carType){ List<Cab> cars = cabRepo.viewCab(carType); return cars; } public List<Cab> viewFreeCabs(){ List<Cab> cabs = cabRepo.viewFreeCabs(); return cabs; } }
true
7a7a25823d44e803c4999bb31fce5c58d4d01824
Java
kongxiangyue/firstline_advanced
/pratice/MessageBoard/app/src/main/java/com/example/gupt/messageboard/MainActivity.java
UTF-8
4,092
2.0625
2
[]
no_license
package com.example.gupt.messageboard; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.example.gupt.messageboard.model.Messege; import com.example.gupt.messageboard.network.HttpCallbackListener; import com.example.gupt.messageboard.network.HttpUtil; import com.example.gupt.messageboard.ui.ListAdapter; import com.example.gupt.messageboard.util.Util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindUI(); } @Override protected void onStart() { super.onStart(); getAllMsgAndShow(); } public void onClick(View v) { switch (v.getId()) { case R.id.btn_add_msg : jumpAddMsgActivity(); break; case R.id.btn_refresh : getAllMsgAndShow(); break; case R.id.btn_other : break; default: break; } } private void bindUI() { listView = (ListView) findViewById(R.id.listview); } private void getAllMsgAndShow() { final String address = Util.http + Util.server_ip + Util.get_all_msg; new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() // 指定访问的服务器地址是电脑本机 .url(address) .build(); Response response = client.newCall(request).execute(); String responseData = response.body().string(); handleAllMsgResponse(responseData); } catch (Exception e) { e.printStackTrace(); } } }).start(); /* *HttpUtil.sendOkHttpRequest(address, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this , MainActivity.this.getResources().getString(R.string.all_msg_error) , Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Call call, final Response response) throws IOException { runOnUiThread(new Runnable() { @Override public void run() { try { handleAllMsgResponse(response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }); } });*/ } private void handleAllMsgResponse(final String body_str) { runOnUiThread(new Runnable() { @Override public void run() { Gson gson = new Gson(); List<Messege> msg_list = gson.fromJson(body_str , new TypeToken<List<Messege>>() {}.getType()); listView.setAdapter(new ListAdapter(MainActivity.this, msg_list)); } }); } private void jumpAddMsgActivity() { Intent i = new Intent("com.example.gupt.messageboard.addmsgactivity"); startActivity(i); } }
true
95ecf87556ba555fff8b15162050cd96caeadf28
Java
qql916/gmallTest
/gmall-order-service/src/main/java/com/atguigu/gmall/order/mapper/OrderInfoMapper.java
UTF-8
294
1.585938
2
[]
no_license
package com.atguigu.gmall.order.mapper; import com.atguigu.gmall.user.bean.OrderInfo; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; public interface OrderInfoMapper extends Mapper<OrderInfo>{ void deleteCheckedCart(@Param("delStr") String delStr); }
true
8762366ccc3ebd551ae4ff1cf6dc0be4fc924da6
Java
callisto-h/tc3-csci165-main
/week-7/lab/MyPoint.java
UTF-8
1,952
3.984375
4
[]
no_license
public class MyPoint { private int x; private int y; // constructor with no args public MyPoint() { } // constructor with args for X and Y public MyPoint(int x, int y) { setXY(x, y); } public MyPoint(MyPoint another) { // null check if (another == null) return; setXY(another.getX(), another.getY()); } // getter for X public int getX() { return x; } // setter for X public void setX(int x) { this.x = x; } // getter for Y public int getY() { return y; } // setter for Y public void setY(int y) { this.y = y; } // gets both X and Y as a 2 element array, [X, Y] public int[] getXY() { return new int[] { x, y }; } // sets both the X and Y public void setXY(int x, int y) { this.x = x; this.y = y; } // formats X Y as "(X,Y)" @Override public String toString() { return String.format("(%d,%d)", this.x, this.y); } // calculates distance from this point to supplied X, Y public double distance(int x, int y) { return Math.sqrt((this.y - y) * (this.y - y) + (this.x - x) * (this.x - x)); } // calculates distance from this point to supplied point public double distance(MyPoint another) { return distance(another.x, another.y); } // calculates distance from this point to 0,0 public double distance() { return distance(0, 0); } // determines MyPoint equality @Override public boolean equals(Object other) { // same object check if (this == other) return true; // null check + different class check if (other == null || this.getClass() != other.getClass()) return false; MyPoint that = (MyPoint) other; return that.x == this.x && that.y == this.y; } }
true
a887727fd2827148ce4a9c0d0b08c36bfdfdce04
Java
kemboikelly/Triple-K-CarWash
/app/src/main/java/com/triple/triple_kcarwash/EngineWashActivity.java
UTF-8
1,860
1.882813
2
[]
no_license
package com.triple.triple_kcarwash; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class EngineWashActivity extends AppCompatActivity { TextView tvTruckEng,tvMattuEng,tvSlonEng,tvTktkEng; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_engine_wash); tvTruckEng = findViewById(R.id.tvTruckEng); tvMattuEng = findViewById(R.id.tvMatatuEng); tvSlonEng = findViewById(R.id.tvSalonEng); tvTktkEng = findViewById(R.id.tvTukTukEng); tvTruckEng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EngineWashActivity.this,PaymentsActivity.class); startActivity(intent); } }); tvMattuEng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EngineWashActivity.this,PaymentsActivity.class); startActivity(intent); } }); tvSlonEng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EngineWashActivity.this,PaymentsActivity.class); startActivity(intent); } }); tvTktkEng.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EngineWashActivity.this,PaymentsActivity.class); startActivity(intent); } }); } }
true
a5297e3de041106837515952625ca8bdf4a27d15
Java
30962088/Dongfeng
/src/com/media/dongfeng/InfoFragment.java
UTF-8
27,454
1.6875
2
[]
no_license
package com.media.dongfeng; import java.util.ArrayList; import java.util.List; import java.util.concurrent.RejectedExecutionException; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.media.dongfeng.exception.ZhiDaoApiException; import com.media.dongfeng.exception.ZhiDaoIOException; import com.media.dongfeng.exception.ZhiDaoParseException; import com.media.dongfeng.model.Content; import com.media.dongfeng.model.ContentList; import com.media.dongfeng.model.Info; import com.media.dongfeng.model.InfoList; import com.media.dongfeng.model.User; import com.media.dongfeng.net.NetDataSource; import com.media.dongfeng.utils.Constants; import com.media.dongfeng.utils.Utils; import com.media.dongfeng.view.InfoTopView; import com.media.dongfeng.view.InfoView; import com.media.dongfeng.view.ItemView; import com.media.dongfeng.view.RTPullListView; public class InfoFragment extends Fragment { private GetDataTask mGetDataTask; private EditText etSearchText; private ImageView mClearBtn; private TextView mEmptyView; private String mSearchText; private List<Info> mHuodongList = new ArrayList<Info>(); private HuodongAdapter mAdapter; private HuodongAdapter mSearchAdapter; private ProgressBar mRrefresh; private ProgressBar mLoadMore; private boolean isMore = false; private boolean mHasInit = false; private boolean mIsShowSearch = false; public InfoFragment() { mAdapter = new HuodongAdapter(); mSearchAdapter = new HuodongAdapter(); mGetDataTask = new GetDataTask(mAdapter, mSearchAdapter); } @Override public void onCreate( Bundle savedInstanceState ) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); } @Override public void onActivityCreated( Bundle savedInstanceState ) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); mEmptyView = (TextView) getView().findViewById(R.id.empty); mRrefresh = (ProgressBar) getView().findViewById(R.id.refreshPB); mLoadMore = (ProgressBar) getView().findViewById(R.id.loadMorePB); RTPullListView mListView; RTPullListView mSearchListView; mListView = (RTPullListView) getView().findViewById(R.id.lvHuodong); mListView.setonRefreshListener(new RTPullListView.OnRefreshListener() { @Override public void onRefresh() { // TODO Auto-generated method stub try { if (TextUtils.isEmpty(mSearchText)) { mGetDataTask.switchListViewMode(false); mGetDataTask.RefreshList(MainTabActivity.mUser, true); } } catch (Exception e) {} } }); mListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged( AbsListView view, int scrollState ) { if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){ int pos = view.getLastVisiblePosition(); if(pos>20&&pos == view.getCount()-1){ mGetDataTask.switchListViewMode(false); mGetDataTask.LoadMoreList(MainTabActivity.mUser); } } } @Override public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount ) { // Log.d("zzm", "y:"+mListView.getSelectedItemPosition()); // TODO Auto-generated method stub // if (TextUtils.isEmpty(mSearchText)) { // if (totalItemCount > 0 && firstVisibleItem>0&& totalItemCount == firstVisibleItem + visibleItemCount) { //// Log.d("net", "mListView onScroll loadMore firstVisibleItem="+firstVisibleItem+" visibleItemCount="+visibleItemCount+" totalItemCount="+totalItemCount); //// mGetDataTask.switchListViewMode(false); //// mGetDataTask.LoadMoreList(MainTabActivity.mUser); // } // } } }); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { // TODO Auto-generated method stub if (position <= 0) { return; } Info content = mGetDataTask.mList.get(position-1); FragmentTransaction transation = getFragmentManager().beginTransaction(); transation.setCustomAnimations(R.anim.enter_right, 0, 0, 0); InfoDetailFragment fragment = new InfoDetailFragment(content); transation.replace(R.id.huodong_container, fragment, InfoActivity.HUODONG_DETAIL_FRAGMENT); transation.addToBackStack(InfoActivity.HUODONG_DETAIL_FRAGMENT); transation.commit(); } }); mListView.setAdapter(mAdapter); mSearchListView = (RTPullListView) getView().findViewById(R.id.lvSearchHuodong); mSearchListView.setonRefreshListener(new RTPullListView.OnRefreshListener() { @Override public void onRefresh() { // TODO Auto-generated method stub try { if (!TextUtils.isEmpty(mSearchText)) { mGetDataTask.switchListViewMode(true); mGetDataTask.RefreshSearchList(MainTabActivity.mUser, mSearchText, true); } } catch (Exception e) {} } }); mSearchListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged( AbsListView view, int scrollState ) { if(scrollState == OnScrollListener.SCROLL_STATE_IDLE){ int pos = view.getLastVisiblePosition(); if(pos>20&&pos == view.getCount()-1){ mGetDataTask.switchListViewMode(false); mGetDataTask.LoadMoreList(MainTabActivity.mUser); } } } @Override public void onScroll( AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount ) { // TODO Auto-generated method stub // if (!TextUtils.isEmpty(mSearchText)) { // if (totalItemCount > 0 && totalItemCount == firstVisibleItem + visibleItemCount) { //// Log.d("net", "mSearchListView onScroll loadMore firstVisibleItem="+firstVisibleItem+" visibleItemCount="+visibleItemCount+" totalItemCount="+totalItemCount); // mGetDataTask.switchListViewMode(true); // mGetDataTask.LoadMoreSearchList(MainTabActivity.mUser, mSearchText); // } // } } }); mSearchListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick( AdapterView<?> parent, View view, int position, long id ) { // TODO Auto-generated method stub if (position <= 0) { return; } Info content = mGetDataTask.mSearchList.get(position-1); FragmentTransaction transation = getFragmentManager().beginTransaction(); transation.setCustomAnimations(R.anim.enter_right, 0, 0, 0); InfoDetailFragment fragment = new InfoDetailFragment(content); transation.replace(R.id.huodong_container, fragment, InfoActivity.HUODONG_DETAIL_FRAGMENT); transation.addToBackStack(InfoActivity.HUODONG_DETAIL_FRAGMENT); transation.commit(); } }); mSearchListView.setAdapter(mSearchAdapter); mGetDataTask.setContext(getActivity()); mGetDataTask.setListView(mListView); mGetDataTask.setSearchListView(mSearchListView); mGetDataTask.setEmptyView(mEmptyView); if (mIsShowSearch) { mSearchListView.setVisibility(View.VISIBLE); mListView.setVisibility(View.GONE); } else { mSearchListView.setVisibility(View.GONE); mListView.setVisibility(View.VISIBLE); } mClearBtn = (ImageView) getView().findViewById(R.id.clearBtn); mClearBtn.setVisibility(View.GONE); mClearBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick( View v ) { mSearchText = null; etSearchText.setText(""); mGetDataTask.switchListViewMode(false); } }); etSearchText = (EditText) getView().findViewById(R.id.etSearchText); etSearchText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(!hasFocus){ InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(etSearchText.getWindowToken(), 0); } } }); etSearchText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) { mClearBtn.setVisibility(View.GONE); mGetDataTask.switchListViewMode(false); } else { mClearBtn.setVisibility(View.VISIBLE); } } }); etSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction( TextView v, int actionId, KeyEvent event ) { // TODO Auto-generated method stub // if (EditorInfo.IME_ACTION_SEARCH == actionId || EditorInfo.IME_ACTION_DONE == actionId) { mSearchText = v.getText().toString(); if (TextUtils.isEmpty(mSearchText)) { mGetDataTask.switchListViewMode(false); mGetDataTask.RefreshList(MainTabActivity.mUser, false); } else { mSearchText = mSearchText.replaceAll(" ", "-"); mGetDataTask.switchListViewMode(true); mGetDataTask.RefreshSearchList(MainTabActivity.mUser, mSearchText, false); } InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); // } return true; } }); if (!mHasInit) { mGetDataTask.switchListViewMode(false); mGetDataTask.RefreshList(MainTabActivity.mUser, false); mHasInit = true; } } // private void addHasReadContent(Info content) { //// for (Info c : mHuodongList) { //// if (c.iid == content.iid) { //// c.isRead = true; //// return; //// } //// } // content.isRead = true; //// mHuodongList.add(content); // } // private Info hasReadContent(Info content) { // content.isRead = true; // return content; //// boolean localFlag = false; //// for (Info c : mHuodongList) { //// if (c.iid == content.iid) { //// localFlag = c.isRead; //// break; //// } //// } //// if (localFlag) { //// content.isRead = true; //// return content; //// } else { //// return content; //// } // } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { // TODO Auto-generated method stub return inflater.inflate(R.layout.huodong_layout, null); } boolean isNeedRefresh = true; public void needRefresh(boolean s){ isNeedRefresh = s; } public void hideLoading(){ mLoadMore.setVisibility(View.GONE); mRrefresh.setVisibility(View.GONE); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); if(isNeedRefresh){ mGetDataTask.RefreshList(MainTabActivity.mUser, false); isNeedRefresh = false; } mGetDataTask.notifyListView(); mGetDataTask.notifySearchListView(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); if (MainTabActivity.mUser != null) { Utils.saveInfoCidList(getActivity(), MainTabActivity.mUser, mHuodongList); } if (mGetDataTask.mListView.getVisibility() == View.VISIBLE) { mIsShowSearch = false; } else { mIsShowSearch = true; } } private class HuodongAdapter extends BaseAdapter { private List<Info> innerList = new ArrayList<Info>(); @Override public int getCount() { return innerList.size(); } @Override public Object getItem( int position ) { return innerList.get(position); } @Override public long getItemId( int position ) { return position; } @Override public View getView( int position, View convertView, ViewGroup parent ) { // TODO Auto-generated method stub Info content = innerList.get(position); View v = null; int color; if (position % 2 == 0) { color = 0xFFE4E6E5; } else { color = 0xFFD6D6D6; } if(position == 0){ InfoTopView iv = new InfoTopView(getActivity()); iv.update(content, color); v = iv; }else{ InfoView iv = new InfoView(getActivity()); iv.update(content, color); v = iv; } return v; } public void notifyDataChange(List<Info> list) { this.innerList.clear(); if (list != null) { innerList.addAll(list); } notifyDataSetChanged(); if (mGetDataTask.mSearchListView.getVisibility() != View.GONE) { if (innerList.isEmpty()) { mEmptyView.setVisibility(View.VISIBLE); } else { mEmptyView.setVisibility(View.GONE); } } if (mGetDataTask.mListView.getVisibility() != View.GONE) { mEmptyView.setVisibility(View.GONE); } } } private class GetDataTask { private int mPage; private int mSearchPage; private List<Info> mList = new ArrayList<Info>(); private List<Info> mSearchList = new ArrayList<Info>(); private RTPullListView mListView; private HuodongAdapter mAdapter; private boolean mIsListTaskFree = true; private RTPullListView mSearchListView; private HuodongAdapter mSearchAdapter; private boolean mIsSearchListTaskFree = true; private Context mContext; private TextView mEmptyView; public GetDataTask(HuodongAdapter adapter, HuodongAdapter searchAdapter) { this.mAdapter = adapter; this.mSearchAdapter = searchAdapter; } public void setContext(Context context) { this.mContext = context; } public void setListView(RTPullListView listview) { this.mListView = listview; } public void setSearchListView(RTPullListView searchListview) { this.mSearchListView = searchListview; } public void setEmptyView(TextView v) { this.mEmptyView = v; } public void switchListViewMode(boolean isSearchMode) { if (isSearchMode) { mListView.setVisibility(View.GONE); mSearchListView.setVisibility(View.VISIBLE); } else { mListView.setVisibility(View.VISIBLE); mSearchListView.setVisibility(View.GONE); mEmptyView.setVisibility(View.GONE); } } public void notifyListView() { mAdapter.notifyDataSetChanged(); } public void notifySearchListView() { mSearchAdapter.notifyDataSetChanged(); } public void RefreshList(User user, boolean isShowPullDownView) { if (user == null || !mIsListTaskFree) { if (isShowPullDownView) { mListView.onRefreshComplete(); } return; } mIsListTaskFree = false; try { mPage = 1; new GetDataTaskInternal().execute( new Object[]{user, mPage, null, true, isShowPullDownView}); } catch (RejectedExecutionException e) { if (isShowPullDownView) { mListView.onRefreshComplete(); } mIsListTaskFree = true; } } public void LoadMoreList(User user) { if (user == null) { return; } if (!mIsListTaskFree) { return; } mIsListTaskFree = false; try { new GetDataTaskInternal().execute( new Object[]{user, mPage+1, null, false, false}); } catch (RejectedExecutionException e) { mIsListTaskFree = true; } } public void RefreshSearchList(User user, String keyword, boolean isShowPullDownView) { if (user == null || !mIsSearchListTaskFree) { if (isShowPullDownView) { mSearchListView.onRefreshComplete(); } return; } mIsSearchListTaskFree = false; try { mSearchPage = 1; new GetDataTaskInternal().execute( new Object[]{user, mSearchPage, keyword, true, isShowPullDownView}); } catch (RejectedExecutionException e) { if (isShowPullDownView) { mSearchListView.onRefreshComplete(); } mIsSearchListTaskFree = true; } } public void LoadMoreSearchList(User user, String keyword) { if (user == null) { return; } if (!mIsSearchListTaskFree) { return; } mIsSearchListTaskFree = false; try { new GetDataTaskInternal().execute( new Object[]{user, mSearchPage+1, keyword, false, false}); } catch (RejectedExecutionException e) { mIsSearchListTaskFree = true; } } private class GetDataTaskInternal extends AsyncTask<Object, Void, List<Info>> { private boolean isSearch = false; private boolean isRefresh; private boolean isShowPullDownView; @Override protected List<Info> doInBackground(Object... params) { User user = (User) params[0]; int page = (Integer) params[1]; String keyword = (String) params[2]; if (TextUtils.isEmpty(keyword)) { isSearch = false; } else { isSearch = true; } isRefresh = (Boolean) params[3]; isShowPullDownView = (Boolean) params[4]; if(isRefresh && !isShowPullDownView){ InfoFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { mRrefresh.setVisibility(View.VISIBLE); } }); } if(!isSearch && page > 1 && isMore){ InfoFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { mLoadMore.setVisibility(View.VISIBLE); } }); } try { InfoList infoList = NetDataSource.getInstance(mContext) .getInfoList(user, page, Constants.LIST_COUNT, keyword); if (infoList != null && !infoList.mInfoList.isEmpty()) { return infoList.mInfoList; } } catch (ZhiDaoParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ZhiDaoApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ZhiDaoIOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(List<Info> result) { super.onPostExecute(result); hideLoading(); if (isSearch) { if (isRefresh) { //refresh mSearchList.clear(); if (result == null || result.isEmpty()) { // Log.d("net", "GetDataTaskInternal onPostExecute isSearch refresh result is empty"); mSearchListView.setSelection(0); mSearchAdapter.notifyDataChange(mSearchList); } else { // Log.d("net", "GetDataTaskInternal onPostExecute isSearch refresh result not empty"); mSearchList.addAll(result); mSearchListView.setSelection(0); mSearchAdapter.notifyDataChange(mSearchList); } } else { //load more if (result != null && !result.isEmpty()) { // Log.d("net", "GetDataTaskInternal onPostExecute isSearch loadmore result not empty"); int oldSize = mSearchList.size(); if (oldSize == 0) { mSearchListView.setSelection(0); } else { mSearchListView.setSelection(oldSize-1); } mSearchList.addAll(result); mSearchPage++; mSearchAdapter.notifyDataChange(mSearchList); } else { // Log.d("net", "GetDataTaskInternal onPostExecute isSearch loadmore result is empty"); } } if (isShowPullDownView) { mSearchListView.onRefreshComplete(); } mIsSearchListTaskFree = true; } else { if(isRefresh && result!= null && result.size() == Constants.LIST_COUNT){ isMore = true; }else if(!isRefresh&&result!= null && mList!=null && result.size() - mList.size() == Constants.LIST_COUNT){ isMore = true; }else{ isMore = false; } if (isRefresh) { //refresh mList.clear(); if (result == null || result.isEmpty()) { // Log.d("net", "GetDataTaskInternal onPostExecute not isSearch refresh result is empty"); mListView.setSelection(0); mAdapter.notifyDataChange(mList); } else { // Log.d("net", "GetDataTaskInternal onPostExecute not isSearch refresh result not empty"); mList.addAll(result); mListView.setSelection(0); mAdapter.notifyDataChange(mList); } } else { //load more if (result != null && !result.isEmpty()) { // Log.d("net", "GetDataTaskInternal onPostExecute not isSearch loadmore result not empty"); int oldSize = mList.size(); if (oldSize == 0) { mListView.setSelection(0); } else { mListView.setSelection(oldSize-1); } mList.addAll(result); mPage++; mAdapter.notifyDataChange(mList); } else { // Log.d("net", "GetDataTaskInternal onPostExecute not isSearch loadmore result is empty"); } } if (isShowPullDownView) { mListView.onRefreshComplete(); } mIsListTaskFree = true; } } } } }
true
15f1bae8e17b0e78e5be0488d86e72779d2a8499
Java
ecen489/Topic_22_Google_Maps
/app/src/main/java/com/example/t20_ggl_maps/MapsActivity.java
UTF-8
2,961
2.109375
2
[]
no_license
package com.example.t20_ggl_maps; import android.Manifest; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; LatLng loc = new LatLng(30.5610, -96.3628); setMyMap(loc, "CLL"); } public void click1(View view) { LatLng loc = new LatLng(30.5610, -96.3628); setMyMap(loc, "CLL"); } public void click2(View view) { LatLng loc = new LatLng(37.6213, -122.3790); setMyMap(loc, "SFO"); } public void setMyMap(LatLng myLatLng, String name) { mMap.addMarker(new MarkerOptions().position(myLatLng).title(name)); mMap.moveCamera(CameraUpdateFactory.newLatLng(myLatLng)); } public void click3(View view) { mMap.animateCamera(CameraUpdateFactory.zoomIn()); } public void click4(View view) { mMap.animateCamera(CameraUpdateFactory.zoomOut()); } public void clickLoc(View view) { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); return; } else { Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc != null) { double myLat = loc.getLatitude(); double myLng = loc.getLongitude(); LatLng locn = new LatLng(myLat, myLng); setMyMap(locn, "Me"); } } } }
true
f165d04a42744ee9b970ffc99d7a013ab65371e1
Java
ondrejfialka/hatchery1
/starter/src/main/java/eu/unicorn/starter/plugins/JDPlugin.java
UTF-8
199
2.046875
2
[]
no_license
package eu.unicorn.starter.plugins; public class JDPlugin implements GreetingsPlugin{ public String getGreeting(String name) { return "How are you " + name + "?"; } }
true
ed8bf45f994a5ecb97ffed1af844347f1b3481c8
Java
lanjie1313/find-express-android
/src/com/runye/express/utils/AssembleAddress.java
UTF-8
1,117
2.734375
3
[]
no_license
package com.runye.express.utils; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; /** * * @ClassName: AssembleAddress * @Description: 地址拼装 * @author LanJie.Chen * @date 2014-7-9 下午1:31:30 * @version V1.0 * @Company:山西润叶网络科技有限公司 */ public class AssembleAddress { /** * */ /** ?...&.. */ public static String questionMark(String path, Map<String, String> params) { // StringBuilder是用来组拼请求地址和参数 StringBuilder sb = new StringBuilder(); sb.append(path).append("?"); if (params != null && params.size() != 0) { for (Map.Entry<String, String> entry : params.entrySet()) { // 如果请求参数中有中文,需要进行URLEncoder编码 gbk/utf8 try { sb.append(entry.getKey()) .append("=") .append(URLEncoder.encode(entry.getValue(), "utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } sb.append("&"); } sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } }
true
00b176bb14e4a2d2f76fb20c2b6436c5daca40e4
Java
geekmc/java
/factor/java/BlueBalPen.java
UTF-8
148
2
2
[]
no_license
package com.factor.java; public class BlueBalPen extends BallPen{ @Override public PenCore getPenCore() { return new BluePenCore(); } }
true
8d9e146d6fe2d07a701a6309b47d5c4b0cc11817
Java
ForDreamCat/FrameworkStudy
/StudyFramWork/app/src/main/java/com/bwpsoft/studyframwork/data/login/LoginRepository.java
UTF-8
1,286
2.015625
2
[]
no_license
package com.bwpsoft.studyframwork.data.login; import android.support.annotation.NonNull; import com.bwpsoft.studyframwork.common.di.ActivityScope; import com.bwpsoft.studyframwork.data.login.local.ILoginLocalApi; import com.bwpsoft.studyframwork.data.login.remote.ILoginRemoteApi; import com.bwpsoft.studyframwork.utils.handler.IJsonHandler; import javax.inject.Inject; import javax.inject.Singleton; import io.reactivex.Observable; import static com.google.common.base.Preconditions.checkNotNull; /** * Created by ZH on 2017/7/27. */ @Singleton public class LoginRepository implements ILoginRemoteApi,ILoginLocalApi { private ILoginRemoteApi iLoginRemoteApi; private IJsonHandler mJsonHandle; @Inject public LoginRepository(@NonNull ILoginRemoteApi iLoginRemoteApi, @NonNull IJsonHandler jsonHandler) { this.iLoginRemoteApi = checkNotNull(iLoginRemoteApi); this.mJsonHandle = checkNotNull(jsonHandler); } @Override public Observable<Object> loginRemote(String userName, String password) { return iLoginRemoteApi.loginRemote(userName, password); } @Override public Observable<Object> logoutRemote() { return null; } @Override public void logoutLocal() { } }
true
73c2ed3141b9dd407168522204d9d02f20d46dc4
Java
liuyijiang/spring-deep-study
/src/com/java/concurrent/atomic/TestAtomic.java
UTF-8
421
2.15625
2
[]
no_license
package com.java.concurrent.atomic; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class TestAtomic { /** * @param args */ public static void main(String[] args) { // todo auto-generated method stub } public void test(){ new Thread(new Runnable() { @Override public void run() { while(true){ } } }).start(); } }
true
9d1cbb004496455f6b889789ac25da738589c7e7
Java
ivanandryuschenko/java-learning-sber
/task7/plugin-manager/src/main/java/EncryptedClassLoader.java
UTF-8
1,067
2.8125
3
[]
no_license
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; public class EncryptedClassLoader extends ClassLoader { private final String key; private final File dir; public EncryptedClassLoader(String key, File dir, ClassLoader parent) { super(parent); this.key = key; this.dir = dir; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { File f = new File(dir.getPath() + File.separatorChar + name.replace('.', File.separatorChar) + ".class.crypt"); InputStream in = new BufferedInputStream(new FileInputStream(f)); byte[] crypted = new byte[in.available()]; in.read(crypted); byte[] decrypted = SimpleEncryptor.decrypt(crypted, key); Class c = defineClass(name, decrypted, 0, decrypted.length); in.close(); return c; } catch (Exception e) { throw new ClassNotFoundException(); } } }
true
8b49f32d76fcb7d5f7361515326e21fdc017c459
Java
AppSecAI-TEST/qiyedaxue
/src/main/java/com/chinamobo/ue/system/entity/TomForumPost.java
UTF-8
10,732
1.890625
2
[]
no_license
package com.chinamobo.ue.system.entity; import java.util.Date; public class TomForumPost { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.POST_ID * * @mbggenerated */ private Integer postId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.PLATE_ID * * @mbggenerated */ private Integer plateId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.POST_TITLE * * @mbggenerated */ private String postTitle; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.POST_PICTURE * * @mbggenerated */ private String postPicture; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.POST_DETAILS * * @mbggenerated */ private String postDetails; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.POST_STATUS * * @mbggenerated */ private String postStatus; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.COMMENT_COUNT * * @mbggenerated */ private Integer commentCount; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.PRAISE_COUNT * * @mbggenerated */ private Integer praiseCount; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.VIEW_COUNT * * @mbggenerated */ private Integer viewCount; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.EMP_CODE * * @mbggenerated */ private String empCode; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.CREATE_TIME * * @mbggenerated */ private Date createTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column TOM_FORUM_POST.DELETED * * @mbggenerated */ private String deleted; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.POST_ID * * @return the value of TOM_FORUM_POST.POST_ID * * @mbggenerated */ public Integer getPostId() { return postId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.POST_ID * * @param postId the value for TOM_FORUM_POST.POST_ID * * @mbggenerated */ public void setPostId(Integer postId) { this.postId = postId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.PLATE_ID * * @return the value of TOM_FORUM_POST.PLATE_ID * * @mbggenerated */ public Integer getPlateId() { return plateId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.PLATE_ID * * @param plateId the value for TOM_FORUM_POST.PLATE_ID * * @mbggenerated */ public void setPlateId(Integer plateId) { this.plateId = plateId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.POST_TITLE * * @return the value of TOM_FORUM_POST.POST_TITLE * * @mbggenerated */ public String getPostTitle() { return postTitle; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.POST_TITLE * * @param postTitle the value for TOM_FORUM_POST.POST_TITLE * * @mbggenerated */ public void setPostTitle(String postTitle) { this.postTitle = postTitle == null ? null : postTitle.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.POST_PICTURE * * @return the value of TOM_FORUM_POST.POST_PICTURE * * @mbggenerated */ public String getPostPicture() { return postPicture; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.POST_PICTURE * * @param postPicture the value for TOM_FORUM_POST.POST_PICTURE * * @mbggenerated */ public void setPostPicture(String postPicture) { this.postPicture = postPicture == null ? null : postPicture.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.POST_DETAILS * * @return the value of TOM_FORUM_POST.POST_DETAILS * * @mbggenerated */ public String getPostDetails() { return postDetails; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.POST_DETAILS * * @param postDetails the value for TOM_FORUM_POST.POST_DETAILS * * @mbggenerated */ public void setPostDetails(String postDetails) { this.postDetails = postDetails == null ? null : postDetails.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.POST_STATUS * * @return the value of TOM_FORUM_POST.POST_STATUS * * @mbggenerated */ public String getPostStatus() { return postStatus; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.POST_STATUS * * @param postStatus the value for TOM_FORUM_POST.POST_STATUS * * @mbggenerated */ public void setPostStatus(String postStatus) { this.postStatus = postStatus == null ? null : postStatus.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.COMMENT_COUNT * * @return the value of TOM_FORUM_POST.COMMENT_COUNT * * @mbggenerated */ public Integer getCommentCount() { return commentCount; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.COMMENT_COUNT * * @param commentCount the value for TOM_FORUM_POST.COMMENT_COUNT * * @mbggenerated */ public void setCommentCount(Integer commentCount) { this.commentCount = commentCount; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.PRAISE_COUNT * * @return the value of TOM_FORUM_POST.PRAISE_COUNT * * @mbggenerated */ public Integer getPraiseCount() { return praiseCount; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.PRAISE_COUNT * * @param praiseCount the value for TOM_FORUM_POST.PRAISE_COUNT * * @mbggenerated */ public void setPraiseCount(Integer praiseCount) { this.praiseCount = praiseCount; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.VIEW_COUNT * * @return the value of TOM_FORUM_POST.VIEW_COUNT * * @mbggenerated */ public Integer getViewCount() { return viewCount; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.VIEW_COUNT * * @param viewCount the value for TOM_FORUM_POST.VIEW_COUNT * * @mbggenerated */ public void setViewCount(Integer viewCount) { this.viewCount = viewCount; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.EMP_CODE * * @return the value of TOM_FORUM_POST.EMP_CODE * * @mbggenerated */ public String getEmpCode() { return empCode; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.EMP_CODE * * @param empCode the value for TOM_FORUM_POST.EMP_CODE * * @mbggenerated */ public void setEmpCode(String empCode) { this.empCode = empCode == null ? null : empCode.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.CREATE_TIME * * @return the value of TOM_FORUM_POST.CREATE_TIME * * @mbggenerated */ public Date getCreateTime() { return createTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.CREATE_TIME * * @param createTime the value for TOM_FORUM_POST.CREATE_TIME * * @mbggenerated */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column TOM_FORUM_POST.DELETED * * @return the value of TOM_FORUM_POST.DELETED * * @mbggenerated */ public String getDeleted() { return deleted; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column TOM_FORUM_POST.DELETED * * @param deleted the value for TOM_FORUM_POST.DELETED * * @mbggenerated */ public void setDeleted(String deleted) { this.deleted = deleted == null ? null : deleted.trim(); } }
true
8c849cde3554f42c1595e3c670d89959a8df8d92
Java
benjamin05/jpv-mv
/core/src/main/groovy/mx/lux/pos/java/repository/TmpServiciosJava.java
UTF-8
2,424
2.1875
2
[]
no_license
package mx.lux.pos.java.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; public class TmpServiciosJava { Integer idServ; String idFactura; String idCliente; String cliente; String dejo; String instruccion; String emp; String servicio; String condicion; Date fechaProm; public Integer getIdServ() { return idServ; } public void setIdServ(Integer idServ) { this.idServ = idServ; } public String getIdFactura() { return idFactura; } public void setIdFactura(String idFactura) { this.idFactura = idFactura; } public String getIdCliente() { return idCliente; } public void setIdCliente(String idCliente) { this.idCliente = idCliente; } public String getCliente() { return cliente; } public void setCliente(String cliente) { this.cliente = cliente; } public String getDejo() { return dejo; } public void setDejo(String dejo) { this.dejo = dejo; } public String getInstruccion() { return instruccion; } public void setInstruccion(String instruccion) { this.instruccion = instruccion; } public String getEmp() { return emp; } public void setEmp(String emp) { this.emp = emp; } public String getServicio() { return servicio; } public void setServicio(String servicio) { this.servicio = servicio; } public String getCondicion() { return condicion; } public void setCondicion(String condicion) { this.condicion = condicion; } public Date getFechaProm() { return fechaProm; } public void setFechaProm(Date fechaProm) { this.fechaProm = fechaProm; } public TmpServiciosJava setValores( ResultSet rs) throws SQLException { this.setIdServ(rs.getInt("id_serv")); this.setIdFactura(rs.getString("id_factura")); this.setIdCliente(rs.getString("id_cliente")); this.setCliente(rs.getString("cliente")); this.setDejo(rs.getString("dejo")); this.setInstruccion(rs.getString("instruccion")); this.setEmp(rs.getString("emp")); this.setServicio(rs.getString("servicio")); this.setCondicion(rs.getString("condicion")); this.setFechaProm(rs.getDate("fecha_prom")); return this; } }
true
b6a8377232e489e487ca532a1cd6b77d19f66f35
Java
VijayEluri/brainflow
/src/main/java/brainflow/image/space/ICoordinateSpace.java
UTF-8
927
2.0625
2
[]
no_license
package brainflow.image.space; import brainflow.image.anatomy.AnatomicalAxis; import brainflow.image.anatomy.BrainLoc; import brainflow.image.anatomy.Anatomy; import brainflow.image.axis.CoordinateAxis; import brainflow.utils.IDimension; /** * Created by IntelliJ IDEA. * User: Brad Buchsbaum * Date: Apr 19, 2007 * Time: 1:08:53 PM * To change this template use File | Settings | File Templates. */ public interface ICoordinateSpace { public double getExtent(Axis axis); public double getExtent(AnatomicalAxis axis); public Axis findAxis(AnatomicalAxis axis); public AnatomicalAxis getAnatomicalAxis(Axis axis); public CoordinateAxis getImageAxis(Axis axis); public CoordinateAxis getImageAxis(AnatomicalAxis axis, boolean ignoreDirection); public BrainLoc getCentroid(); public int getNumDimensions(); public Anatomy getAnatomy(); public IDimension<Float> getOrigin(); }
true
e41096151a70329a9e4e432ebc29145c433cbaf9
Java
SantosLopezLozano/Java
/Hola_Mundo/Ejercicio3.java
UTF-8
812
3.515625
4
[]
no_license
/** * Coloreado de texto * * Muestra varias columnas de palabras y traducciones. * he usado el printf en vez del \t por diversas razones * @author Santos López Lozano */ public class Ejercicio3 { public static void main(String[] args) { System.out.printf("%-10s %s\n", "computer", "ordenador"); System.out.printf("%-10s %s\n", "student", "alumno\\a"); System.out.printf("%-10s %s\n", "cat", "gato"); System.out.printf("%-10s %s\n", "penguin", "pingüino"); System.out.printf("%-10s %s\n", "machine", "máquina"); System.out.printf("%-10s %s\n", "nature", "naturaleza"); System.out.printf("%-10s %s\n", "light", "luz"); System.out.printf("%-10s %s\n", "green", "verde"); System.out.printf("%-10s %s\n", "book", "libro"); System.out.printf("%-10s %s\n", "pyramid", "pirámide"); } }
true
feb686c73bdc13942b2191b6c440cba79f8b386b
Java
Athalias/SysDrogaria
/src/br/com/Drogaria/Bean/AutenticacaoBean.java
ISO-8859-2
1,130
2.265625
2
[]
no_license
package br.com.Drogaria.Bean; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import org.primefaces.context.RequestContext; import br.com.Drogaria.Domain.UsuarioDM; import br.com.Drogaria.Repository.UsuarioSelect; import br.com.Drogaria.Util.JSFUtil; @ManagedBean @SessionScoped public class AutenticacaoBean { private UsuarioDM usuarioLogado; public UsuarioDM getUsuarioLogado() { if(usuarioLogado == null){ usuarioLogado = new UsuarioDM(); } return usuarioLogado; } public void setUsuarioLogado(UsuarioDM usuarioLogado) { this.usuarioLogado = usuarioLogado; } public void autenticar(){ RequestContext context = RequestContext.getCurrentInstance(); boolean loggedIn = false; UsuarioSelect uss = new UsuarioSelect(); List<UsuarioDM> usuList = uss.listarLogin(usuarioLogado.getLogin(), usuarioLogado.getSenha()); if(usuList.size()==0){ JSFUtil.addMensagemErro("Login ou Senha invlidos"); }else{ JSFUtil.addMensagemSucesso("Logado com sucesso"); loggedIn = true; } context.addCallbackParam("loggedIn", loggedIn); } }
true
1cec59dd28b7d465e16bd81a1c41de33e44a1def
Java
contact2kb/cb-sp-api
/src/main/java/test/CbTest.java
UTF-8
3,003
2.015625
2
[]
no_license
package test; import com.couchbase.client.java.Bucket; import com.couchbase.client.java.document.json.JsonObject; import test.service.TestServ; import java.util.UUID; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/add") public class CbTest { final static Logger logger = Logger.getLogger("com.couchbase.client"); private final Bucket bucket; @Autowired public CbTest(Bucket bucket) { this.bucket = bucket; } /** * Create a rec , will get all the required data from the jmeter/postman/application ,out side this method * @return */ @RequestMapping(value="/records", method=RequestMethod.POST ,produces="text/html") public Object create(@RequestBody String json) { logger.info("Method records"); JsonObject jsonData = JsonObject.fromJson(json.toString()); return TestServ.createAndGet(bucket, jsonData); } /** * Create a rec , this method will generate required dat here and pushed to the couchbase. * @return */ @RequestMapping(value="/generats", method=RequestMethod.POST,produces="text/html") public Object createRec() { logger.info("Method generats"); String addString = "{\"recordTypeCode\":\"D\",\"transactionRefNumber\":\"" + "320133500" + "\",\"transactionDate\":\"11/08/2013\",\"transactionAmount\":" + 100 + "." + 00 + ",\"authorizationCode\":\"\",\"postDate\":\"12/16/2013\",\"transactionCode\":\"0181\",\"referenceSeNumber\":\"1092817261\",\"transPlasticNumber\":\"XX8349261405000\",\"refBatchNumber\":\"\",\"subCode\":\"\",\"billDescLine1Text\":\"\",\"billDescLine2Text\":\"\",\"billDescLine3Text\":\"\",\"refBillCCYCode\":\"\",\"seNumber\":\"\",\"rocInvoiceNumber\":\"\",\"seName\":\"\",\"productNumberCode\":\"ZC\",\"captureCenterRefNumber\":\"\",\"airLineTicketNumber\":\"\",\"airLineDeparDateDesc\":\"\",\"airLineDocTypeCode\":\"\",\"airportFromName\":\"\",\"accIdContextId\":\"TRIUMP\",\"billPostalCode\":\"850248688\",\"billRegionCode\":\"AZ\",\"billCountryCode\":\"US\",\"accLevelTypeCode\":\"B\",\"accStatusCode\":\"\",\"accAgeCode\":\"0\",\"productId\":\"YY\",\"accEffectiveDate\":\"10/04/1996\",\"prevProdIdentifierText\":\"YY\",\"billCycleCode\":\"B12\",\"transIa\":\"YY\",\"transConfigCode\":\"ZC\",\"rocFileId\":\"" + "000000000" + 1 + "\"}"; JsonObject add = JsonObject.fromJson(addString); String uuid = UUID.randomUUID().toString(); return TestServ.createAndRead(bucket, add ,uuid); } }
true
2aadc87af3002d67c4c32fd492e78a18ed10b25f
Java
caveman-frak/java-core
/core-utilities/src/main/java/uk/co/bluegecko/core/util/resources/ResourceHandler.java
UTF-8
7,116
2.140625
2
[ "Apache-2.0" ]
permissive
package uk.co.bluegecko.core.util.resources; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Image; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.net.URL; import java.text.ChoiceFormat; import java.text.MessageFormat; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.KeyStroke; public class ResourceHandler implements PropertyChangeListener { private static final String LOCALE = "locale"; private static final Logger LOGGER = Logger.getLogger( "log.resources", "log.resources" ); private final PropertyChangeSupport support; private final ResourceHandler parent; private final String bundleName; private Locale locale; private ResourceBundle bundle; public ResourceHandler( final ResourceHandler parent, final String bundleName, final Locale locale ) { super(); support = new PropertyChangeSupport( this ); this.parent = parent; this.bundleName = bundleName; setLocale( locale ); if ( parent != null ) { parent.addLocaleListener( this ); } } public synchronized void setLocale( final Locale locale ) { this.locale = locale; final Locale oldValue = bundle != null ? bundle.getLocale() : null; bundle = ResourceBundle.getBundle( bundleName, locale ); support.firePropertyChange( LOCALE, oldValue, locale ); } public Locale getLocale() { return locale; } public ResourceBundle getBundle() { return bundle; } public Locale getMappedLocale() { return bundle.getLocale(); } public final String getString( final String key ) { return ( String ) getObject( key ); } public final String[] getStringArray( final String key ) { final Object result = getObject( key ); if ( result instanceof String[] ) { return ( String[] ) result; } else if ( result instanceof String ) { return ( ( String ) result ).split( "\\W" ); } return null; } @SuppressWarnings( "unused" ) public final Object getObject( final String key ) { try { synchronized ( this ) { return bundle.getObject( key ); } } catch ( final MissingResourceException ex ) { if ( parent != null ) { return parent.getObject( key ); } return null; } } public String getMessage( final String key, final Object... params ) { final String text = getString( key ); if ( text != null ) { return MessageFormat.format( text, params ); } return null; } public String getChoice( final String key, final double value ) { final String text = getString( key ); if ( text != null ) { final ChoiceFormat choice = new ChoiceFormat( text ); return choice.format( value ); } return null; } public KeyStroke getKeyStroke( final String key ) { final String text = getString( key ); if ( text != null ) { final KeyStroke keyStroke = KeyStroke.getKeyStroke( text ); if ( keyStroke == null && LOGGER.isLoggable( Level.FINE ) ) { LOGGER.log( Level.FINE, "i18n.unable-to-parse-keystroke", new Object[] { key, text } ); } return keyStroke; } return null; } public Boolean getBoolean( final String key ) { final String text = getString( key ); if ( text != null ) { if ( text.equalsIgnoreCase( "true" ) ) { return Boolean.TRUE; } else if ( text.equalsIgnoreCase( "false" ) ) { return Boolean.FALSE; } else { if ( LOGGER.isLoggable( Level.FINE ) ) { LOGGER.log( Level.FINE, "i18n.unable-to-parse-boolean", new Object[] { key, text } ); } } } return null; } @SuppressWarnings( { "boxing", "unused" } ) public Integer getInteger( final String key ) { final String text = getString( key ); if ( text != null ) { try { if ( Character.isAlphabetic( text.codePointAt( 0 ) ) ) { return text.codePointAt( 0 ); } else if ( text.startsWith( "0x" ) ) { return Integer.parseInt( text.split( "x", 2 )[1], 16 ); } return Integer.valueOf( text ); } catch ( final NumberFormatException ex ) { if ( LOGGER.isLoggable( Level.FINE ) ) { LOGGER.log( Level.FINE, "i18n.unable-to-parse-integer", new Object[] { key, text } ); } } } return null; } @SuppressWarnings( "unused" ) public Double getDouble( final String key ) { final String text = getString( key ); if ( text != null ) { try { return Double.valueOf( text ); } catch ( final NumberFormatException ex ) { if ( LOGGER.isLoggable( Level.FINE ) ) { LOGGER.log( Level.FINE, "i18n.unable-to-parse-double", new Object[] { key, text } ); } } } return null; } public URL getURL( final String key ) { final String text = getString( key ); URL url = null; if ( text != null ) { url = getClass().getClassLoader() .getResource( text ); if ( url == null ) { url = ClassLoader.getSystemResource( text ); } } return url; } public ImageIcon getIcon( final String key ) { final String text = getString( key ); if ( text != null ) { final URL url = getURL( key ); if ( url != null ) { return new ImageIcon( url ); } if ( LOGGER.isLoggable( Level.FINE ) ) { LOGGER.log( Level.FINE, "i18n.unable-to-access-image", new Object[] { key, text } ); } } return null; } public Image getImage( final String key ) { final ImageIcon icon = getIcon( key ); return icon != null ? icon.getImage() : null; } @SuppressWarnings( "unused" ) public Color getColour( final String key ) { final String text = getString( key ); if ( text != null ) { try { if ( text.startsWith( "0x" ) ) { final int rgb = Integer.parseInt( text.split( "x", 2 )[1], 16 ); return new Color( rgb ); } return Color.decode( text ); } catch ( final NumberFormatException ex ) { if ( LOGGER.isLoggable( Level.FINE ) ) { LOGGER.log( Level.FINE, "i18n.unable-to-parse-colour", new Object[] { key, text } ); } } } return null; } public ComponentOrientation getComponentOrientation() { return ComponentOrientation.getOrientation( locale ); } @Override public void propertyChange( final PropertyChangeEvent e ) { if ( LOCALE.equals( e.getPropertyName() ) ) { setLocale( ( Locale ) e.getNewValue() ); } } public void addLocaleListener( final PropertyChangeListener listener ) { support.addPropertyChangeListener( LOCALE, listener ); } public void removeListener( final PropertyChangeListener listener ) { support.addPropertyChangeListener( LOCALE, listener ); } }
true
18c61507ab58dcd9f94966921f52fad083302bc7
Java
MegaGera/Cine-Swing
/src/vista/PlateaVista.java
UTF-8
3,041
2.546875
3
[]
no_license
package vista; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Icon; import javax.swing.JPanel; import control.OyenteVista; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; import modelo.Platea; import modelo.Butaca; /** * Vista Swing de la platea * */ public class PlateaVista extends JPanel { private static int ALTURA_FILA = 30; private static int ANCHURA_COLUMNA = 30; private Platea platea; private ButacaVista butacasVista[][]; private Butaca butacas[][]; private List<Butaca> reservas = new ArrayList<Butaca>(); private CineVista vista; /** * Construye el panel del la platea * */ PlateaVista(CineVista vista) { this.vista = vista; this.setPreferredSize(new Dimension(20 * ALTURA_FILA, 20 * ANCHURA_COLUMNA)); } /** * Muestra una platea * */ public void mostrarPlatea(Platea platea) { this.platea = platea; int filas = platea.devolverFilas(); int columnas = platea.devolverColumnas(); setLayout(new GridLayout(filas, columnas)); butacasVista = new ButacaVista[filas][columnas]; butacas = platea.devolverMatriz(); for (int fil = 0; fil < filas; fil++) { for (int col = 0; col < columnas; col++) { butacasVista[fil][col] = new ButacaVista(butacas[fil][col]); Butaca butacaSelecc = butacas[fil][col]; add(butacasVista[fil][col]); vista.ponerIconoButaca(butacas[fil][col]); if (!butacas[fil][col].pasillo()){ butacasVista[fil][col].addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { vista.notificacion(OyenteVista.Evento.RESERVAR, butacaSelecc); } }); } } } this.setPreferredSize(new Dimension(columnas * ALTURA_FILA, filas * ANCHURA_COLUMNA)); } /** * Devuelve el tamaño del tablero * */ public Dimension dimensionCasilla() { return butacasVista[0][0].getSize(); } /** * Pone un icono a una butaca * */ public void ponerIconoButaca(Butaca butaca, Icon icono) { int f = 0; int n = 0; while (butacas[f][n].devolverFila() != butaca.devolverFila()) { while (butacas[f][n].pasillo() && n < platea.devolverColumnas() - 1) { n++; } if (butacas[f][n].devolverFila() != butaca.devolverFila()) { f++; n = 0; } } while (butacas[f][n].devolverNumero() != butaca.devolverNumero()) { n++; } butacasVista[f][n].setIcon(icono); } }
true
117c62de78a4b7091b844764633b2e2698c1062f
Java
NuRrda/MyJava
/MyJava/src/leetcode/Prob72.java
UTF-8
353
2.640625
3
[]
no_license
package leetcode; public class Prob72 { static int count = 0; // public static void main(String[] args) { // minDistance("eat","rat"); // } // public static int minDistance(String word1, String word2, int count) { // if(word1.equalsIgnoreCase(word2)) // return count; // return Math.min(word1) // // } }
true
9b5198a2789abaa66d49b59bbdb51e9777407461
Java
dmorcellet/delta-downloads
/src/main/java/delta/downloads/async/BufferReceiver.java
UTF-8
852
2.84375
3
[]
no_license
package delta.downloads.async; import java.io.ByteArrayOutputStream; /** * Receives bytes into a buffer. * @author DAM */ public class BufferReceiver implements BytesReceiver { private ByteArrayOutputStream _bos; /** * Constructor. */ public BufferReceiver() { _bos=new ByteArrayOutputStream(); } @Override public boolean start() { _bos=new ByteArrayOutputStream(); return true; } @Override public boolean handleBytes(byte[] buffer, int offset, int count) { _bos.write(buffer,offset,count); return true; } @Override public boolean terminate() { return true; } /** * Get the result buffer. * @return the result buffer. */ public byte[] getBytes() { return _bos.toByteArray(); } @Override public String toString() { return "Buffer receiver"; } }
true
98d9a62a37e17ab2bdb17d64a2ad754bdad21005
Java
wujian199462/mayiedu
/src/test/java/test/TestNum.java
UTF-8
1,951
3.34375
3
[]
no_license
package test; public class TestNum { public static void main(String[] args) { String v1 =""; String v2 ="12345"; /* int v11 = Integer.parseInt(v1); int v22 = Integer.parseInt(v2); if(v11>v22){ System.out.println(1); }else{ System.out.println(-1); }*/ String s = null; String s1 = ""; System.out.println(s); System.out.println(s1); if("".endsWith(s1)){ System.out.println(1111); } int a = compareVersion(v1,v2); System.out.println(a); } /** * 版本号比较 * * @param v1 * @param v2 * @return 0代表相等,1代表左边大,-1代表右边大 * Utils.compareVersion("1.0.358_20180820090554","1.0.358_20180820090553")=1 */ public static int compareVersion(String v1, String v2) { if(v1==""||v1==null||v2==""||v2==null){ return 0; } if (v1.equals(v2)) { return 0; } String[] version1Array = v1.split("[._]"); String[] version2Array = v2.split("[._]"); int index = 0; int minLen = Math.min(version1Array.length, version2Array.length); long diff = 0; while (index < minLen && (diff = Long.parseLong(version1Array[index]) - Long.parseLong(version2Array[index])) == 0) { index++; } if (diff == 0) { for (int i = index; i < version1Array.length; i++) { if (Long.parseLong(version1Array[i]) > 0) { return 1; } } for (int i = index; i < version2Array.length; i++) { if (Long.parseLong(version2Array[i]) > 0) { return -1; } } return 0; } else { return diff > 0 ? 1 : -1; } } }
true
3b8d68ed1b489a0de3093fd974ba0c4708b0bdd0
Java
AmolRajeChavan/AmolSample
/app/src/main/java/com/threemb/app/AppConstants.java
UTF-8
3,719
1.867188
2
[]
no_license
package com.threemb.app; import android.content.Context; import android.support.multidex.MultiDexApplication; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; /** * Created by Amol on 1/28/2018. */ public class AppConstants extends MultiDexApplication { public static final String URL_GET_DATA = "http://adgebra.co.in/AdServing/PushNativeAds?pid=323&mkeys=&dcid=9&nads=2&deviceId=2&ip=203.109.101.177&url=demo.inuxu.org&pnToken=3KfutF4QBdjzSL9z"; public static final String GET_DATA ="lbl_get_data" ; public static final String KEY_FRAGEMENT_NAME = "fragement_name"; public static final String LOGIN_REQUEST ="login_request" ; public static final String SEND_INJEST ="injest_request"; public static final String SEND_NOTE="send_note"; public static final String PROJECT_SYNC_REQUEST ="sync_request" ; public static final String STATUS_DRAFT = "Draft"; public static final String STATUS_IN_PROGRESS = "In Progress"; public static final String STATUS_COMPLETED = "Completed"; public static final String STATUS_CANCELLED = "Cancelled"; public static final String STATUS_DRAFT_CODE = "3001"; public static final String STATUS_IN_PROGRESS_CODE = "3002"; public static final String STATUS_COMPLETED_CODE = "3003"; public static final String STATUS_CANCELLED_CODE = "3004"; public final static String JOB_STATUS_NON_STARTED="1"; public final static String JOB_STATUS_STARTED="2"; public final static String JOB_STATUS_COMPLETEDD="3"; public static final String STATUS = "status"; public static final String JOB_SYNC_REQUEST ="job_sync_request"; public static final String PROJECT_ASYNC="project_async"; public static final String PROJECTS = "projects"; public static final String JOBS ="jobs" ; public static final String JOB ="job" ; public static final String SENSOR_JOB ="job" ; public static final String PROJECT = "project"; public static final String SENSER_TYPE_THREE_RAD="Radiation"; public static final String SENSER_TYPE_FIVE_GPS="GPS"; public static final String SENSER_TYPE_SEVEN_NOTE="Notes"; public static final String SENSER_TYPE_EIGHT_IMG="Photo"; public static final String SENSER_TYPE_THREE_RAD_TITLE="RAD"; public static final String SENSER_TYPE_FIVE_GPS_TITLE="GPS"; public static final String SENSER_TYPE_SEVEN_NOTE_TITLE="NOTE"; public static final String SENSER_TYPE_EIGHT_IMG_TITLE="IMAGE"; public static final String DEFAULT_TITLE="Details"; @Override public void onCreate() { super.onCreate(); initImageLoader(this); } public static void initImageLoader(Context context) { // This configuration tuning is custom. You can tune every option, you may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration.createDefault(this); // method. ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context); config.threadPriority(Thread.NORM_PRIORITY - 2); config.denyCacheImageMultipleSizesInMemory(); config.diskCacheFileNameGenerator(new Md5FileNameGenerator()); config.diskCacheSize(50 * 1024 * 1024); // 50 MiB config.tasksProcessingOrder(QueueProcessingType.LIFO); config.writeDebugLogs(); // Remove for release app // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config.build()); } }
true
55cb50f0ae819727bda24f3e6ad363572f8a2cef
Java
tlynx538/spotfinder-v1
/AndroidApp/MyApplication/app/src/main/java/lynx/tommy/myapplication/MainActivity.java
UTF-8
13,436
1.960938
2
[]
no_license
package lynx.tommy.myapplication; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.amazonaws.mobile.client.AWSMobileClient; import com.amazonaws.mobile.client.Callback; import com.amazonaws.mobile.client.UserStateDetails; import com.amazonaws.mobileconnectors.iot.AWSIotKeystoreHelper; import com.amazonaws.mobileconnectors.iot.AWSIotMqttClientStatusCallback; import com.amazonaws.mobileconnectors.iot.AWSIotMqttLastWillAndTestament; import com.amazonaws.mobileconnectors.iot.AWSIotMqttManager; import com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback; import com.amazonaws.mobileconnectors.iot.AWSIotMqttQos; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.iot.AWSIotClient; import com.amazonaws.services.iot.model.AttachPrincipalPolicyRequest; import com.amazonaws.services.iot.model.CreateKeysAndCertificateRequest; import com.amazonaws.services.iot.model.CreateKeysAndCertificateResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import java.io.UnsupportedEncodingException; import java.security.KeyStore; import java.util.UUID; public class MainActivity extends AppCompatActivity{ private String TAG = MainActivity.class.getCanonicalName(); private Button b1,btnConnect; private static final String KEYSTORE_NAME = "iot_keystore"; // Password for the private key in the KeyStore private static final String KEYSTORE_PASSWORD = "password"; private static final String CERTIFICATE_ID = "default"; // Region of AWS IoT private static final Regions MY_REGION = Regions.US_EAST_1; private static final String LOG_TAG = "debug1"; KeyStore keystorex = null; String keystorePath; String keystoreName; String keystorePassword; String certificateId; TextView tvClientID; TextView tvStatus; TextView emailStatus; TextView tvLastMessage; AWSIotClient mIotAndroidClient; AWSIotMqttManager mqttManager; private FirebaseAuth mAuth; private static final String AWS_IOT_POLICY_NAME = "test-broker-policy"; //Amazon Credentials private static final String CUSTOMER_SPECIFIC_ENDPOINT = "a2bv3h4jn09xqe-ats.iot.us-east-1.amazonaws.com"; private static String Client_id; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvClientID = findViewById(R.id.tvClientID); tvStatus=findViewById(R.id.tvStatus); tvLastMessage=findViewById(R.id.tvLastMessage); b1 = (Button) findViewById(R.id.button2); btnConnect=(Button)findViewById(R.id.button3); Client_id= UUID.randomUUID().toString(); tvClientID.setText(Client_id); emailStatus=findViewById(R.id.textView13); mAuth = FirebaseAuth.getInstance(); onStart(); // Initialize the AWS Cognito credentials provider AWSMobileClient.getInstance().initialize(this, new Callback<UserStateDetails>() { @Override public void onResult(UserStateDetails result) { initIoTClient(); } @Override public void onError(Exception e) { Log.e(LOG_TAG, "onError: ", e); } }); } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); Log.d(LOG_TAG,"user is signed in"); emailStatus.setText("Hi "+currentUser.getEmail()); } void initIoTClient() { Region region = Region.getRegion(MY_REGION); // MQTT Client mqttManager = new AWSIotMqttManager(Client_id, CUSTOMER_SPECIFIC_ENDPOINT); // Set keepalive to 10 seconds. Will recognize disconnects more quickly but will also send // MQTT pings every 10 seconds. mqttManager.setKeepAlive(10); // Set Last Will and Testament for MQTT. On an unclean disconnect (loss of connection) // AWS IoT will publish this message to alert other clients. AWSIotMqttLastWillAndTestament lwt = new AWSIotMqttLastWillAndTestament("my/lwt/topic", "Android client lost connection", AWSIotMqttQos.QOS0); mqttManager.setMqttLastWillAndTestament(lwt); // IoT Client (for creation of certificate if needed) mIotAndroidClient = new AWSIotClient(AWSMobileClient.getInstance()); mIotAndroidClient.setRegion(region); keystorePath = getFilesDir().getPath(); keystoreName = KEYSTORE_NAME; keystorePassword = KEYSTORE_PASSWORD; certificateId = CERTIFICATE_ID; // To load cert/key from keystore on filesystem try { if (AWSIotKeystoreHelper.isKeystorePresent(keystorePath, keystoreName)) { if (AWSIotKeystoreHelper.keystoreContainsAlias(certificateId, keystorePath, keystoreName, keystorePassword)) { Log.i(LOG_TAG, "Certificate " + certificateId + " found in keystore - using for MQTT."); // load keystore from file into memory to pass on connection keystorex = AWSIotKeystoreHelper.getIotKeystore(certificateId, keystorePath, keystoreName, keystorePassword); /* initIoTClient is invoked from the callback passed during AWSMobileClient initialization. The callback is executed on a background thread so UI update must be moved to run on UI Thread. */ runOnUiThread(new Runnable() { @Override public void run() { btnConnect.setEnabled(true); } }); } else { Log.i(LOG_TAG, "Key/cert " + certificateId + " not found in keystore."); } } else { Log.i(LOG_TAG, "Keystore " + keystorePath + "/" + keystoreName + " not found."); } } catch (Exception e) { Log.e(LOG_TAG, "An error occurred retrieving cert/key from keystore.", e); } if (keystorex == null) { Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate."); new Thread(new Runnable() { @Override public void run() { try { // Create a new private key and certificate. This call // creates both on the server and returns them to the // device. CreateKeysAndCertificateRequest createKeysAndCertificateRequest = new CreateKeysAndCertificateRequest(); createKeysAndCertificateRequest.setSetAsActive(true); final CreateKeysAndCertificateResult createKeysAndCertificateResult; createKeysAndCertificateResult = mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest); Log.i(LOG_TAG, "Cert ID: " + createKeysAndCertificateResult.getCertificateId() + " created."); // store in keystore for use in MQTT client // saved as alias "default" so a new certificate isn't // generated each run of this application AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId, createKeysAndCertificateResult.getCertificatePem(), createKeysAndCertificateResult.getKeyPair().getPrivateKey(), keystorePath, keystoreName, keystorePassword); // load keystore from file into memory to pass on // connection keystorex = AWSIotKeystoreHelper.getIotKeystore(certificateId, keystorePath, keystoreName, keystorePassword); // Attach a policy to the newly created certificate. // This flow assumes the policy was already created in // AWS IoT and we are now just attaching it to the // certificate. AttachPrincipalPolicyRequest policyAttachRequest = new AttachPrincipalPolicyRequest(); policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME); policyAttachRequest.setPrincipal(createKeysAndCertificateResult .getCertificateArn()); mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest); runOnUiThread(new Runnable() { @Override public void run() { btnConnect.setEnabled(true); } }); } catch (Exception e) { Log.e(LOG_TAG, "Exception occurred when generating new private key and certificate.", e); } } }).start(); } } public void connectClick(final View view) { Log.d(LOG_TAG, "clientId = " + Client_id); try { mqttManager.connect(keystorex, new AWSIotMqttClientStatusCallback() { @Override public void onStatusChanged(final AWSIotMqttClientStatus status, final Throwable throwable) { Log.d(LOG_TAG, "Status = " + String.valueOf(status)); runOnUiThread(new Runnable() { @Override public void run() { tvStatus.setText(status.toString()); if (throwable != null) { Log.e(LOG_TAG, "Connection error.", throwable); } } }); } }); } catch (final Exception e) { Log.e(LOG_TAG, "Connection error.", e); tvStatus.setText("Error! " + e.getMessage()); } } public void disconnectClick(final View view) { try { mqttManager.disconnect(); } catch (Exception e) { Log.e(LOG_TAG, "Disconnect error.", e); } } public void subscribeClick(final View view) { final String topic = "outTopic"; Toast.makeText(getApplicationContext(),"Getting Status",Toast.LENGTH_LONG).show(); Log.d(LOG_TAG, "topic = " + topic); try { mqttManager.subscribeToTopic(topic, AWSIotMqttQos.QOS0, new AWSIotMqttNewMessageCallback() { @Override public void onMessageArrived(final String topic, final byte[] data) { runOnUiThread(new Runnable() { @Override public void run() { try { String message = new String(data, "UTF-8"); Log.d(LOG_TAG, "Message arrived:"); Log.d(LOG_TAG, " Topic: " + topic); Log.d(LOG_TAG, " Message: " + message); tvLastMessage.setText(message); } catch (UnsupportedEncodingException e) { Log.e(LOG_TAG, "Message encoding error.", e); } } }); } }); } catch (Exception e) { Log.e(LOG_TAG, "Subscription error.", e); } } public void BookSlot(final View view) { final String topic = "inTopic"; final String msg = "1"; try { mqttManager.publishString(msg, topic, AWSIotMqttQos.QOS0); Toast.makeText(getApplicationContext(),"Slot Booked",Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.e(LOG_TAG, "Publish error.", e); } } public void CancelSlot(final View view) { final String topic = "inTopic"; final String msg = "0"; try { mqttManager.publishString(msg, topic, AWSIotMqttQos.QOS0); Toast.makeText(getApplicationContext(),"Slot Cancelled",Toast.LENGTH_LONG).show(); } catch (Exception e) { Log.e(LOG_TAG, "Publish error.", e); } } }
true
62b7750b432962da314f4aa88dd375a203548db1
Java
samuelevi87/EventManager-Challenge
/backend/src/main/java/br/com/sl3v1/challengeselection/people/People.java
UTF-8
1,010
2.265625
2
[]
no_license
package br.com.sl3v1.challengeselection.people; import br.com.sl3v1.challengeselection.coffee.Coffee; import br.com.sl3v1.challengeselection.room.Room; import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "tb_people") @Data public class People implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // Instruindo o JPA a mapear o ID como chave primária auto-incrementável no banco @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "room_id" ) private Long roomId; // @OneToOne // @JoinColumn(name = "room_id", insertable = false, updatable = false) // private Room room; @Column(name = "coffee_id" ) private Long coffeeId; @OneToOne @JoinColumn(name = "coffee_id", insertable = false, updatable = false) private Coffee coffee; }
true
ff1b1eb7f0bdf033b155ecd502eaf825c4f5e82c
Java
GINGER-WU/carfactory
/src/com/CarService/service/ListService.java
UTF-8
621
2.140625
2
[]
no_license
package com.CarService.service; import java.util.List; public interface ListService { public List<Integer> findParts(int recordID); public List<Integer> findWorker(int recordID); public int findCount(int recordID,int partsID); public void addRecordWorker(int recordID,int workerID); public void addRecordParts(int recordID,int partsID,int n); public void changeRecordPartsNumber(int recordID, int partsID, int n); public void deleteRecord(int recordID); public void deleteRecordWorker(int recordID,int workerID); public void deleteRecordParts(int recordID,int partsID); }
true
7b5fa06215b8282008976efd94586b2a439613c6
Java
MindHeaders/QDump
/qdump-persistence/src/main/java/org/dataart/qdump/persistence/config/GlobalInterceptor.java
UTF-8
1,803
2.171875
2
[]
no_license
package org.dataart.qdump.persistence.config; import java.io.Serializable; import java.util.Date; import java.util.Iterator; import org.dataart.qdump.entities.questionnaire.BaseEntity; import org.hibernate.EmptyInterceptor; import org.hibernate.Transaction; import org.hibernate.type.Type; public class GlobalInterceptor extends EmptyInterceptor{ /** * */ private static final long serialVersionUID = 4605249677380841090L; @Override public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { if(entity instanceof BaseEntity) { for(int i = 0; i < propertyNames.length; i++) { if(propertyNames[i].equals("modifiedDate")) { currentState[i] = new Date(); return true; } } } return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types); } @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) { if(entity instanceof BaseEntity) { for(int i = 0; i < propertyNames.length; i++) { if(propertyNames[i].equals("createdDate")) { state[i] = new Date(); return true; } } } return super.onSave(entity, id, state, propertyNames, types); } @Override public void postFlush(Iterator entities) { super.postFlush(entities); } @Override public void preFlush(Iterator entities) { super.preFlush(entities); } @Override public void afterTransactionBegin(Transaction tx) { super.afterTransactionBegin(tx); } @Override public void afterTransactionCompletion(Transaction tx) { super.afterTransactionCompletion(tx); } @Override public void beforeTransactionCompletion(Transaction tx) { super.beforeTransactionCompletion(tx); } }
true
df2fd671bfd431734962c8aa01aaa12dae974830
Java
linked-swissbib/swissbib-metafacture-commands
/src/main/java/org/swissbib/linked/mf/morph/functions/ItemLink.java
UTF-8
10,058
2.25
2
[]
no_license
package org.swissbib.linked.mf.morph.functions; import org.metafacture.commons.ResourceUtil; import org.metafacture.metamorph.api.helpers.AbstractSimpleStatelessFunction; import java.io.IOException; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; class AlephStructure { String server; String docLibrary; } class VirtuaStructure { String server; } class BacklinksTemplate { String urlTemplate; } public final class ItemLink extends AbstractSimpleStatelessFunction { private HashMap< String, AlephStructure> alephNetworks; private HashMap< String, VirtuaStructure> virtuaNetworks; private HashMap< String, BacklinksTemplate> urlTemplates; private HashMap<String, Pattern> systemNumberPattern; private final Pattern pNebisReplacePattern = Pattern.compile("\\{bib-system-number}"); public ItemLink() throws IOException { Properties config = ResourceUtil.loadProperties("itemLinks/AlephNetworks.properties"); Enumeration<Object> keys = config.keys(); this.alephNetworks = new HashMap<>(); while (keys.hasMoreElements()) { String alephKey = (String) keys.nextElement(); String[] keyValues = config.getProperty(alephKey).split(","); if (!(keyValues.length == 2)) continue; AlephStructure as = new AlephStructure(); as.docLibrary = keyValues[1]; as.server = keyValues[0]; this.alephNetworks.put(alephKey, as); } config = ResourceUtil.loadProperties("itemLinks/VirtuaNetworks.properties"); keys = config.keys(); this.virtuaNetworks = new HashMap<>(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String[] keyValues = config.getProperty(key).split(","); if (!(keyValues.length == 2)) continue; VirtuaStructure vs = new VirtuaStructure(); vs.server = keyValues[0]; this.virtuaNetworks.put(key, vs); } config = ResourceUtil.loadProperties("itemLinks/Backlinks.properties"); keys = config.keys(); this.urlTemplates = new HashMap<>(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); BacklinksTemplate bT = new BacklinksTemplate(); bT.urlTemplate = config.getProperty(key); this.urlTemplates.put(key, bT); } //(RERO)R004689410!!(SGBN)000187319!!(NEBIS)000262918!!(IDSBB)000217483 //we need (!!|$) to catch a pattern (IDSBB)000217483 at the end of the string (without !! as delimiter) Pattern p = Pattern.compile("\\(IDSBB\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern = new HashMap<>(); this.systemNumberPattern.put("IDSBB", p); p = Pattern.compile("\\(RERO\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("RERO", p); p = Pattern.compile("\\(SGBN\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("SGBN", p); p = Pattern.compile("\\(NEBIS\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("NEBIS", p); p = Pattern.compile("\\(IDSSG\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("IDSSG", p); p = Pattern.compile("\\(IDSSG2\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("IDSSG2", p); p = Pattern.compile("\\(IDSLU\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("IDSLU", p); p = Pattern.compile("\\(BGR\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("BGR", p); p = Pattern.compile("\\(ABN\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("ABN", p); p = Pattern.compile("\\(SBT\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("SBT", p); p = Pattern.compile("\\(ABN\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("ABN", p); p = Pattern.compile("\\(SNL\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("SNL", p); p = Pattern.compile("\\(ALEX\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("ALEX", p); p = Pattern.compile("\\(CCSA\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("CCSA", p); p = Pattern.compile("\\(CHARCH\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("CHARCH", p); p = Pattern.compile("\\(LIBIB\\)(.*?)(!!|$)",Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL); this.systemNumberPattern.put("LIBIB", p); } @Override protected String process(String value) { String[] valueParts = value.split("##"); if (!this.checkValidity(valueParts)) return ""; String itemURL = ""; if (this.alephNetworks.containsKey(valueParts[0])) { itemURL = this.createAlephLink(valueParts); } else if (this.virtuaNetworks.containsKey(valueParts[0])) { itemURL = this.createVirtuaLink(valueParts); } else if (this.urlTemplates.containsKey(valueParts[0])) { itemURL = this.createBacklinkFromTemplate(valueParts); } return itemURL; } private boolean checkValidity (String [] valueParts) { return (valueParts.length == 6); } private String createAlephLink (String [] valueParts) { //#ALEPH "{server}/F?func=item-global&doc_library={bib-library-code}&doc_number={bib-system-number}&sub_library={aleph-sublibrary-code}" if (!this.systemNumberPattern.containsKey(valueParts[0])) return ""; Pattern p = this.systemNumberPattern.get(valueParts[0]); Matcher m = p.matcher(valueParts[5]); String url = ""; String subLibraryCode = valueParts[2].length() > 0 ? valueParts[2] : valueParts[1].length() > 0 ? valueParts[1] : null; if (subLibraryCode != null && m.find()) { url = String.format(this.urlTemplates.get("ALEPH").urlTemplate, this.alephNetworks.get(valueParts[0]).server, this.alephNetworks.get(valueParts[0]).docLibrary, m.group(1), subLibraryCode); } return url; } private String createVirtuaLink (String [] valueParts) { return ""; } private String createBacklinkFromTemplate (String [] valueParts) { if (!this.systemNumberPattern.containsKey(valueParts[0])) return ""; if (!this.urlTemplates.containsKey(valueParts[0])) return ""; Pattern p = this.systemNumberPattern.get(valueParts[0]); Matcher m = p.matcher(valueParts[5]); if (!m.find()) return ""; String url = ""; String subLibraryCode = valueParts[2].length() > 0 ? valueParts[2] : valueParts[1].length() > 0 ? valueParts[1] : null; String bibSysNumber; switch (valueParts[0]) { case "IDSBB": //IDSBB "http://baselbern.swissbib.ch/Record/{id}?expandlib={sub-library-code}#holding-institution-{network}-{sub-library-code}" if (subLibraryCode != null) { url = String.format(this.urlTemplates.get(valueParts[0]).urlTemplate,valueParts[4],subLibraryCode,valueParts[0],subLibraryCode); } break; case "NEBIS": //http://recherche.nebis.ch/primo_library/libweb/action/display.do?tabs=locationsTab&ct=display&fn=search&doc=ebi01_prod{bib-system-number}&indx=1&recIds=ebi01_prod{bib-system-number}&recIdxs=0&elementId=0&renderMode=poppedOut&displayMode=full&frbrVersion=&dscnt=0&scp.scps=scope%3A%28ebi01_prod%29&frbg=&tab=default_tab&vl%28585331958UI1%29=all_items&srt=rank&mode=Basic&dum=true&tb=t&vid=NEBIS bibSysNumber = m.group(1); Matcher nebisMatcher = this.pNebisReplacePattern.matcher(this.urlTemplates.get(valueParts[0]).urlTemplate); url = nebisMatcher.replaceAll(bibSysNumber); break; case "IDSSG": //"http://aleph.unisg.ch/php/bib_holdings.php?docnr={bib-system-number}" bibSysNumber = m.group(1); url = String.format(this.urlTemplates.get(valueParts[0]).urlTemplate, bibSysNumber); break; case "CHARCH": break; case "CCSA": break; case "RERO": if (subLibraryCode != null) { int RERO_network_code = Integer.valueOf(subLibraryCode.substring(2, 4)); bibSysNumber = m.group(1); String sub_library_code_rero = subLibraryCode.replaceAll("[\\D]",""); url = String.format(this.urlTemplates.get(valueParts[0]).urlTemplate,"en",RERO_network_code,bibSysNumber,sub_library_code_rero); } break; case "SNL": bibSysNumber = m.group(1); String bibSysNumber_snl = bibSysNumber.replaceAll("^vtls0*",""); url = String.format(this.urlTemplates.get(valueParts[0]).urlTemplate,bibSysNumber_snl); break; default: break; } return url; } }
true
4b508d5a4204b4c1e640c40de03fb1014135edc7
Java
khileshfegade-v2/V2AutoW_Jun2107
/V2AutoW/src/in/v2solutions/hybrid/util/Keywords.java
UTF-8
147,804
1.53125
2
[]
no_license
package in.v2solutions.hybrid.util; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import net.lightbody.bmp.proxy.ProxyServer; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.EntityBuilder; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.log4j.Logger; import org.bson.Document; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.Proxy; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; //import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.firefox.FirefoxDriver; //import org.openqa.selenium.firefox.FirefoxDriver; //import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.safari.SafariDriver; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.mongodb.BasicDBObject; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import edu.umass.cs.benchlab.har.HarWarning; public class Keywords extends Constants { /* @HELP @class: Keywords @Singleton Class: Keywords getKeywordsInstance() @ constructor: Keywords() @methods: OpenBrowser(), Navigate(), NavigateTo(), ResizeBrowser(), Login(), Input(), InputDDTdata(), Click(), SelectValueFromDropDownWithAnchorTags(), SelectValueFromDropDown(), SelectUnselectCheckbox(), GetText(), GetDollarPrice(), GetCountOfAllWebElements(), GetCountOfDisplayedWebElements(), GetCountOfImagesDisplayed(), GetSizeOfImages(), GetPositionOfImages(), Wait(), VerifyText(), VerifyTextDDTdata(), VerifyDollarPrice(), VerifyTitle(), VerifyUrl(), VerifyTotalPrice(), VerifyTotalPriceForDDT(), VerifyListOfStrings(), VerifyCountOfAllWebElements(), VerifyCountOfDisplayedWebElements(), VerifyImageCounts() VerifyListOfImageDimensions(), VerifyListOfImagePositions(), HighlightNewWindowOrPopup(), HandlingJSAlerts(), Flash_LoadFlashMovie(), Flash_SetPlaybackQuality(), Flash_SetVolume(), Flash_SeekTo(), Flash_VerifyValue(), Flash_StopVideo(), CloseBrowser(), QuitBrowser(). @parameter: Different parameters are passed as per the method declaration @notes: Keyword Drives and Executes the framework interacting with the Master xlsx file @returns: All respective methods have there return types @END */ @SuppressWarnings("rawtypes") public static Map getTextOrValues = new HashMap(); // Generating Dynamic Log File public String FILE_NAME = System.setProperty("filename", tsName + tcName + " - " + getCurrentTime()); public String PATH = System.setProperty("ROOTPATH", rootPath); public Logger APP_LOGS = Logger.getLogger("AutomationLog"); public static long start; static Keywords keywords = null; public boolean Fail=false; public boolean highlight = false; public String failedResult = ""; public static int count=0; public static String randomVal; public static String actStartDateAndTime; public static String actEndDateAndTime=""; public static String reqData; public static String scriptTableFirstRowData=""; static Properties props; public static Connection connection = null; public static Statement statement = null; public static String sGPname; public static String issueID; public String parentWindowID; public String actualEmployeeCode; public String GTestName=null; public String getMethodResponce = null; private static String urlGet = "http://ews.staging.tree.com/studentloans/api/CalculatorOffer/GetCalculatorOffers?annualIncome=800000&creditScore=1&refinanceRateTerm=120&totalBalance=100000&refiIntrestRate=3"; private static String urlPost = "https://ews.staging.tree.com/studentloans/api/OfferSave/Post"; String StrGet = null; String StrPost = null; private Keywords() throws IOException { props = new Properties(); props.load(new FileInputStream(new File(orPath + "OR.properties/"))); System.out.println(": Initializing keywords"); APP_LOGS.debug(": Initializing keywords"); // Initialize properties file try { // Config getConfigDetails(); // OR OR = new Properties(); fs = new FileInputStream(orPath + "OR.properties/"); OR.load(fs); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void executeKeywords(String testName, Hashtable<String, String> data ) throws Exception { /* @HELP @class: Keywords @method: executeKeywords() @parameter: String testName, Hashtable<String, String> data @notes: Executes the Keywords as defined in the Master Xslx "Test Steps" Sheet and takes screenshots for any Test Step failure. The test case execution is asserted for any failure in actions and the script execution continues of at all there are some failures in verifications. @returns: No return type @END */ System.out.println(": ========================================================="); APP_LOGS.debug(": ========================================================="); System.out.println(": Executing---" + testName + " Test Case"); APP_LOGS.debug(": Executing---" + testName + " Test Case"); String keyword = null; String objectKeyFirst = null; String objectKeySecond = null; String dataColVal = null; GTestName = testName; String links_highlight_true = null; String links_highlight_false =null; String links_on_action = null; for (int rNum = 2; rNum <= xls.getRowCount("Test Steps"); rNum++) { if (testName.equals(xls.getCellData("Test Steps", "TCID", rNum))) { keyword = xls.getCellData("Test Steps", "Keyword", rNum); objectKeyFirst = xls.getCellData("Test Steps", "FirstObject", rNum); objectKeySecond = xls.getCellData("Test Steps", "SecondObject", rNum); dataColVal = xls.getCellData("Test Steps", "Data", rNum); String result = null; if (keyword.equals("OpenBrowser"))// It is not a keyword, it is a supportive method result = OpenBrowser(dataColVal); else if (keyword.equals("Navigate")) result = Navigate(dataColVal); else if (keyword.equals("NavigateTo")) result = NavigateTo(dataColVal); else if (keyword.equals("Login")) result = Login(); else if (keyword.equals("InputText")) result = InputText(objectKeyFirst, dataColVal); else if (keyword.equals("InputNumber")) result = InputNumber(objectKeyFirst, dataColVal); else if (keyword.equals("InputDDTdata")) result = InputDDTdata(objectKeyFirst, data.get(dataColVal)); else if (keyword.equals("VerifyURLDDTContent")) result = VerifyURLDDTContent(data.get(dataColVal)); else if (keyword.equals("VerifyDDTImageExistsByImgSRC")) result = VerifyDDTImageExistsByImgSRC(objectKeyFirst,data.get(dataColVal)); else if (keyword.equals("Click")) result = Click(objectKeyFirst); else if (keyword.equals("ClickOnElementIfPresent")) result = ClickOnElementIfPresent(objectKeyFirst); else if (keyword.equals("SelectValueFromDropDownWithAnchorTags")) result = SelectValueFromDropDownWithAnchorTags(objectKeyFirst,objectKeySecond); else if (keyword.equals("SelectValueFromDropDown")) result = SelectValueFromDropDown(objectKeyFirst,dataColVal); else if (keyword.equals("SelectUnselectCheckbox")) result = SelectUnselectCheckbox(objectKeyFirst,dataColVal); else if (keyword.equals("Wait")) result = Wait(dataColVal); else if (keyword.equals("GetText")) result = GetText(objectKeyFirst); else if (keyword.equals("VerifyText")) result = VerifyText(objectKeyFirst, objectKeySecond, dataColVal); else if (keyword.equals("VerifyTotalPrice")) result = VerifyTotalPrice(objectKeyFirst, objectKeySecond, dataColVal); else if (keyword.equals("VerifyTextDDTdata")) result = VerifyTextDDTdata(objectKeyFirst, objectKeySecond, data.get(dataColVal)); else if (keyword.equals("VerifyTitle")) result = VerifyTitle(actTitle, dataColVal); else if (keyword.equals("VerifyUrl")) result = VerifyUrl(actUrl, dataColVal); else if (keyword.equals("HighlightNewWindowOrPopup")) result = HighlightNewWindowOrPopup(objectKeyFirst); else if (keyword.equals("HandlingJSAlerts")) result = HandlingJSAlerts(); else if (keyword.equals("HighlightFrame")) result = HighlightFrame(dataColVal); else if (keyword.equals("OpenDBConnection")) result = OpenDBConnection(); else if (keyword.equals("ExecuteAndVerifyDBQuery")) result = ExecuteAndVerifyDBQuery(objectKeyFirst, dataColVal); else if (keyword.equals("ExecuteDBQuery")) result = ExecuteDBQuery(objectKeyFirst); else if (keyword.equals("CloseDBConnection")) result = CloseDBConnection(); else if (keyword.equals("CloseBrowser")) result = CloseBrowser(); else if (keyword.equals("QuitBrowser")) result = QuitBrowser(); else if (keyword.equals("MouseHover")) result = MouseHover(objectKeyFirst); else if (keyword.equals("MouseHoverAndClick")) result = MouseHoverAndClick(objectKeyFirst, objectKeySecond); else if (keyword.equals("TestCaseEnds")) result = TestCaseEnds(); else if(keyword.equals("SwitchToNewWindow")) result= SwitchToNewWindow(); else if(keyword.equals("SwitchToParentWindow")) result= SwitchToParentWindow(); else if(keyword.equals("ClearTextField")) result = clearTextField(objectKeyFirst); else if(keyword.equals("SwitchToParentWindow")) result=SwitchToParentWindow(); else if(keyword.equals("ScrollPageToEnd")) result=ScrollPageToEnd(objectKeyFirst); else if(keyword.equals("VerifyColumnData")) result=VerifyColumnData(objectKeyFirst,objectKeySecond,dataColVal); else if(keyword.equals("VerifyElementPresent")) result=VerifyElementPresent(objectKeyFirst,dataColVal); else if(keyword.equals("GoToHomeLoansSubMenu")) result=GoToHomeLoansSubMenu(objectKeyFirst, objectKeySecond); else if(keyword.equals("SwitchToiFrame")) result=switchToiFrame(dataColVal); else if(keyword.equals("SwitchToDefaultFrameContent")) result=switchToDefaultContent(); else if (keyword.equals("VerifyTextContains")) result = VerifyTextContains(objectKeyFirst, objectKeySecond, dataColVal); else if(keyword.equals("VerifyToolTip")) result=VerifyToolTip(objectKeyFirst, dataColVal); else if (keyword.equals("VerifyTextDDTdataContains")) result = VerifyTextDDTdataContains(objectKeyFirst, objectKeySecond, data.get(dataColVal)); else if (keyword.equals("VerifyTitleContains")) result = VerifyTitleContains(dataColVal); else if (keyword.equals("OpenMongoDBConnection")) result = OpenMongoDBConnection(); else if (keyword.equals("VerifyMongoDBQuery")) result = VerifyMongoDBQuery(dataColVal); else if (keyword.equals("CloseMongoDBConnection")) result = CloseMongoDBConnection(); else if (keyword.equals("StartHARReading")) result = startHARReading(); else if (keyword.equals("StopHARReading")) result = stopHARReading(); else if (keyword.equals("VerifyHARContent")) result = VerifyHARContent(dataColVal); else if(keyword.equals("SignOutIFAlreadyLoggedIn")) result=SignOutIFAlreadyLoggedIn(objectKeyFirst, objectKeySecond); else if (keyword.equals("VerifyXMLContent")) result = VerifyXMLContent(dataColVal); else if (keyword.equals("VerifyCompleteGetResponse")) result = VerifyCompleteGetResponse(dataColVal); else if (keyword.equals("VerifyPOSTRequestContent")) result = VerifyPOSTRequestContent(dataColVal); else if (keyword.equals("MakeGetRequest")) result = makeGetRequest(dataColVal); else if (keyword.equals("MakeGetRequestDDT")) result = makeGetRequestDDT(data.get(dataColVal)); else if (keyword.equals("MakePostRequest")) result = makePostRequest(dataColVal); else if (keyword.equals("MakePostRequestJSON")) result = makePostRequestJSON(dataColVal); else if (keyword.equals("DragAndDropByCoordinates")) result = dragAndDropByCoordinates(objectKeyFirst,dataColVal); else if (keyword.equals("DragAndDropByElement")) result = dragAndDropByElement(objectKeyFirst, objectKeySecond); else if(keyword.equals("UploadThroughAutoIT")) result = uploadThroughAutoIT(); else if(keyword.equals("CloseTheChildWindow")) result = CloseTheChildWindow(); else if(keyword.equals("VerifyTableData")) result=VerifyTableData(objectKeyFirst,objectKeySecond,dataColVal); else if(keyword.equals("VerifyNewlyCreatedProject")) result=VerifyNewlyCreatedProject(objectKeyFirst,objectKeySecond,dataColVal); else if(keyword.equals("ScrollPageToBottom")) result=ScrollPageToBottom(); else if(keyword.equals("UploadFile")) result=uploadFile(dataColVal); else if(keyword.equals("SaveFile")) result=saveFile(); else if(keyword.equals("VerifyFileDownload")) result=VerifyFileDownload(dataColVal); else if(keyword.equals("DeleteFile")) result=DeleteFile(dataColVal); else if(keyword.equals("SwitchToPdfWindowAndVerifyText")) result=SwitchToPdfWindowAndVerifyText(objectKeyFirst,objectKeySecond,dataColVal); else if(keyword.equals("VerifyElementIsEditable")) result=VerifyElementIsEditable(objectKeyFirst); else if(keyword.equals("VerifyUsersEditables")) result=verifyUsersEditables(objectKeyFirst,dataColVal); else if(keyword.equals("InsertAndCheckUsersBelongings")) result=InsertAndCheckUsersBelongings(objectKeyFirst,objectKeySecond); else if(keyword.equals("VerifyFileIsDownloaded")) result=verifyFileIsDownloaded(); else if(keyword.equals("DeleteFilesFromFolder")) result=deleteFilesFromFolder(null); System.out.println(": " + result); APP_LOGS.debug(": " + result); File scrFile=null; if (keyword.contains("Verify")) { if (!result.equals("PASS")) { // screenshots if (highlight == true) { try { scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); scrFileName = testName + "--Failed_AT-" + keyword + "-" + objectKeyFirst + "-" + getCurrentTimeForScreenShot() + ".png"; links_highlight_true = " , For Error Screenshot please refer to this link : "+ "<a href="+"'"+scrFileName+"'"+">"+scrFileName+"</a>"; String filename= SRC_FOLDER2+Forwardslash+failedDataInText; FileWriter fw = new FileWriter(filename,true); String tempStr; tempStr=testName+"__"+objectKeyFirst+"__"+objectKeyFirst+" Not able to read text. Please check and modify Object Repository or wait time"+"__"+""+"__"+scrFileName; fw.write(tempStr+"\r\n"); fw.close(); }catch(Exception e){ System.out.println("-------------------------------Newly added catch"); Fail = true; failedResult = failedResult.concat(result + links_highlight_true + " && " ); } try { FileUtils.copyFile(scrFile, new File(screenshotPath + scrFileName)); System.out.println(": Verification failed. Please refer " + scrFileName); APP_LOGS.debug(": Verification failed. Please refer " + scrFileName); Fail = true; failedResult = failedResult.concat(result + links_highlight_true + " && " ); } catch (IOException e) { e.printStackTrace(); } } else { if(keyword.equals("VerifyXMLContent") ) { APP_LOGS.debug(": Verification failed. VerifyXMLContent" ); Fail = true; }else if(keyword.equals("VerifyPOSTRequestContent")){ APP_LOGS.debug(": Verification failed. VerifyXMLContent" ); Fail = true; }else if(keyword.equals("VerifyCompleteGetResponse")){ APP_LOGS.debug(": Verification failed. VerifyXMLContent" ); Fail = true; } else { try{ highlightElement(returnElementIfPresent(objectKeyFirst)); }catch(Exception e ){ Fail = true; //failedResult = failedResult.concat(result + Links + " && " ); } } scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); scrFileName = testName + "--Failed_AT-" + keyword + "-" + objectKeyFirst + "-" + getCurrentTimeForScreenShot() + ".png"; links_highlight_false = " , For Error Screenshot please refer to this link : "+ "<a href="+"'"+scrFileName+"'"+">"+scrFileName+"</a>"; String filename= SRC_FOLDER2+Forwardslash+failedDataInText; FileWriter fw = new FileWriter(filename,true); String tempStr; tempStr=testName+"__"+objectKeyFirst+"__"+actText+"__"+globalExpText+"__"+scrFileName; fw.write(tempStr+"\r\n"); fw.close(); Thread.sleep(500); if(keyword.equals("ExecuteAndVerifyDBQuery")) { } else { unhighlightElement(returnElementIfPresent(objectKeyFirst)); } try { FileUtils.copyFile(scrFile, new File(screenshotPath + scrFileName)); System.out.println(": Verification failed. Please refer " + scrFileName); APP_LOGS.debug(": Verification failed. Please refer " + scrFileName); Fail = true; failedResult = failedResult.concat(result + links_highlight_false + " && " ); } catch (IOException e) { e.printStackTrace(); } } } String filename= SRC_FOLDER2+Forwardslash+verificationSummaryText; try{ FileWriter fw = new FileWriter(filename,true); String tempStr=GTestName; if(result.equals("PASS")){ tempStr+=" "+"__"+objectKeyFirst+"__"+keyword+"__"+"Y"+"__"+"-"; }else{ tempStr+=" "+"__"+objectKeyFirst+"__"+keyword+"__"+"-"+"__"+"Y"; } count++; fw.write(tempStr+"\r\n"); fw.close(); } catch(Exception e){ System.out.println("Error in count of the verification points.."); e.printStackTrace(); } } else { if (!result.equals("PASS")) { // screenshots scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); scrFileName = testName + "--Failed_AT-" + keyword + "-" + objectKeyFirst + "-" + getCurrentTimeForScreenShot() + ".png"; links_on_action = " , For Error Screenshot please refer to this link : "+ "<a href="+"'"+scrFileName+"'"+">"+scrFileName+"</a>"; String filename= SRC_FOLDER2+Forwardslash+failedDataInText; FileWriter fw = new FileWriter(filename,true); String tempStr; tempStr=testName+"__"+objectKeyFirst+"__"+objectKeyFirst+" Did not appeared after waiting "+waitTime+" seconds. Please check the application status or modify Object Repository, Wait time."+"__"+""+"__"+scrFileName; fw.write(tempStr+"\r\n"); fw.close(); try { FileUtils.copyFile(scrFile, new File(screenshotPath + scrFileName)); System.out.println(": Verification failed. Please refer " + scrFileName); APP_LOGS.debug(": Verification failed. Please refer " + scrFileName); Fail = true; failedResult = failedResult.concat(result + links_on_action + " && " ); } catch (IOException e) { e.printStackTrace(); } System.out.println(": On Action Failed"); Fail = false; QuitBrowser(); driver = null; Assert.assertTrue(false, failedResult); }// last if is closing }//first Else is closing. it is of inner IF's }//outer If loop is closing }//outer For loop is closing } // **************************************************************************************************Keywords Definitions****************************************************************************************************************************** //***************** 1. OpenBrowser****************// public String OpenBrowser(String browserType) throws Exception { /* @HELP @class: Keywords @method: OpenBrowser () @parameter: String browserType @notes: Opens Browsers, Sets Timeout parameter and Maximize the Browser @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ getConfigDetails(); int WaitTime; NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(waitTime); WaitTime = number.intValue(); failedResult = ""; System.out.println(": Opening: " + bType + " Browser"); try { if(tBedType.equals("DESKTOP")){ //***************** 1. For Desktop Browsers****************// if (bType.equals("Chrome")) { System.setProperty("webdriver.chrome.driver", chromedriverPath); if(GTestName.contains("Segment")){ System.out.println("Inside segment block of chrome"); capabilities = new DesiredCapabilities(); // start the proxy server = new ProxyServer(4444); server.start(); // captures the moouse movements and navigations server.setCaptureHeaders(true); server.setCaptureContent(true); // get the Selenium proxy object Proxy proxy = server.seleniumProxy(); capabilities.setCapability(CapabilityType.PROXY, proxy); driver = new ChromeDriver(capabilities); } else{ driver = new ChromeDriver(); } getBrowserVersion(); APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (bType.equals("Mozilla")) { System.setProperty("webdriver.gecko.driver", geckodriverPath); if(GTestName.contains("Segment")){ capabilities = new DesiredCapabilities(); // start the proxy server = new ProxyServer(4444); server.start(); // captures the moouse movements and navigations server.setCaptureHeaders(true); server.setCaptureContent(true); // get the Selenium proxy object Proxy proxy = server.seleniumProxy(); capabilities.setCapability(CapabilityType.PROXY, proxy); driver = new FirefoxDriver(capabilities); } else{ /*ProfilesIni profile = new ProfilesIni(); FirefoxProfile myprofile = profile.getProfile("FFProfile"); driver = new FirefoxDriver(myprofile);*/ driver = new FirefoxDriver(); } getBrowserVersion(); //System.out.println("______________ "+getBrowserVersion()); APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (bType.equals("Safari")) { if(GTestName.contains("Segment")){ capabilities = new DesiredCapabilities(); // start the proxy server = new ProxyServer(4444); server.start(); // captures the moouse movements and navigations server.setCaptureHeaders(true); server.setCaptureContent(true); // get the Selenium proxy object Proxy proxy = server.seleniumProxy(); capabilities.setCapability(CapabilityType.PROXY, proxy); driver = new SafariDriver(capabilities); } else{ driver = new SafariDriver(); } getBrowserVersion(); APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (bType.equals("IE")) { System.setProperty("webdriver.ie.driver", iedriverPath); if(GTestName.contains("Segment")){ capabilities = new DesiredCapabilities(); // start the proxy server = new ProxyServer(4444); server.start(); // captures the moouse movements and navigations server.setCaptureHeaders(true); server.setCaptureContent(true); // get the Selenium proxy object Proxy proxy = server.seleniumProxy(); capabilities.setCapability(CapabilityType.PROXY, proxy); driver = new InternetExplorerDriver(capabilities); } else{ driver = new InternetExplorerDriver(); } getBrowserVersion(); APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (bType.equals("Opera")) { driver = new OperaDriver(); if(GTestName.contains("Segment")){ } getBrowserVersion(); APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); driver.manage().window().maximize(); } else if (bType.equals("HtmlUnit")) { if(GTestName.contains("Segment")){ capabilities = new DesiredCapabilities(); // start the proxy server = new ProxyServer(4444); server.start(); // captures the moouse movements and navigations server.setCaptureHeaders(true); server.setCaptureContent(true); // get the Selenium proxy object Proxy proxy = server.seleniumProxy(); capabilities.setCapability(CapabilityType.PROXY, proxy); driver = new HtmlUnitDriver(capabilities); } /*else if (bType.equals("Edge")) { System.setProperty("webdriver.edge.driver", edgedriverPath); driver = new EdgeDriver(); getBrowserVersion(); APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); driver.manage().window().maximize(); }*/ else{ driver = new HtmlUnitDriver(true); } APP_LOGS.debug(": Opening: " + bTypeVersion + " Browser"); driver.manage().timeouts().implicitlyWait(WaitTime, TimeUnit.SECONDS); } }else { System.out.println(": The Browser Type: " + bType + " is not valid. Please Enter a valid Browser Type"); return "FAIL - The Browser Type: " + bType + " is not valid. Please Enter a valid Browser Type"; } } catch (Exception e) { return "FAIL - Not able to Open Browser"; } return "PASS"; } //***************** 2. Navigate****************// public String Navigate(String URLKey) { /* @HELP @class: Keywords @method: Navigate () @parameter: String URLKey @notes: Navigate opened Browser to specific URL as metioned in the config details. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ getConfigDetails(); /*System.out.println("deleting cookies"); driver.manage().deleteAllCookies();*/ failedResult = ""; System.out.println(": Navigating to (" + SUTUrl + ") Site"); APP_LOGS.debug(": Navigating to (" + SUTUrl + ") Site"); try { if (driver!=null){ System.out.println(": Driver Handle: "+ driver); System.out.println(": Browser is Already Opened and same will be used for this TestScript execution"); APP_LOGS.debug(": Browser is Already Opened and same will be used for this TestScript execution"); driver.get(SUTUrl); if(GTestName.contains("segment")){ QuitBrowser(); OpenBrowser(bType); } } else{ System.out.println(": Driver Handle: "+ driver); System.out.println(": No Opened Browser Available, Opening New one"); APP_LOGS.debug(": No Opened Browser Available, Opening New one"); OpenBrowser(bType); driver.get(SUTUrl); } /*System.out.println("deleting cookies"); driver.manage().deleteAllCookies(); */ } catch (Exception e) { return "FAIL - Not able to Navigate " + SUTUrl + " Site"; } return "PASS"; } //***************** 3. NavigateTo****************// public String NavigateTo(String URLKey) { /* @HELP @class: Keywords @method: NavigateTo () @parameter: String URLKey @notes: Navigate to specific URL as metioned in the Data Coulmn in "Test Steps" Sheet. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ getConfigDetails(); failedResult = ""; System.out.println(": Navigating to (" + URLKey + ") Site"); APP_LOGS.debug(": Navigating to (" + URLKey + ") Site"); try { if (driver!=null){ System.out.println(": Driver Handle: "+ driver); System.out.println(": Browser is Already Opened and same will be used for this TestScript execution"); APP_LOGS.debug(": Browser is Already Opened and same will be used for this TestScript execution"); driver.get(URLKey); if(GTestName.contains("segment")){ QuitBrowser(); OpenBrowser(bType); } } else{ System.out.println(": Driver Handle: "+ driver); System.out.println(": No Opened Browser Available, Opening New one"); APP_LOGS.debug(": No Opened Browser Available, Opening New one"); OpenBrowser(bType); driver.get(URLKey); } } catch (Exception e) { System.out.println(": Exception: "+e.getMessage()); return "FAIL - Not able to Navigate " + URLKey + " Site"; } return "PASS"; } //***************** 3. Login****************// public String Login() { /* @HELP @class: Keywords @method: Login () @parameter: None @notes: Inputs the default login details as mentioned in the "Config Details" sheet of the master xlsx and performs click action on the login button. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try { getConfigDetails(); System.out.println(": Entering: " + username + " in USERNAME Field"); APP_LOGS.debug(": Entering: " + username + " in USERNAME Field"); returnElementIfPresent(GUSER_XPATH).sendKeys(username); System.out.println(": PASS"); APP_LOGS.debug(": PASS"); System.out.println(": Entering: " + password + " in PASSWORD Field"); APP_LOGS.debug(": Entering: " + password + " in PASSWORD Field"); returnElementIfPresent(GPASS_XPATH).sendKeys(password); System.out.println(": PASS"); APP_LOGS.debug(": PASS"); System.out.println(": Performing Click action on LOGIN"); APP_LOGS.debug(": Performing Click action on LOGIN"); returnElementIfPresent(GLOGIN).click(); } catch (Exception e) { APP_LOGS.debug(": FAIL - Not able to Loging with " + username + " : Username and " + password + ": Password"); return ("FAIL - Not able to Loging with " + username + " : Username and " + password + ": Password"); } return "PASS"; } //***************** 4. Input Text****************// public String InputText(String firstXpathKey, String inputData) throws Exception { /* @HELP @class: Keywords @method: Input () @parameter: String firstXpathKey & String inputData @notes: Inputs the value in any edit box. Value is defined in the master xlsx file and is assigned to "inputData" local variable. We cannot perform a data driven testing using the input keyword. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); APP_LOGS.debug(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); try { System.out.println("In Input methodddddddddddddd"); System.out.println("Browserrrrr ------- "+bType); if(firstXpathKey.equals("NEWEMAIL")){ long randomNum=System.currentTimeMillis(); String randomString=String.valueOf(randomNum); inputData=inputData+randomString+"@v2solutions.com"; returnElementIfPresent(firstXpathKey).sendKeys(inputData); }else{ System.out.println("In elseeeeeeeeeeee"); if(bType.equals("IE")){ returnElementIfPresent(firstXpathKey).click(); System.out.println("Element clicked"); returnElementIfPresent(firstXpathKey).sendKeys(inputData); }else{ returnElementIfPresent(firstXpathKey).sendKeys(inputData); } System.out.println("In Input textttt method with -:"+inputData); } } catch (Exception e) { return "FAIL - Not able to enter " + inputData + " in " + firstXpathKey + " Field"; } return "PASS"; } //***************** 5. Input Number****************// public String InputNumber(String firstXpathKey, String inputData) throws Exception { /* @HELP @class: Keywords @method: Input () @parameter: String firstXpathKey & String inputData @notes: Inputs the value in any edit box. Value is defined in the master xlsx file and is assigned to "inputData" local variable. We cannot perform a data driven testing using the input keyword. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try{ String regex = ".*\\d.*"; if (inputData.matches(regex)) { NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(inputData); long lnputValue = number.longValue(); inputData = String.valueOf(lnputValue); System.out.println(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); APP_LOGS.debug(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); returnElementIfPresent(firstXpathKey).clear(); returnElementIfPresent(firstXpathKey).sendKeys(inputData); } else{ System.out.println(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); APP_LOGS.debug(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); returnElementIfPresent(firstXpathKey).sendKeys(inputData); } }catch (Exception e) { return "FAIL - Not able to enter " + inputData + " in " + firstXpathKey + " Field"; } return "PASS"; } //***************** 6. InputDDTdata****************// public String InputDDTdata(String firstXpathKey, String inputData) throws Exception { /* @HELP @class: Keywords @method: InputDDTdata () @parameter: String firstXpathKey & String inputData @notes: Inputs the value in any edit box. Value will be a multiple test data obtained from the "Test Data" sheet of the master xlsx. Data driven testing is achieved using the keyword InputDDTdata. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ String numRegex1 = "[0-9].[0-9]"; String numRegex2 = "[0-9][0-9].[0-9]"; if (inputData.matches(numRegex1)) { NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(inputData); long lnputValue = number.longValue(); inputData = String.valueOf(lnputValue); System.out.println(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); APP_LOGS.debug(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); try { returnElementIfPresent(firstXpathKey).clear(); returnElementIfPresent(firstXpathKey).sendKeys(inputData); } catch (Exception e) { return "FAIL - Not able to enter " + inputData + " in " + firstXpathKey + " Field"; } } else if (inputData.matches(numRegex2)) { NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(inputData); long lnputValue = number.longValue(); inputData = String.valueOf(lnputValue); System.out.println(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); APP_LOGS.debug(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); try { returnElementIfPresent(firstXpathKey).clear(); returnElementIfPresent(firstXpathKey).sendKeys(inputData); } catch (Exception e) { return "FAIL - Not able to enter " + inputData + " in " + firstXpathKey + " Field"; } } else { System.out.println(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); APP_LOGS.debug(": Entering: " + '"' + inputData + '"' + " text in " + firstXpathKey + " Field"); try { returnElementIfPresent(firstXpathKey).sendKeys(inputData); } catch (Exception e) { return "FAIL - Not able to enter " + inputData + " in " + firstXpathKey + " Field"; } } return "PASS"; } //***************** 7. Click****************// public String Click(String firstXpathKey) { /* @HELP @class: Keywords @method: Click () @parameter: String firstXpathKey @notes: Performs Click action on link, Hyperlink, selections or buttons of a web page. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing Click action on " + firstXpathKey); APP_LOGS.debug(": Performing Click action on " + firstXpathKey); try{ returnElementIfPresent(firstXpathKey).click(); } catch (Exception e) { return "FAIL - Not able to click on -- " + firstXpathKey; } return "PASS"; } //***************** 7. Click****************// public String ClickOnElementIfPresent(String firstXpathKey) { /* @HELP @class: Keywords @method: Click () @parameter: String firstXpathKey @notes: Performs Click action on link, Hyperlink, selections or buttons of a web page. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing Click action on " + firstXpathKey+ " Element if it is Present in WebPage"); APP_LOGS.debug(": Performing Click action on " + firstXpathKey+ " Element if it is Present in WebPage"); try { if (isElementPresent(firstXpathKey)) { System.out.println(": "+ firstXpathKey+ "Element is present. Performing Click Action on it."); APP_LOGS.debug(": "+ firstXpathKey+ "Element is present. Performing Click Action on it."); returnElementIfPresent(firstXpathKey).click(); } else { System.out.println(": "+ firstXpathKey+ "Element is Not present in WebPage"); APP_LOGS.debug(": "+ firstXpathKey+ "Element is Not present in WebPage"); } } catch (Exception e) { return "FAIL - Not able to click on -- " + firstXpathKey; } return "PASS"; } //***************************** 8. SelectValueFromDropDownWithAnchorTags*************************************// public String SelectValueFromDropDownWithAnchorTags(String firstXpathKey, String secondXpathKey) throws Exception { /* @HELP @class: Keywords @method: SelectValueFromDropDownWithAnchorTags () @parameter: String firstXpathKey, String inputData @notes: Click the dropdown and click the value from the List(Which contains anchor tags). @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Selecting : " + secondXpathKey + " from the Dropdown"); APP_LOGS.debug(": Selecting : " + secondXpathKey + " from the Dropdown"); try { returnElementIfPresent(firstXpathKey).click(); returnElementIfPresent(secondXpathKey).click(); } catch (Exception e) { return "FAIL - Not able to select " + secondXpathKey + " from the Dropdown"; } return "PASS"; } //***************************** 9. SelectValueFromDropDown*************************************// public String SelectValueFromDropDown(String firstXpathKey,String inputData) throws Exception { /* @HELP @class: Keywords @method: SelectValueFromDropDown () @parameter: String firstXpathKey, String inputData @notes: Selects the "inputData" as mentioned in the module xlsx from the DropDown in a webpage.firstXpathKey would be location of the Dropdown on webpage and dataColVal would be visible text of the dropdown. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Selecting : " + inputData + " from the Dropdown"); APP_LOGS.debug(": Selecting : " + inputData + " from the Dropdown"); try { System.out.println(": "+inputData); Select sel=new Select(returnElementIfPresent(firstXpathKey)); sel.selectByVisibleText(inputData); } catch (Exception e) { return "FAIL - Not able to select " + inputData + " from the Dropdown"; } return "PASS"; } //***************************** 10. SelectUnselectCheckbox*************************************// public String SelectUnselectCheckbox(String firstXpathKey, String checkBoxVal) { /* @HELP @class: Keywords @method: SelectUnselectCheckbox () @parameter: String firstXpathKey, String checkBoxVal @notes: Select or Unselect the checkbox of a webpage as per the value of local variable "chechBoxVal" mentioned in the "Test Steps" sheet in module excel. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing Select Unselect action on " + firstXpathKey); APP_LOGS.debug(": Setting " + firstXpathKey + " Checkbox Value As " + checkBoxVal); try { if (checkBoxVal.equals("TRUE")) { if (returnElementIfPresent(firstXpathKey).isSelected()) { } else { returnElementIfPresent(firstXpathKey).click(); } } else { if (returnElementIfPresent(firstXpathKey).isSelected()) { returnElementIfPresent(firstXpathKey).click(); } } } catch (Exception e) { return "FAIL - Not able to Select Unselect Checkbox-- " + firstXpathKey; } return "PASS"; } //***************** 11. Wait****************// public String Wait(String WaitTime) { /* @HELP @class: Keywords @method: Wait () @parameter: String WaitTime @notes: Wait for a user defined specific time to load the page for ex: 20 seconds. String "WaitTime" captures the value from the module xlsx file. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try { NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(WaitTime); long lWaitTime = number.longValue(); Thread.sleep(lWaitTime * 1000); System.out.println(": Waiting for Page to load."); APP_LOGS.debug(": Waiting for Page to load."); } catch (Exception e) { APP_LOGS.debug(": FAIL - Not able to wait for " + WaitTime + " Seconds to load the page"); return ("FAIL - Not able to wait for " + WaitTime + " Seconds to load the page"); } return "PASS"; } //***************** 12. GetText****************// @SuppressWarnings("unchecked") public String GetText(String firstXpathKey) throws IOException { /* @HELP @class: Keywords @method: GetText () @parameter: String firstXpathKey @notes: Get the text of the web element of the passed "firstXpathKey" and stores it into a global Hash map "getTextOrValues". @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Getting " + firstXpathKey + " Text from the Page"); APP_LOGS.debug(": Getting " + firstXpathKey + " Text from the Page"); try { getTextOrValues.put(firstXpathKey, returnElementIfPresent(firstXpathKey).getText().toLowerCase()); } catch (Exception e) { return "FAIL - Not able to read text from " + firstXpathKey; } return "PASS"; } /* //----------------------GetTableData------------------------ public String VerifyGetTableData(String firstXpathKey, String secondXpathKey,String expText) throws ParseException { System.out.println(": Getting " + firstXpathKey + " Text from the Page"); APP_LOGS.debug(": Getting " + firstXpathKey + " Text from the Page"); String[] inter = expText.split(","); for(int i = 0; i< inter.length;i++){ System.out.println("Values : "+inter[i]); } highlight = false; try { WebElement table =returnElementIfPresent(firstXpathKey); //driver.findElement(By.xpath("html/body/div[1]/div/form/table")); List<WebElement> th=table.findElements(By.tagName("th")); int col_position=0; for(int i=0;i<th.size();i++){ System.out.println(": Getting " + secondXpathKey + " Text from the Page"); APP_LOGS.debug(": Getting " + firstXpathKey + " Text from the Page"); if((returnElementIfPresent(secondXpathKey).getText()).equalsIgnoreCase(th.get(i).getText())){ col_position=i+1; break; } } List<WebElement> FirstColumns = table.findElements(By.xpath("//tr/td["+col_position+"]")); for(int i = 0;i<inter.length;i++){ WebElement e = FirstColumns.get(i); System.out.println("INSIDE FOR TABLE : "+e.getText()); System.out.println(": Getting company name from the table "+e.getText()); APP_LOGS.debug(": Getting company name from the table "+e.getText()); if(inter[i].contains(e.getText())) { System.out.println(": Able to verify the company name from the list"); APP_LOGS.debug(": Able to verify the company name from the list"); }else { System.out.println(": Not able to verify the company name from the list"); APP_LOGS.debug(": Not able to verify the company name from the list"); } } }catch(Exception e){ highlight = true; return "FAIL - Not able to read text from " + firstXpathKey; } return "PASS"; } */ //--------------------------ElementPresentInUI--------------------------- public String getColumnData(String firstXpathKey,String secondXpathKey){ //System.out.println("Inside getColumnData initialization"); String data = ""; WebElement table =returnElementIfPresent(firstXpathKey); List<WebElement> th=table.findElements(By.tagName("th")); System.out.println(th.get(1).getText()); int col_position=0; System.out.println(": Getting " + secondXpathKey + " Column Data from the Table"); APP_LOGS.debug(": Getting " + secondXpathKey + " Column Data from the Table"); for(int i=0;i<th.size();i++){ /*System.out.println(": Getting " + secondXpathKey + " Column Data from the Table"); APP_LOGS.debug(": Getting " + secondXpathKey + " Column Data from the Table");*/ if((returnElementIfPresent(secondXpathKey).getText()).equalsIgnoreCase(th.get(i).getText())){ col_position=i+1; break; } } List<WebElement> FirstColumns = table.findElements(By.xpath("//tr/td["+col_position+"]")); for (WebElement e : FirstColumns){ data = data+e.getText()+","; } return data; } public String getColumnDataLink(String firstXpathKey,String secondXpathKey){ /* * Need to create a method or mechanism which calculates unique names from list from String data which have the concatenated string of column Role or we can implement that method in upper method. * */ String data = ""; WebElement table =returnElementIfPresent(firstXpathKey); System.out.println("Table Tag Name : "+table.getTagName()); //System.out.println(table.findElement(By.tagName("li"))); List<WebElement> ul=table.findElements(By.tagName("th")); //System.out.println(ul.get(1).getText()); int col_position=0; for(int i=0;i<ul.size();i++){ System.out.println(": Getting " + secondXpathKey + " Column Data from the Table"); APP_LOGS.debug(": Getting " + firstXpathKey + " Column Data from the Table"); /*System.out.println(ul.get(i).getText()); if(i == 3){ System.out.println("Third : "+ul.get(3).getText()); System.out.println(); }*/ if((returnElementIfPresent(secondXpathKey).getText()).equalsIgnoreCase(ul.get(i).getText())){ col_position=i+1; break; } } List<WebElement> FirstColumns = table.findElements(By.xpath("//tr/td["+col_position+"]")); for (WebElement e : FirstColumns){ data = data+e.getText()+","; } return data; } public String VerifyColumnData(String firstXpathKey,String secondXpathKey,String expText){ /* @HELP @class: Keywords @method: VerifyColumnData () @parameter: String firstXpathKey, String secondXpathKey, String expText @notes: Performs the verification of the table data by getting column data from firstXpathKey and secondXpathKey and verify it against the expText or dataColVal. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try{ highlight = false; String actText = getColumnData(firstXpathKey,secondXpathKey); System.out.println(": Verifying Table Data:"); APP_LOGS.debug(": Verifying Table Data:"); if (expText.equalsIgnoreCase(actText)){ System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + actText + " AND Expected is->" + expText); } else{ System.out.println("FAIL - Not Able to verify "+actText+" is present or Not-- with " + expText); APP_LOGS.debug("FAIL - Not Able to verify "+actText+" is present or Not-- with " + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch(Exception e) { highlight = true; System.out.println("FAIL - Not Able to verify "+actText+" is present or Not-- with " + expText); APP_LOGS.debug("FAIL - Not Able to verify "+actText+" is present or Not-- with " + expText); return "FAIL - Not Able to verify Element is present or Not--" + firstXpathKey; } return "PASS"; } public String VerifyTableData(String firstXpathKey,String secondXpathKey,String expText){ //System.out.println("Initialization of keyword"); highlight = false; //String envelopeMessage= OR.getProperty("NO_ENVELOPE_FOUND_MESSAGE"); WebElement message ; try{ //System.out.println("Inside try"); /*if(driver.findElement(By.xpath("//h2[text()='No envelopes found.']")).isDisplayed()){ System.out.println("No envelope is displayed."); APP_LOGS.debug("No envelope is displayed."); //return "No envelope is displayed."; System.out.println("In IF"); }else{*/ //System.out.println("In ELSE");returnElementIfPresent(firstXpathKey)==null || /*if ( driver.findElement(By.xpath("//h2[text()='No envelopes found.']")).isDisplayed()) { System.out.println(": No table displayed with \"No envelopes found.\" Message" ); APP_LOGS.debug(": No table displayed with \"No envelopes found.\" Message" ); }*/ //else { String actText = getColumnData(firstXpathKey,secondXpathKey); //System.out.println("getcolumnData"); String[] inter = actText.split(","); for(int i = 0; i< inter.length;i++){ System.out.println("Values : "+inter[i]); } System.out.println("Total "+inter.length+" records found."); for(int i = 0; i< inter.length;i++){ if (inter[i].contains(expText)){ System.out.println(": Actual is-> " + inter[i] + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + inter[i] + " AND Expected is->" + expText); } else{ highlight = true; System.out.println(": Actual is-> " + inter[i] + " AND Expected is-> " + expText); return "FAIL - Actual is-> " + inter[i] + " AND Expected is->" + expText; } } //} } catch(Exception ex){ highlight = true; System.out.println("Unable to match data with table data."); APP_LOGS.debug("Unable to match data with table data "); return "FAIL - Not able to match data with table data."; } return "PASS"; } public String InsertAndCheckUsersBelongings(String firstXpathKey,String secondXpathKey){ //System.out.println("Initialization of keyword"); highlight = false; //String envelopeMessage= OR.getProperty("NO_ENVELOPE_FOUND_MESSAGE"); WebElement message ; try{ //System.out.println("Inside try"); //Boolean isPresent = driver.findElements(By.xpath("html/body/div[3]/div/div[4]")).size() != 0; String actText = getColumnData(firstXpathKey,secondXpathKey); String[] inter = actText.split(","); for(int i = 0; i< inter.length;i++){ System.out.println("Values : "+inter[i]); } System.out.println("Total "+inter.length+" records found."); for(int i = 0,j = 1; i< inter.length;i++,j++){ /*int j = ++i;*/ WebElement checkBox = driver.findElement(By.xpath("html/body/div[1]/div/div/table/tbody/tr["+j+"]/td[5]/form/label/span")); System.out.println(checkBox.getAttribute("class")); if(checkBox.getAttribute("class").contains("checked")){ returnElementIfPresent("SETTINGS").click(); Thread.sleep(5000); returnElementIfPresent("USER_SEARCH").sendKeys(inter[i]); returnElementIfPresent("SEARCH_BUTTON").click(); Thread.sleep(2000); if (isElementPresent(By.xpath("html/body/div[3]/div/div[4]"))){ highlight = true; System.out.println(": User does not belongs to Admin -> " + inter[i]+" With error message :\" "+driver.findElement(By.xpath("html/body/div[3]/div/div[4]")).getText()+" \""); APP_LOGS.debug(": User does not belongs to Admin -> " + inter[i]+" With error message :\" "+driver.findElement(By.xpath("html/body/div[3]/div/div[4]")).getText()+" \""); return ": User does not belongs to Admin -> " + inter[i]; } else{ System.out.println(": User belongs to Admin -> " + inter[i]); APP_LOGS.debug(": User belongs to Admin -> " + inter[i]); } }else{ System.out.println("User is not Active."); } returnElementIfPresent("ADMIN_TAB").click(); Thread.sleep(2000); } //} } catch(Exception ex){ highlight = true; System.out.println("Unable to match data with table data." +ex); APP_LOGS.debug("Unable to match data with table data "); return "FAIL - Not able to match data with table data."; } return "PASS"; } /*public static boolean isElementVisible(final By by) throws InterruptedException { boolean value = false; if (driver.findElements(by).size() > 0) { value = true; } return value; } */ public boolean isElementPresent(By by){ try { driver.findElement(by); return true; } catch (Exception e){ return false; } } public String verifyUsersEditables(String firstXpathKey,String expText){ highlight = false; //String envelopeMessage= OR.getProperty("NO_ENVELOPE_FOUND_MESSAGE"); WebElement message ; try{ //returnElementIfPresent("LINKOFTHEUSERS").click(); WebElement listOfTheOptions = returnElementIfPresent(firstXpathKey); //System.out.println("::: "+listOfTheOptions.getText()); //List options = listOfTheOptions.getText(); String actText = listOfTheOptions.getText(); actText = actText.trim(); String[] options = actText.split("\n"); /*for(int i = 0; i< options.length;i++){ System.out.println(":: : "+options[i]+" "+i+"*"+options.length); }*/ ArrayList<String> actList = new ArrayList<String>(Arrays.asList(options)); Collections.sort(actList); //System.out.println( "___________________----------- : "+Arrays.toString(actList.toArray())); expText = expText.trim(); String[] expOptions = expText.split(","); ArrayList<String> expList = new ArrayList<String>(Arrays.asList(expOptions)); Collections.sort(expList); ArrayList<String> temp = new ArrayList<String>(); temp = actList; List<Integer> comparingList = new ArrayList<Integer>(); // adding default values as one for (int a = 0; a < actList.size(); a++) { comparingList.add(0); } if(actList.size() == expList.size()){ for (int counter = 0; counter < expList.size(); counter++) { if (actList.contains(expList.get(counter))) { comparingList.set(counter, 1); /*System.out.println(":All elements are present as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug(":All elements are present as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray()));*/ }/*else{ highlight = true; System.out.println("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray())); //return "FAIL - Not able to match data with expected data"; }*/ } //System.out.println(comparingList); if (!comparingList.contains(0)) { System.out.println(":All elements are present as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug(":All elements are present as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray())); }else{ highlight = true; System.out.println("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray())); return "FAIL - Not able to match data with expected data"; } }else{ highlight = true; System.out.println("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray())); return "FAIL - Not able to match data with expected data"; } /*if(expList.removeAll(temp)){ System.out.println(":All elements are present as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug(":All elements are present as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray())); }else{ highlight = true; System.out.println("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is-> " + Arrays.toString(expList.toArray())); APP_LOGS.debug("FAIL : as Actual is-> " + Arrays.toString(actList.toArray()) + " AND Expected is->" + Arrays.toString(expList.toArray())); return "FAIL - Not able to match data with expected data."; }*/ //Iterator<String> itr=arrayList.iterator(); /*while(itr.hasNext()){ //System.out.println("Within iterator it is parsing : "+itr.next()); } */ //System.out.println("Act text : "+actText); //String actText = getColumnDataLink(firstXpathKey,secondXpathKey); //System.out.println("ActText is here : "+actText); /*String[] inter = actText.split(","); for(int i = 0; i< inter.length;i++){ System.out.println("Values : "+inter[i]); } for(int i = 0; i< inter.length;i++){ if (inter[i].contains(expText)){ System.out.println(": Actual is-> " + inter[i] + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + inter[i] + " AND Expected is->" + expText); } else{ highlight = true; System.out.println(": Actual is-> " + inter[i] + " AND Expected is-> " + expText); return "FAIL - Actual is-> " + inter[i] + " AND Expected is->" + expText; } }*/ /* }*/ } catch(Exception ex){ highlight = true; System.out.println("Data is mismatching with given data."); APP_LOGS.debug("Data is mismatching with given data."); return "FAIL - Data is mismatching with given data."; } return "PASS"; } public String VerifyNewlyCreatedProject(String firstXpathKey,String secondXpathKey,String expText){ highlight = false; String actText = getColumnData(firstXpathKey,secondXpathKey); String[] inter = actText.split(","); ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(inter)); for(int i = 0; i< inter.length;i++){ System.out.println("Values : "+inter[i]); } for(int i = 0; i< inter.length;i++){ if (inter[i].compareTo(expText) == 0){ System.out.println(": Actual is-> " + inter[i] + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + inter[i] + " AND Expected is->" + expText); break; } else if(i == inter.length-1){ if (inter[i].compareTo(expText) == 0){ System.out.println(": Actual is-> " + arrayList + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + arrayList + " AND Expected is->" + expText); break; }else{ highlight = true; System.out.println(": Actual is-> " + inter[i] + " AND Expected is-> " + expText); return "FAIL - Actual is-> " + inter[i] + " AND Expected is->" + expText; } } } return "PASS"; } public String VerifyElementPresent(String firstXpathKey,String expTEXT) throws ParseException{ /* @HELP @class: Keywords @method: VerifyElementPresent () @parameter: String firstXpathKey, String expText @notes: Performs the verification of the table data by getting column data from firstXpathKey and secondXpathKey and verify it against the expText or dataColVal.User can perform negative testing by passing boolean value in dataColVal. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Checking Element " + firstXpathKey + " Text from the Page"); APP_LOGS.debug(": Checking Element " + firstXpathKey + " Text from the Page"); highlight = false; try { //System.out.println(": Expeted string is ----> "+expTEXT); String sFlag=""; if(isElementPresent(firstXpathKey)){ sFlag="TRUE"; System.out.println(": Yes: Is element Present on Page----> "+sFlag); APP_LOGS.debug(": Yes: Is element Present on Page----> "+sFlag); } else{ sFlag="FALSE"; System.out.println(": No: Is element Present on Page----> "+sFlag); APP_LOGS.debug(": No: Is element Present on Page----> "+sFlag); } if(expTEXT.equals(sFlag)) { System.out.println(": Element is present in the page"); APP_LOGS.debug(": Element is " + firstXpathKey + " : Present in the page"); }else{ highlight = true; System.out.println(": Element is not present in the page"); APP_LOGS.debug(": Element is " + firstXpathKey + " : Not Present in the page"); } }catch(Exception e) { highlight = true; // System.out.println("inside VerifyElement"+e.getMessage()); return "FAIL - Not Able to verify Element is present or Not--" + firstXpathKey; } return "PASS"; } //***************** 13. VerifyText****************// @SuppressWarnings("unchecked") public String VerifyText(String firstXpathKey, String secondXpathKey, String expText) throws ParseException { /*@HELP @class: Keywords @method: VerifyText () @parameter: String firstXpathKey, Optional=>String secondXpathKey, Optional=> String expText @notes: Verifies the Actual Text as compared to the Expected Text. Verification can be performed on the same page or on different pages. User can perform two different webelement's text comparision by passing argument as objectKeySecond. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ //System.out.println("----------------------------------------------- : "+returnElementIfPresent(firstXpathKey).isDisplayed()); //System.out.println("----------------------##------------------------- : "+returnElementIfPresent(firstXpathKey).getText()); highlight = false; System.out.println(": Verifying " + firstXpathKey + " Text on the Page"); APP_LOGS.debug(": Verifying " + firstXpathKey + " Text on the Page"); String regex = "[0-9].[0-9]"; if (expText.matches(regex)) { NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(expText); long lnputValue = number.longValue(); expText = String.valueOf(lnputValue); } if (expText.isEmpty()) { getTextOrValues.put(secondXpathKey, returnElementIfPresent(secondXpathKey).getText()); expText = getTextOrValues.get(secondXpathKey).toString(); } try { getTextOrValues.put(firstXpathKey, returnElementIfPresent(firstXpathKey).getText()); actText = getTextOrValues.get(firstXpathKey).toString(); actText=actText.trim(); expText=expText.trim(); if (actText.compareTo(expText) == 0) { System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + actText + " AND Expected is->" + expText); } else { globalExpText=expText; System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to read text--" + firstXpathKey; } return "PASS"; } //***************** 14. VerifyTextDDTdata****************// @SuppressWarnings("unchecked") public String VerifyTextDDTdata(String firstXpathKey, String secondXpathKey, String expText) throws ParseException, InterruptedException { /* @HELP @class: Keywords @method: VerifyTextDDTdata () @parameter: String firstXpathKey, Optional=>String secondXpathKey, Optional=> String expText @notes: Verifies the Actual Text as compared to the Expected Text. Verification can be performed on the same page or on different pages for DDT. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ highlight = false; System.out.println(": Verifying " + firstXpathKey + " Text on the Page"); APP_LOGS.debug(": Verifying " + firstXpathKey + " Text on the Page"); try { getTextOrValues.put(firstXpathKey, returnElementIfPresent(firstXpathKey).getText()); //actText = getTextOrValues.get(firstXpathKey).toString().toLowerCase(); actText = getTextOrValues.get(firstXpathKey).toString(); if (actText.compareTo(expText) == 0) { System.out.println(": Actual is-> " + actText + " AND Expected is->" + expText); APP_LOGS.debug(": Actual is-> " + actText + " AND Expected is->" + expText); } else { globalExpText=expText; System.out.println(": Actual is-> " + actText + " AND Expected is->" + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to read text--" + firstXpathKey; } return "PASS"; } //***************** 15. VerifyTotalPrice****************// public String VerifyTotalPrice(String firstXpathKey, String secondXpathKey, String getInputData) throws Exception { /* * @HELP * @class: Keywords * @method: VerifyTotalPrice () * @parameter: String firstXpathKey, String secondXpathKey & String getInputData * @notes: Calculates the total product price and stores the value into expText local variable concated with "0" and compares the same with the actual product price. inputData value is used for calculating the total product price. * @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method * @END */ highlight = false; System.out.println(": Calculating the Total Price at Run Time & Verifying with Acutal"); APP_LOGS.debug(": Calculating the Total Price at Run Time & Verifying with Acutal"); double quantity = 1, totalPrice, actPrice; NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(getInputData); long lnputValue = number.longValue(); getInputData = String.valueOf(lnputValue); try { String qty = getInputData; quantity = Double.parseDouble(qty); String itemPrice = getTextOrValues.get(secondXpathKey).toString(); if (itemPrice.contains("$")) { itemPrice = itemPrice.replace("$", ""); } if (itemPrice.contains(",")) { itemPrice = itemPrice.replace(",", ""); } if (itemPrice.contains(" ")) { String str[] = itemPrice.split(" "); itemPrice = str[1]; } actPrice = Double.parseDouble(itemPrice); totalPrice = actPrice * quantity; //System.out.println(": "+totalPrice); String expText = String.valueOf(totalPrice).trim(); actText = returnElementIfPresent(firstXpathKey).getText(); if (actText.contains("$")) { actText = actText.replace("$", ""); } if (actText.contains(",")) { actText = actText.replace(",", ""); } if (actText.contains(" ")) { String str[] = actText.split(" "); actText = str[1]; } if (actText.compareTo(expText) == 0) { System.out.println(": Verifying Total Price: Actual is-> $" + actText + " AND Expected is-> $" + expText); APP_LOGS.debug(": Actual is-> $" + actText + " AND Expected is-> $" + expText); } else { System.out.println(": Verifying Total Price: Actual is-> $" + actText + " AND Expected is-> $" + expText); return "FAIL - Actual is-> $" + actText + " AND Expected is-> $" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to read text or value from --" + firstXpathKey + " OR " + secondXpathKey; } return "PASS"; } //***************** 16. VerifyTitle****************// public String VerifyTitle(String actTitle, String expTitle) { /* @HELP @class: Keywords @method: VerifyTitle () @parameter: String actTitle & String expTitle @notes: Verifies the Actual Web Page Title as compared to the Expected Web Page title. Verification is performed on the same Web page. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ highlight = false; System.out.println(": Verifying Page Title"); APP_LOGS.debug(": Verifying Page Title"); try { expTitle = expTitle.replace("_", ","); actTitle = driver.getTitle(); if (actTitle.compareTo(expTitle) == 0) { System.out.println(": Actual is-> " + actTitle + " AND Expected is->" + expTitle); APP_LOGS.debug(": Actual is-> " + actTitle + " AND Expected is->" + expTitle); } else { highlight = true; System.out.println(": Actual is-> " + actTitle + " AND Expected is->" + expTitle); return "FAIL - Actual is-> " + actTitle + " AND Expected is->" + expTitle; } } catch (Exception e) { highlight = true; return "FAIL - Not able to get title"; } return "PASS"; } //***************** 17. VerifyUrl****************// public String VerifyUrl(String actUrl, String expUrl) { /* @HELP @class: Keywords @method: VerifyUrl () @parameter: String actUrl, String expUrl @notes: Verifies the Actual Web Page URL as compared to the Expected Web Page URL. Verification is performed on the same Web page. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ highlight = false; System.out.println(": Verifying Current URL"); APP_LOGS.debug(": Verifying Current URL"); try { actUrl = driver.getCurrentUrl(); if (actUrl.compareTo(expUrl) == 0) { System.out.println(": Actual is-> " + actUrl + " AND Expected is->" + expUrl); APP_LOGS.debug(": Actual is-> " + actUrl + " AND Expected is->" + expUrl); } else { highlight = true; System.out.println(": Actual is-> " + actUrl + " AND Expected is->" + expUrl); return "FAIL - Actual is-> " + actUrl + " AND Expected is->" + expUrl; } } catch (Exception e) { highlight = true; return "FAIL - Not able to get URL"; } return "PASS"; } //***************** 18. HighlightNewWindowOrPopup****************// public String HighlightNewWindowOrPopup(String firstParam) throws Exception { /* @HELP @class: Keywords @method: HighlightNewWindowOrPopup () @parameter: None @notes: WebDriver Object focus should move to New Window or Popup @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Switching to NewWindow or Popup"); APP_LOGS.debug(": Switching to NewWindow or Popup"); try { winIDs = driver.getWindowHandles(); it = winIDs.iterator(); if (firstParam.equals("MainWindow")) { firstParam = it.next(); } else { firstParam = it.next(); firstParam = it.next(); } driver.switchTo().window(firstParam); } catch (Exception e) { return "FAIL - Not able to Switch to NewWindow or Popup"; } return "PASS"; } //***************** 19. HandlingJSAlerts****************// public String HandlingJSAlerts() throws Exception { /* @HELP @class: Keywords @method: HandlingJSAlerts () @parameter: None @notes: WebDriver Object focus should move to JavaScript Alerts @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Handling Java Scripts Alerts"); APP_LOGS.debug(": Handling Java Scripts Alerts"); try { Alert alt = driver.switchTo().alert(); alt.accept(); // alt.dismiss(); } catch (Exception e) { return "FAIL - Not able to Switch to NewWindow or Popup"; } return "PASS"; } //***************** 20. HighlightFrame****************// public String HighlightFrame(String inputData) throws Exception { /* @HELP @class: Keywords @method: HighlightFrame () @parameter: String inputData @notes: WebDriver Object focus should move to Frame @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Highlighting Frame"); APP_LOGS.debug(": Highlighting Frame"); NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(inputData); int frameID = number.intValue(); try { driver.switchTo().frame(frameID); } catch (Exception e) { return "FAIL - Not able to Highlight Frame"; } return "PASS"; } //***************** 21. OpenDBConnection****************// public String OpenDBConnection() { /* @HELP @class: Keywords @method: OpenDBConnection () @parameter: None @notes: Connect to the database mentioned in Config details. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Connecting to the "+databaseType+" database"); APP_LOGS.debug(": Connecting to the "+databaseType+" database"); try { if(databaseType.equals("My SQL")){ Class.forName("com.mysql.jdbc.Driver"); }else if(databaseType.equals("Oracle")){ Class.forName("oracle.jdbc.driver.OracleDriver"); }else if(databaseType.equals("MS SQL Server")){ Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); } } catch (ClassNotFoundException e) { System.out.println(": "+e.getMessage()); } try { connection = DriverManager.getConnection(dbConnection, dbUsername, dbPassword); } catch (SQLException e) { System.out.println(": "+e.getMessage()); return "FAIL - Not able to connect to the "+databaseType; } return "PASS"; } //***************** 22. ExecuteAndVerifyDBQuery****************// public String ExecuteAndVerifyDBQuery(String firstXpathKey, String expData) throws SQLException { /* @HELP @class: Keywords @method: ExecuteAndVerifyDBQuery () @parameter: String firstXpathKey @notes: Fetches the data from database and verifies the data with expected. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Fetching the data from "+databaseType+" database"); APP_LOGS.debug(": Fetching the data from "+databaseType+" database"); String selectQuery = OR.getProperty(firstXpathKey); ArrayList<String> actList=new ArrayList<String>(); ArrayList<String> expList=new ArrayList<String>(); expList.add(expData); try { statement = connection.createStatement(); ResultSet rs = statement.executeQuery(selectQuery); ResultSetMetaData rsMetaData = rs.getMetaData(); int tableColumnCount = rsMetaData.getColumnCount(); while (rs.next()) { for(int i=1; i<=tableColumnCount; i++){ actList.add(rs.getString(i)); } } if (actList.toString().equals(expList.toString())) { System.out.println(": Actual list is -> " + actList + " AND Expected list is-> " + expList); APP_LOGS.debug(": Actual list is -> " + actList + " AND Expected list is-> " + expList); } else { System.out.println(": Actual list is -> " + actList + " AND Expected list is-> " + expList); return "FAIL - Actual list is -> " + actList + " AND Expected list is-> " + expList; } } catch (SQLException e) { System.out.println(": "+e.getMessage()); return "FAIL"; } return "PASS"; } //***************** 23. ExecuteDBQuery****************// public String ExecuteDBQuery(String firstXpathKey) throws SQLException { /* @HELP @class: Keywords @method: ExecuteDBQuery () @parameter: String firstXpathKey @notes: Fetches the data from database and verifies the data with expected. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Executing "+firstXpathKey+" query"); APP_LOGS.debug(": Executing "+firstXpathKey+" query"); String query = OR.getProperty(firstXpathKey); try { statement = connection.createStatement(); statement.executeUpdate(query); } catch (SQLException e) { System.out.println(": "+e.getMessage()); return "FAIL"; } return "PASS"; } //***************** 24. CloseDBConnection****************// public String CloseDBConnection() { /* @HELP @class: Keywords @method: CloseDBConnection () @parameter: None @notes: Connect to the database @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Closing "+databaseType+" database"); APP_LOGS.debug(": Closing "+databaseType+" database"); try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (Exception e) { System.out.println(": "+e.getMessage()); return "FAIL"; } return "PASS"; } //***************** 25. CloseBrowser****************// public String CloseBrowser() { /* @HELP @class: Keywords @method: CloseBrowser () @parameter: None @notes: Closing the opened Browser after the Test Case Execution. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ getTextOrValues.clear(); scriptTableFirstRowData=""; System.out.println(": Closing the Browser"); APP_LOGS.debug(": Closing the Browser"); try { driver.close(); }catch (Exception e) { return "FAIL - Not able to Close Browser"; } return "PASS"; } //***************** 26. QuitBrowser****************// public String QuitBrowser() { /* @HELP @class: Keywords @method: QuitBrowser () @parameter: None @notes: Quits all opened Browsers or Brower instances after the test case Execution. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ getTextOrValues.clear(); scriptTableFirstRowData=""; System.out.println(": Quiting all opened Browsers"); APP_LOGS.debug(": Quiting all opened Browsers"); try { driver.quit(); driver = null; } catch (Exception e) { return "FAIL - Not able to Quit all opened Browsers"; } return "PASS"; } //***************** 7. MouseHover****************// public String MouseHover(String firstXpathKey) { /* @HELP @class: Keywords @method: MouseHoverAndClick () @parameter: String firstXpathKey @notes: Hover mouse over given Object, link, Hyperlink, selections or buttons of a web page. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing Mouse hover on " + firstXpathKey); APP_LOGS.debug(": Performing Mouse hover on " + firstXpathKey); try { Thread.sleep(2000); Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); act.moveToElement(root).build().perform(); //Thread.sleep(2000); } catch (Exception e) { return "FAIL - Not able to do mouse hover on -- " + firstXpathKey; } return "PASS"; } //***************** 7. MouseHoverAndClick****************// public String MouseHoverAndClick(String firstXpathKey, String secondXpathKey) { /* @HELP @class: Keywords @method: MouseHoverAndClick () @parameter: String firstXpathKey, String secondXpathKey @notes: Performs Click action on link, Hyperlink, selections or buttons of a web page. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing Mouse hover and Click action on " + firstXpathKey); APP_LOGS.debug(": Performing Mouse hover and Click action on " + firstXpathKey); try { Thread.sleep(2000); Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); act.moveToElement(root).build().perform(); Thread.sleep(1000); returnElementIfPresent(secondXpathKey).click(); } catch (Exception e) { return "FAIL - Not able to do mouse hover and click on -- " + firstXpathKey; } return "PASS"; } // *****************Singleton Class******************** public static Keywords getKeywordsInstance() throws IOException { if (keywords == null) { keywords = new Keywords(); } return keywords; } public String TestCaseEnds() { /* @HELP @class: Keywords @method: TestCaseEnds () @parameter: None @notes: Performs necessary actions before concluding the testcase like if testcase has anything fail it will declare by Assert. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": TestCase is Ending"); APP_LOGS.debug(": TestCase is Ending"); getTextOrValues.clear(); scriptTableFirstRowData=""; try { if (Fail == true) { highlight = false; Fail = false; //QuitBrowser(); //driver=null; Assert.assertTrue(false, failedResult); }else { Fail = true; Assert.assertTrue(true, failedResult); Fail = false; } } catch (Exception e) { return "FAIL - Not able to end TC"; } return "PASS"; } public String getLastTestCaseName(){ /* @HELP @class: Keywords @method: getLastTestCaseName () @returns: returns last test case name from Master.xlsx file which have runmode Y into any combination @END */ Xls_Reader x =new Xls_Reader(masterxlsPath + "/Master.xlsx"); String suiteType= suitetype; if(!suiteType.contains("_") && !suiteType.equalsIgnoreCase("Regression")){ int totalRows = x.getRowCount("Test Cases"); String lastTestCaseName = null; String tcType=null; String runMode=null; for(int i = 1; i <= totalRows; i++){ tcType = x.getCellData("Test Cases",1,i); if(tcType.contains(suiteType)){ runMode = x.getCellData("Test Cases",2,i); if(runMode.contains("Y")){ lastTestCaseName = x.getCellData("Test Cases",0,i); } } }System.out.println("Last Test Case Name is: "+lastTestCaseName); return lastTestCaseName; } else if(suiteType.contains("_")){ System.out.println(": This suiteType contains UnderScore and is: "+suiteType); String splitArray[] = suiteType.split("_"); int totalRows = x.getRowCount("Test Cases"); String lastTestCaseName = null; String tcType=null; String runMode=null; for(int i = 1; i <= totalRows; i++){ tcType = x.getCellData("Test Cases",1,i); if(tcType.contains(splitArray[0]) || tcType.contains(splitArray[1])){ runMode = x.getCellData("Test Cases",2,i); if(runMode.contains("Y")){ lastTestCaseName = x.getCellData("Test Cases",0,i); } } }System.out.println("Last Test Case Name is: "+lastTestCaseName); return lastTestCaseName; } else { System.out.println(": This suiteType is "+suiteType); int totalRows = x.getRowCount("Test Cases"); String lastTestCaseName = null; String runMode=null; for(int i = 1; i <= totalRows; i++){ runMode = x.getCellData("Test Cases",2,i); if(runMode.equalsIgnoreCase("Y")){ lastTestCaseName = x.getCellData("Test Cases",0,i); } }System.out.println("Last Test Case Name is: "+lastTestCaseName); return lastTestCaseName; } } public String SwitchToNewWindow(){ /* @HELP @class: Keywords @method: SwitchToNewWindow () @parameter: None @notes: Switches to new window and move the control of the driver to the newly opened window. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try{ System.out.println(": Switching to New Window"); APP_LOGS.debug(": Switching to New Window"); Set <String> set = driver.getWindowHandles(); Iterator<String> itr = set.iterator(); parentWindowID = itr.next(); String ChID = itr.next(); driver.switchTo().window(ChID); }catch(Exception e){ System.out.println("Not Able To Perform SwitchToNewWindow"); } return "PASS"; } public String SwitchToParentWindow(){ /* @HELP @class: Keywords @method: SwitchToParentWindow () @parameter: None @notes: Switches to parent window and move the control of the driver main window of the browser. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try{ System.out.println(": Switching to Parent Window"); APP_LOGS.debug(": Switching to Parent Window"); driver.switchTo().window(parentWindowID); }catch(Exception e){ System.out.println("Not Able To Perform SwitchToParentWindow"); } return "PASS"; } public String clearTextField(String firstXpathKey){ /* @HELP @class: Keywords @method: clearTextField () @parameter: None @notes: Clearing Text Field. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try { System.out.println(": Clearing Text Field"); APP_LOGS.debug(": Clearing Text Field"); Thread.sleep(1000); returnElementIfPresent(firstXpathKey).clear(); } catch (InterruptedException e) { System.out.println("Not Able to perform clearTextField"); } return "PASS"; } public String ScrollPageToBottom() { /* @HELP @class: Keywords @method: ScrollPageToBottom () @parameter: None @notes: Scroll The Page to END in terms of what element is passed in firstXpathKey. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println("Scrolling The Page to END Using END key"); APP_LOGS.debug(": Scrolling The Page to END Using END key"); try { ((JavascriptExecutor) driver) .executeScript("window.scrollTo(0, document.body.scrollHeight)"); } catch (Exception e) { return "FAIL - Not Able to Scrol The Page to END Using END key"; } return "PASS"; } public String ScrollPageToEnd(String firstXpathKey) { /* @HELP @class: Keywords @method: ScrollPageToEnd () @parameter: None @notes: Scroll The Page to END in terms of what element is passed in firstXpathKey. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println("Scrolling The Page to END Using END key"); APP_LOGS.debug(": Scrolling The Page to END Using END key"); try { WebElement element = returnElementIfPresent(firstXpathKey); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element); } catch (Exception e) { return "FAIL - Not Able to Scrol The Page to END Using END key"; } return "PASS"; } //***************** VerifyURLDDTContent****************// public String VerifyURLDDTContent(String expUrlContent) { /* @HELP @class: Keywords @method: VerifyURLDDTContent () @parameter: String actUrl, String expUrl @notes: Verifies the Actual Web Page URL as compared to the Expected Web Page URL. Verification is performed on the same Web page in DDT manner. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Verifying "+ expUrlContent + " is Present in URL"); APP_LOGS.debug(": Verifying "+ expUrlContent + " is Present in URL"); highlight = false; try { actUrl = driver.getCurrentUrl(); if (actUrl.contains(expUrlContent)) { System.out.println(": Expected String-> " + expUrlContent + " is Present in Current URL-> " + actUrl); APP_LOGS.debug(": Expected String-> " + expUrlContent + " is Present in Current URL-> " + actUrl); System.out.println(": Expected is->" + expUrlContent); APP_LOGS.debug(": Expected is->" + expUrlContent); } else { System.out.println(": FAIL- Expected String-> " + expUrlContent + " is NOT Present in Current URL-> " + actUrl); APP_LOGS.debug(": FAIL- Expected String-> " + expUrlContent + " is NOT Present in Current URL-> " + actUrl); return "FAIL- Expected String-> " + expUrlContent + " is NOT Present in Current URL-> " + actUrl; } } catch (Exception e) { highlight = true; return "FAIL - Not able to verify URL content"; } return "PASS"; } //***************** verifyDDTImageExistsByImgSRC****************// public String VerifyDDTImageExistsByImgSRC(String firstXpathKey, String inputData) { /* @HELP @class: Keywords @method: VerifyDDTImageExistsByImgSRC () @parameter: None @notes: Performs verification of the Img content src attribute on web page by dataColVal. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Verifying Image Exists by its SRC property"); APP_LOGS.debug(": Verifying Image Exists by its SRC property"); highlight = false; try{ WebElement img= returnElementIfPresent(firstXpathKey); String src = img.getAttribute("src"); APP_LOGS.debug(": Expected SRC "+ inputData); APP_LOGS.debug(": Actual SRC "+ src); if (src.compareTo(inputData) == 0) { System.out.println(": Expected SRC Of Image-> " + inputData + " Actual SRC of Image-> " + src); APP_LOGS.debug(": Expected SRC Of Image-> " + inputData + " Actual SRC of Image-> " + src); } else{ System.out.println(": FAIL- Expected SRC Of Image-> " + inputData + " is not present in Actual SRC of Image-> " + src); APP_LOGS.debug(": FAIL- Expected SRC Of Image-> " + inputData + " is not present in Actual SRC of Image-> " + src); return "FAIL- Expected SRC Of Image-> " + inputData + " is not present in Actual SRC of Image-> " + src; } } catch (Exception e) { highlight = true; return "FAIL - Not able to verify SRC Of Image"; } return "PASS"; } public String GoToHomeLoansSubMenu(String firstXpathKeyOption, String secondXpathKeyOption) { /* @HELP @class: Keywords @method: GoToHomeLoansSubMenu () @parameter: Two @notes: This Method is created as generic method as per LT project requirement as there are two ways to go to "HOME EQUITY" sub menu links. Example: for "HOME EQUITY LOANS", One is via "HOME LOANS> HOME EQUITY LOANS" and other is "ALL>Home Equity". firstXpathKeyOption is for "HOME EQUITY LOANS" sub link AND secondXpathKeyOption is for "Home Equity" sub link IMP: Please make sure that identifiers for "HOME LOANS" and "ALL" Menu links are present in OR file. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ if (returnElementIfPresent("HOME_LOANSLINK")!=null){ MouseHoverAndClick("HOME_LOANSLINK",firstXpathKeyOption); } else{ MouseHoverAndClick ("ALL_LINK", secondXpathKeyOption); } return "PASS"; } public String switchToiFrame(String dataValue) { /* @HELP @class: Keywords @method: switchToiFrame () @parameter: One @notes: Parameter will be integer of iframe tag index of the HTML page @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Switching to iframe "+dataValue ); APP_LOGS.debug(": Switching to iframe"); try { driver.switchTo().frame(0); System.out.println(" : Crossed"); } catch (Exception e) { return "FAIL - Not Able to switch to iframe"; } return "PASS"; } public String switchToDefaultContent() { /* @HELP @class: Keywords @method: switchToDefaultContent () @parameter: One @notes: No parameter is needed for this method it will give control to the main page for switching form iFrame. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Switch default content from iframe"); APP_LOGS.debug(": Switch default content from iframe"); try { driver.switchTo().defaultContent(); } catch (Exception e) { return "FAIL - Not Able to switch default content from iframe"; } return "PASS"; } //***************** VerifyTextContains****************// @SuppressWarnings("unchecked") public String VerifyTextContains(String firstXpathKey, String secondXpathKey, String expText) throws ParseException { /*@HELP @class: Keywords @method: VerifyTextContains () @parameter: String firstXpathKey, Optional=>String secondXpathKey, Optional=> String expText @notes: Verifies the Actual Text as compared to the Expected Text. Verification can be performed on the same page or on different pages. User can perform two different webelement's text comparision by passing argument as objectKeySecond. In this it is not necessary expText should have as a whole it uses contains function. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ //System.out.println("^^^^^^^^^^^^^^^^Dhruval Patel : "+expText); highlight = false; System.out.println(": Verifying " + firstXpathKey + " Text on the Page"); APP_LOGS.debug(": Verifying " + firstXpathKey + " Text on the Page"); String regex = "[0-9].[0-9]"; if (expText.matches(regex)) { //System.out.println("----------------------------------------------- : 1"); NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(expText); long lnputValue = number.longValue(); expText = String.valueOf(lnputValue); } if (expText.isEmpty()) { //System.out.println("----------------------------------------------- : 2"); getTextOrValues.put(secondXpathKey, returnElementIfPresent(secondXpathKey).getText()); expText = getTextOrValues.get(secondXpathKey).toString(); System.out.println("----------------------------------------------- : 3"); } try { //System.out.println("----------------------------------------------- : "+returnElementIfPresent(firstXpathKey).isDisplayed()); getTextOrValues.put(firstXpathKey, returnElementIfPresent(firstXpathKey).getText()); //System.out.println("----------------------##------------------------- : "+returnElementIfPresent(firstXpathKey).getText()); actText = getTextOrValues.get(firstXpathKey).toString(); actText=actText.trim(); expText=expText.trim(); if (actText.contains(expText) == true) { System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + actText + " AND Expected is->" + expText); } else { globalExpText=expText; System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to read text--" + firstXpathKey; } return "PASS"; } //***************** VerifyToolTip****************// public String VerifyToolTip(String firstXpathKey, String expText) { /* @HELP @class: Keywords @method: VerifyToolTip () @parameter: String firstXpathKey @notes: Hover mouse over given Object, link, Hyperlink, selections or buttons of a web page and get the tooltip from the element and verifies it with expText. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ highlight = false; System.out.println(": Performing Mouse hover on " + firstXpathKey); APP_LOGS.debug(": Performing Mouse hover on " + firstXpathKey); try { Thread.sleep(2000); Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); act.moveToElement(root).build().perform(); Thread.sleep(2000); String actText=root.getText(); if(actText.contains(expText)){ System.out.println(": Actual is-> " + actText + " AND Expected is->" + expText); APP_LOGS.debug(": Actual is-> " + actTitle + " AND Expected is->" + expText); } else { highlight = true; System.out.println(": Actual is-> " + actText + " AND Expected is->" + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to get tool tip text"; } return "PASS"; } //***************** VerifyTextDDTdataContains****************// @SuppressWarnings("unchecked") public String VerifyTextDDTdataContains(String firstXpathKey, String secondXpathKey, String expText) throws ParseException, InterruptedException { /* @HELP @class: Keywords @method: VerifyTextDDTdata () @parameter: String firstXpathKey, Optional=>String secondXpathKey, Optional=> String expText @notes: Verifies the Actual Text as compared to the Expected Text. Verification can be performed on the same page or on different pages for DDT. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ highlight = false; System.out.println(": Verifying " + firstXpathKey + " Text on the Page"); APP_LOGS.debug(": Verifying " + firstXpathKey + " Text on the Page"); //System.out.println("Inside VerifyTextDDTdataContains..............................."); try { getTextOrValues.put(firstXpathKey, returnElementIfPresent(firstXpathKey).getText()); //actText = getTextOrValues.get(firstXpathKey).toString().toLowerCase(); actText = getTextOrValues.get(firstXpathKey).toString(); actText=actText.trim(); expText=expText.trim(); if (actText.contains(expText)) { System.out.println(": Actual is-> " + actText + " AND Expected is->" + expText); APP_LOGS.debug(": Actual is-> " + actText + " AND Expected is->" + expText); } else { globalExpText=expText; System.out.println(": Actual is-> " + actText + " AND Expected is->" + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to read text--" + firstXpathKey; } return "PASS"; } //***************** 16. VerifyTitle****************// public String VerifyTitleContains(String expTitle) { /* @HELP @class: Keywords @method: VerifyTitle () @parameter: String actTitle & String expTitle @notes: Verifies the Actual Web Page Title as compared to the Expected Web Page title. Verification is performed on the same Web page. It is not necessary to have full page title as expTitle. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ //System.out.println("Inside VerifyTitleContains.................... "); highlight = false; System.out.println(": Verifying Page Title"); APP_LOGS.debug(": Verifying Page Title"); try { expTitle = expTitle.replace("_", ","); expTitle.trim(); actTitle = driver.getTitle(); if (actTitle.contains(expTitle)) { System.out.println(": Actual is-> " + actTitle + " AND Expected is->" + expTitle); APP_LOGS.debug(": Actual is-> " + actTitle + " AND Expected is->" + expTitle); } else { highlight = true; System.out.println(": Actual is-> " + actTitle + " AND Expected is->" + expTitle); return "FAIL - Actual is-> " + actTitle + " AND Expected is->" + expTitle; } } catch (Exception e) { highlight = true; return "FAIL - Not able to get title"; } return "PASS"; } //***************** 21. OpenMongoDBConnection****************// public String OpenMongoDBConnection() { /* @HELP @class: Keywords @method: OpenMongoDBConnection () @parameter: None @notes: Connect to the Mongo database @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Connecting to the "+databaseType+" database"); APP_LOGS.debug(": Connecting to the "+databaseType+" database"); try { mongoClient = new MongoClient( new MongoClientURI(dbConnection)); db = mongoClient.getDatabase("np-staging-credit-card-offers"); // DB Name System.out.println(": Connected to the "+databaseType+" database Successfully"); APP_LOGS.debug(": Connected to the "+databaseType+" database Successfully"); } catch (Exception e) { System.out.println(": "+e.getMessage()); return "FAIL - Not able to connect to the "+databaseType; } return "PASS"; } //***************** 21. VerifyMongoDBQuery****************// public String VerifyMongoDBQuery(final String expDBData) { /* @HELP @class: Keywords @method: VerifyMongoDBQuery () @parameter: None @notes: Verifying MongoDB Data @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ getConfigDetails(); System.out.println(": Verfying '"+expDBData+"' Issuer is present in database"); APP_LOGS.debug(": Verfying '"+expDBData+"' Issuer is present in database"); highlight = false; try { BasicDBObject whereQuery = new BasicDBObject(); System.out.println(": Firing {'name' : '"+expDBData+"'} Query to database"); APP_LOGS.debug(": Firing {'name' : '"+expDBData+"'} Query to database"); whereQuery.put("name", expDBData); FindIterable<Document> iterable = db.getCollection("issuers").find(whereQuery); iterable.forEach(new Block<Document>() { @Override public void apply(final Document document) { String temp = document.toString(); System.out.println(": Actual data received from Database as result of above Query: "+temp); APP_LOGS.debug(": Actual data received from Database as result of above Query: "+temp); if (temp.contains(expDBData)) { System.out.println(": "+expDBData+" Data is present in DataBase"); APP_LOGS.debug(": "+expDBData+" Data is present in DataBase"); } } }); } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not able to Verify the Data: "+ expDBData; } return "PASS"; } //***************** 21. CloseMongoDBConnection****************// public String CloseMongoDBConnection() { /* @HELP @class: Keywords @method: CloseMongoDBConnection () @parameter: None @notes: Close MongoDB Connection @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Closing "+databaseType+" Database Connection"); APP_LOGS.debug(": Closing "+databaseType+" Database Connection"); try { mongoClient.close(); System.out.println(": "+databaseType+" Database Connection is Closed"); APP_LOGS.debug(": "+databaseType+" Database Connection is Closed"); } catch (Exception e) { System.out.println(": "+e.getMessage()); return "FAIL - Not able to close : " +databaseType+" Database Connection"; } return "PASS"; } //***************** 21. startHARReading****************// public String startHARReading() { /* @HELP @class: Keywords @method: startHARReading () @parameter: None @notes: It will start recording the Network panel data with new browser instance. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Capturing Network Panel Data "); APP_LOGS.debug(": Capturing Network Panel Data "); try { // // HarFileWriter w = new HarFileWriter(); // System.out.println("Reading " + harPath); List<HarWarning> warnings = new ArrayList<HarWarning>(); //HarLog log = r.readHarFile(f, warnings); server.newHar(); Thread.sleep(3000); System.out.println(": Started Capturing Network Panel data in HAR Format"); APP_LOGS.debug(": Started Capturing Network Panel data in HAR Format"); } catch (Exception e) { System.out.println(": "+e.getMessage()); return "FAIL - Not able to Start Capturing Network Panel data in HAR Format"; } return "PASS"; } //***************** 21. stopHARReading****************// public String stopHARReading() { /* @HELP @class: Keywords @method: stopHARReading () @parameter: None @notes: stops the recording of the Network panel data. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Stopping Network Panel Data Capture and Saving it in HAR file"); APP_LOGS.debug(": Stopping Network Panel Data Capture and Saving it in HAR file"); try { har = server.getHar(); FileOutputStream fos = new FileOutputStream(harPath); har.writeTo(fos); server.endHar(); Thread.sleep(3000); System.out.println(": Network Panel Data is Captured and Saved in HAR file"); APP_LOGS.debug(": Network Panel Data is Captured and Saved in HAR file"); } catch (Exception e) { System.out.println(": "+e.getMessage()); return "FAIL - Not able to Capture and Save Network Panel Data as HAR file"; } return "PASS"; } //***************** 21. VerifyHARContent****************// public String VerifyHARContent(String data) { /* @HELP @class: Keywords @method: VerifyHARContent () @parameter: None @notes: Verifies Html archive content through saved .har file in HAR folder. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ String[] temp; System.out.println(": Verifing : "+data+" is Present in HAR file"); APP_LOGS.debug(": Verifing : "+data+" is Present in HAR file"); highlight = false; try { log = r.readHarFile(f, warnings); entries = log.getEntries(); String mk=entries.toString(); temp = data.split(","); for(int i = 0; i<temp.length;i++){ System.out.println(": Verifing "+temp[i]+" is Present in HAR file"); APP_LOGS.debug(": Verifing "+temp[i]+" is Present in HAR file"); if(mk.contains(temp[i].toString())) { System.out.println(": "+temp[i]+" is Present in HAR file"); APP_LOGS.debug(": "+temp[i]+" is Present in HAR file"); }else{ System.out.println("Fail : "+temp[i]+" is Not Present in HAR file"); APP_LOGS.debug("Fail : "+temp[i]+" is Not Present in HAR file"); } } } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to verify " +data+ "in HAR file"; } return "PASS"; } //***************** VerifyXMLContent****************// public String VerifyXMLContent(String data) throws IOException,ParserConfigurationException,SAXException,IOException { /* @HELP @class: Keywords @method: VerifyXMLContent () @parameter: None @notes: Verifies content of previously gained HttpRequest in MakeGetRequestDDT with expected data given in module excel. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Verifing 'Lender Name' and "+data+" is Present in GET Response XML file"); APP_LOGS.debug(": Verifing 'Lender Name' and "+data+" is Present in GET Response XML file"); highlight = false; String[] temp; ArrayList<String> al = new ArrayList<String>(); File file = new File(SRC_FOLDER2+"/data.xml"); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(StrGet); bw.close(); try{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // factory.setValidating(true); factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document doc = builder.parse(file); Element element = doc.getDocumentElement(); // get all child nodes NodeList nodes = element.getElementsByTagName(data); for (int i = 0; i < nodes.getLength(); i++) { System.out.println("" + nodes.item(i).getTextContent()); String dtr= nodes.item(i).getTextContent(); al.add(dtr); } //System.out.println( "::::: "+doc.getChildNodes()); if (al.size() > 0) { System.out.println(": Following 'Lender Names' are Present in GET response XML->" + al.toString()); APP_LOGS.debug(": Following 'Lender Names' are Present in GET response XML->" + al.toString()); } else { //highlight = true; System.out.println("::::::: FAIL: No 'Lender Name' is Present in GET response XML"); APP_LOGS.debug(": FAIL: No 'Lender Name' is Present in GET response XML"); return "*FAIL - Not Able to verify 'Lender Name' in GET Response XML"; } } catch (Exception e) { //highlight = true; System.out.println(": " + e.getMessage()); return "FAIL - Not Able to verify 'Lender Name' in GET Response XML"; } /*try { while (StrGet.contains("<StudentLoanOffer>")) { temp = StrGet.split("<Lender>", 2); if (temp.length == 1) { break; } else { StrGet = temp[1]; } int retval = StrGet.indexOf(data); String dataWithForwardslash = data.replace("<", "</"); int endIndex = StrGet.indexOf(dataWithForwardslash); String dtr = StrGet.substring(retval, endIndex); dtr = dtr.replace("<Name>", ""); al.add(dtr); } if (al.size() > 0) { System.out.println(": Following 'Lender Names' are Present in GET response XML->" + al.toString()); APP_LOGS.debug(": Following 'Lender Names' are Present in GET response XML->" + al.toString()); } else { //highlight = true; System.out.println("::::::: FAIL: No 'Lender Name' is Present in GET response XML"); APP_LOGS.debug(": FAIL: No 'Lender Name' is Present in GET response XML"); return "*FAIL - Not Able to verify 'Lender Name' in GET Response XML"; } } catch (Exception e) { //highlight = true; System.out.println(": " + e.getMessage()); return "FAIL - Not Able to verify 'Lender Name' in GET Response XML"; }*/ return "PASS"; } public String VerifyCompleteGetResponse(String data) throws org.json.simple.parser.ParseException { /* @HELP @class: Keywords @method: VerifyCompleteGetResponse () @parameter: None @notes: verifies the complete response of the GET request by equalsIgnoreCase. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Verifing and "+data+" is Present in GET Response XML file"); APP_LOGS.debug(": Verifing and "+data+" is Present in GET Response XML file"); highlight = false; //String[] temp; //ArrayList<String> al = new ArrayList<String>(); try { JSONParser parser = new JSONParser(); JSONObject obj2_json = (JSONObject) parser.parse(StrGet); String temp[] = null; temp = data.split(","); System.out.println(obj2_json.get(temp[0])); if (obj2_json.get(temp[0]).equals(temp[1])) { System.out.println(": Following " + temp[1]+ " are Present in GET response "); APP_LOGS.debug(": Following " + temp[1]+ " are Present in GET response "); } else { APP_LOGS.debug("FAIL - Not Able to verify " + temp[1]+ " in GET Response"); return "FAIL - Not Able to verify " + temp[1] + " in GET Response"; } } catch (Exception e) { // highlight = true; System.out.println(": " + e.getMessage()); return "FAIL - Not Able to verify " + data + " in GET Response XML"; } return "PASS"; } //***************** VerifyPOSTRequestContent****************// @SuppressWarnings("unchecked") public String VerifyPOSTRequestContent(String data) { /* @HELP @class: Keywords @method: VerifyPOSTRequestContent () @parameter: None @notes: Verifies content of previously gained HttpRequest in MakePostRequest or MakePostRequestJSON with expected data given in module excel. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Verifing : "+data+" is Present in POST response"); APP_LOGS.debug(": Verifing : "+data+" is Present in POST response"); highlight = false; try { data = data.trim(); /* JSONParser parser = new JSONParser(); //Object obj = parser.parse(str); // JSONArray array = (JSONArray)obj; JSONObject obj2 = (JSONObject) parser.parse(str);*/ /* StrPost = StrPost.replace("\"", ""); data = data.replace("\"", "");*/ // System.out.println("StrPost ::::::::::::::::::::: "+StrPost+" data :::::::::::::::" +data); if (StrPost.contains(data)) { // System.out.println("IF ///////////////////////////////"); System.out.println(": Actual is-> " + StrPost + " AND Expected is->" + data); APP_LOGS.debug(": Actual is-> " + StrPost + " AND Expected is->" + data); } else { //highlight = true; //System.out.println("Else ..................................."); System.out.println(": Actual is-> " + StrPost + " AND Expected is->" + data); return ": Actual is-> " + StrPost + " AND Expected is->" + data; } } catch (Exception e) { //highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to verify " +data+ "in XML respose"; } return "PASS"; } //***************** executeHttpGet****************// public HttpResponse executeHttpGet(String uri, Map<String, String> headerMap) throws ClientProtocolException, IOException { HttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(uri); Iterator<String> itr = headerMap.keySet().iterator(); while (itr.hasNext()) { String key = (String) itr.next(); get.addHeader(key, headerMap.get(key).toString()); } return client.execute(get); } //***************** executeHttpPost****************// public HttpResponse executeHttpPost(String uri, Map<String, String> headerMap, String body) throws ClientProtocolException, IOException { EntityBuilder builder = EntityBuilder.create(); builder.setText(body); HttpEntity entity = builder.build(); HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(uri); Iterator<String> itr = headerMap.keySet().iterator(); while (itr.hasNext()) { String key = (String) itr.next(); post.addHeader(key, headerMap.get(key).toString()); } post.setEntity(entity); return client.execute(post); } //***************** processResponse****************// public StringBuffer processResponse(HttpResponse response) throws ClientProtocolException, IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result; } private StringBuffer readFile(String filePath) { BufferedReader br = null; StringBuffer stringBuffer = new StringBuffer(); try { String lineString = null; br = new BufferedReader(new java.io.FileReader(filePath)); while ((lineString = br.readLine()) != null) { stringBuffer.append(lineString); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } return stringBuffer; } //*****************SignOutIFAlreadyLoggedIn****************// public String SignOutIFAlreadyLoggedIn(String firstXpathKey, String secondXpathKey) { /* @HELP @class: Keywords @method: SignOutIFAlreadyLoggedIn () @parameter: String firstXpathKey & String secondXpathKey @notes: LT PROJECT SPECIFIC KEYWORD: Perform Signout at home page if user is already logged in. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ try { if (isElementPresent(firstXpathKey)) { System.out.println(": User is already looged in, Performing Mouse hover on " + firstXpathKey); APP_LOGS.debug(": User is already looged in, Performing Mouse hover on " + firstXpathKey); Thread.sleep(2000); Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); act.moveToElement(root).build().perform(); Thread.sleep(2000); returnElementIfPresent(secondXpathKey).click(); } else{ System.out.println(": No User is Logged-IN."); APP_LOGS.debug(": No User is Logged-IN."); } } catch (Exception e) { return "FAIL - Not able to Signout."; } return "PASS"; } //***************** makeGetRequest****************// public String makeGetRequest(String data) throws ClientProtocolException, IOException { /* @HELP @class: Keywords @method: makeGetRequest () @parameter: None @notes: takes dataColVal as URL stering to make GET resuest using apache library supported HttpRequest and HttpResponse @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Making GET request:-> "+data); APP_LOGS.debug(": Making GET request:-> "+data); highlight = false; try { data = data.trim(); HashMap<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Content-type", "text/xml"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpGet(data, headerMap); StrGet = this.processResponse(response).toString(); //StrGet = getMethodResponce; } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to make GET request " +data; } return "PASS"; } //***************** makeGetRequestDDT****************// public String makeGetRequestDDT(String data) throws ClientProtocolException, IOException { /* @HELP @class: Keywords @method: makeGetRequest () @parameter: None @notes: takes dataColVal as URL stering to make GET resuest using apache library supported HttpRequest and HttpResponse in DDT manner. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Making GET request:-> "+data); APP_LOGS.debug(": Making GET request:-> "+data); highlight = false; try { data = data.trim(); HashMap<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Content-type", "text/xml"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpGet(data, headerMap); StrGet = this.processResponse(response).toString(); //StrGet = getMethodResponce; } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to make GET request " +data; } return "PASS"; } //***************** makePostRequest****************// public String makePostRequest(String data) { /* @HELP @class: Keywords @method: VerifyPOSTRequestContent () @parameter: None @notes: Makes POST request with attached data in form of file saved on HDD( in XMLForLT folder of the framework) using apache apache library supported HttpRequest and HttpResponse. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Making POST request with XML DATA:-> "+data); APP_LOGS.debug(": Making POST request with XML DATA:-> "+data); highlight = false; try { data = data.trim(); String filePathFromInput = null; String twoDimentionArray[] = data.split(","); filePathFromInput = twoDimentionArray[1]; System.out.println(twoDimentionArray[0]+" "+twoDimentionArray[1]); String dataR = this.readFile(xmlForLT+filePathFromInput).toString(); //StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); HashMap<String, String> headerMap = new HashMap<String, String>(); headerMap.put("Content-type", "text/xml"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpPost(twoDimentionArray[0], headerMap, dataR); StrPost = this.processResponse(response).toString().trim(); } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to verify " +data+ "in XML file"; } return "PASS"; } public String makePostRequestJSON(String data) { /* @HELP @class: Keywords @method: VerifyPOSTRequestContent () @parameter: None @notes: Makes POST request with attached data in form of file saved on HDD( in XMLForLT folder of the framework which contains JSON file) using apache apache library supported HttpRequest and HttpResponse. In dataColValue user must pass file path followed by URL e.g https://offers.dev.lendingtree.com/formstore/submit-lead.ashx,/XMLForLT/LT_02_Verify_POST_API_JSON.json @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Making POST request with JSON DATA:-> "+data); APP_LOGS.debug(": Making POST request with JSON DATA:-> "+data); highlight = false; try { data = data.trim(); String filePathFromInput = null; String twoDimentionArray[] = data.split(","); filePathFromInput = twoDimentionArray[1]; System.out.println(twoDimentionArray[0]+" "+twoDimentionArray[1]); String dataR = this.readFile(xmlForLT+filePathFromInput).toString(); //StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); HashMap<String, String> headerMap = new HashMap<String, String>(); //headerMap.put("Content-type", "text/xml"); headerMap.put("content-type", "application/json"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpPost(twoDimentionArray[0], headerMap, dataR); StrPost = this.processResponse(response).toString().trim(); } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to procure " +data+ " JSON response"; } return "PASS"; } public String dragAndDropByCoordinates(String firstXpathKey,String data) { /* @HELP @class: Keywords @method: dragAndDropByCoordinates (data) @parameter: None @notes: Makes POST request with attached data in form of file saved on HDD( in XMLForLT folder of the framework which contains JSON file) using apache apache library supported HttpRequest and HttpResponse. In dataColValue user must pass file path followed by URL e.g https://offers.dev.lendingtree.com/formstore/submit-lead.ashx,/XMLForLT/LT_02_Verify_POST_API_JSON.json @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing drag and drop :-> "+data); APP_LOGS.debug(": Performing drag and drop :-> "+data); highlight = false; try { data = data.trim(); //String filePathFromInput = null; String twoDimentionArray[] = data.split(","); //filePathFromInput = twoDimentionArray[1]; System.out.println(twoDimentionArray[0]+" "+twoDimentionArray[1]); //String dataR = this.readFile(xmlForLT+filePathFromInput).toString(); Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); Integer x = new Integer(twoDimentionArray[0]); Integer y = new Integer(twoDimentionArray[1]); act.dragAndDropBy(root, x,y).perform(); Thread.sleep(3000); //StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); /*HashMap<String, String> headerMap = new HashMap<String, String>(); //headerMap.put("Content-type", "text/xml"); headerMap.put("content-type", "application/json"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpPost(twoDimentionArray[0], headerMap, dataR); StrPost = this.processResponse(response).toString().trim(); */ } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to perform drag and drop "; } return "PASS"; } public String dragAndDropByElement(String firstXpathKey,String secondXpathKey) { /* @HELP @class: Keywords @method: dragAndDropByCoordinates (data) @parameter: None @notes: Makes POST request with attached data in form of file saved on HDD( in XMLForLT folder of the framework which contains JSON file) using apache apache library supported HttpRequest and HttpResponse. In dataColValue user must pass file path followed by URL e.g https://offers.dev.lendingtree.com/formstore/submit-lead.ashx,/XMLForLT/LT_02_Verify_POST_API_JSON.json @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing drag and drop :-> "); APP_LOGS.debug(": Performing drag and drop :-> "); highlight = false; try { /*data = data.trim(); String filePathFromInput = null; String twoDimentionArray[] = data.split(","); /*filePathFromInput = twoDimentionArray[1]; System.out.println(twoDimentionArray[0]+" "+twoDimentionArray[1]); *///String dataR = this.readFile(xmlForLT+filePathFromInput).toString(); Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); WebElement target=returnElementIfPresent(secondXpathKey); act.dragAndDrop(root, target).perform(); Thread.sleep(3000); //StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); /*HashMap<String, String> headerMap = new HashMap<String, String>(); //headerMap.put("Content-type", "text/xml"); headerMap.put("content-type", "application/json"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpPost(twoDimentionArray[0], headerMap, dataR); StrPost = this.processResponse(response).toString().trim(); */ } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to perform drag and drop "; } return "PASS"; } public String uploadThroughAutoIT() { /* @HELP @class: Keywords @method: dragAndDropByCoordinates (data) @parameter: None @notes: Makes POST request with attached data in form of file saved on HDD( in XMLForLT folder of the framework which contains JSON file) using apache apache library supported HttpRequest and HttpResponse. In dataColValue user must pass file path followed by URL e.g https://offers.dev.lendingtree.com/formstore/submit-lead.ashx,/XMLForLT/LT_02_Verify_POST_API_JSON.json @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Performing uploading :-> "); APP_LOGS.debug(": Performing uploading :-> "); highlight = false; try { /*data = data.trim(); String filePathFromInput = null; String twoDimentionArray[] = data.split(","); /*filePathFromInput = twoDimentionArray[1]; System.out.println(twoDimentionArray[0]+" "+twoDimentionArray[1]); *///String dataR = this.readFile(xmlForLT+filePathFromInput).toString(); /*Actions act=new Actions(driver); WebElement root=returnElementIfPresent(firstXpathKey); WebElement target=returnElementIfPresent(secondXpathKey); act.dragAndDrop(root, target).perform();*/ Runtime.getRuntime().exec("D://test.exe"); Thread.sleep(3000); //StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} "); /*HashMap<String, String> headerMap = new HashMap<String, String>(); //headerMap.put("Content-type", "text/xml"); headerMap.put("content-type", "application/json"); headerMap.put("Accept", "text/xml"); HttpResponse response = this.executeHttpPost(twoDimentionArray[0], headerMap, dataR); StrPost = this.processResponse(response).toString().trim(); */ } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to perform uploading :-> "; } return "PASS"; } public String CloseTheChildWindow() { /* @HELP @class: Keywords @method: dragAndDropByCoordinates (data) @parameter: None @notes: Makes POST request with attached data in form of file saved on HDD( in XMLForLT folder of the framework which contains JSON file) using apache apache library supported HttpRequest and HttpResponse. In dataColValue user must pass file path followed by URL e.g https://offers.dev.lendingtree.com/formstore/submit-lead.ashx,/XMLForLT/LT_02_Verify_POST_API_JSON.json @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ System.out.println(": Closing Child Window"); APP_LOGS.debug(": Closing Child Window"); highlight = false; try { String ParentWindow; String ChildWindow1; Set<String> set=driver.getWindowHandles(); Iterator<String> it=set.iterator(); ParentWindow=it.next(); ChildWindow1=it.next(); driver.switchTo().window(ChildWindow1); Thread.sleep(2000); driver.close(); driver.switchTo().window(ParentWindow); } catch (Exception e) { highlight = true; System.out.println(": "+e.getMessage()); return "FAIL - Not Able to close Child Window"; } return "PASS"; } public String uploadFile(String fileLocation) throws Exception { try { System.out.println(": Uploading a file from Specified location "+fileLocation); //System.out.println(": Uploading a file from Specified location "+fileLocation); APP_LOGS.debug(": Uploading a file from Specified location "+fileLocation); // setClipboardData(fileLocation); //native key strokes for CTRL, V and ENTER keys StringSelection stringSelection = new StringSelection(fileLocation); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_CONTROL); Thread.sleep(2000); robot.keyPress(KeyEvent.VK_V); Thread.sleep(2000); robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); Thread.sleep(2000); robot.keyPress(KeyEvent.VK_ENTER); Thread.sleep(2000); robot.keyRelease(KeyEvent.VK_ENTER); }catch(RuntimeException localRuntimeException){ highlight = true; System.out.println("Error in uploading a file from location: " + localRuntimeException.getMessage()); return "FAIL - Error in uploading a file"; //throw new AutomationException("Error in uploading a file from location: " + localRuntimeException.getMessage()); } return "PASS"; } public String saveFile() throws Exception { try { // Add the code for deleting file at the downloads location. /*File file = new File("C:\\Users\\dhruval.patel\\Downloads\\Contracts.pdf"); if(file.exists()){ //System.out.println("Inside file exists block"); file.delete(); }*/ Thread.sleep(2000); System.out.println(": saving a file "); //System.out.println(": Uploading a file from Specified location "+fileLocation); APP_LOGS.debug(": saving a file "); // setClipboardData(fileLocation); //native key strokes for CTRL, V and ENTER keys //StringSelection stringSelection = new StringSelection(fileLocation); //Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); Robot robot = new Robot(); /*robot.keyPress(KeyEvent.VK_CONTROL); Thread.sleep(2000); robot.keyPress(KeyEvent.VK_V); Thread.sleep(2000); robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); Thread.sleep(2000);*/ robot.keyPress(KeyEvent.VK_ENTER); //Thread.sleep(1000); robot.keyRelease(KeyEvent.VK_ENTER); }catch(RuntimeException exception){ highlight = true; System.out.println("Error in saving a file: " + exception.getMessage()); return "FAIL - Error in saving a file"; //throw new AutomationException("Error in uploading a file from location: " + localRuntimeException.getMessage()); } return "PASS"; } public String DeleteFile(String path) throws Exception { try { // Add the code for deleting file at the downloads location. File file = new File(path); if(file.exists()){ //System.out.println("Inside file exists block"); file.delete(); } Thread.sleep(2000); System.out.println(": Deleted a file "); //System.out.println(": Uploading a file from Specified location "+fileLocation); APP_LOGS.debug(": Deleted a file "); }catch(RuntimeException exception){ highlight = true; System.out.println("Error in deleting a file: " + exception.getMessage()); return "FAIL - Error in deleting a file"; //throw new AutomationException("Error in uploading a file from location: " + localRuntimeException.getMessage()); } return "PASS"; } public String VerifyFileDownload(String dataColValue) throws Exception { try { // Add the code for deleting file at the downloads location. dataColValue.replaceAll("\\\\", "/"); File file = new File(dataColValue); if(file.exists()){ //System.out.println("Inside file checking block"); System.out.println(": File is downloaded successfull at:-> "+dataColValue+ " path"); APP_LOGS.debug(": File is downloaded successfull at:-> "+dataColValue+ " path"); }else{ highlight = true; System.out.println(": File is not present at the location "); APP_LOGS.debug(": File is not present at the location "); return "FAIL - File is not present at the location "; } /*System.out.println(": saving a file "); //System.out.println(": Uploading a file from Specified location "+fileLocation); APP_LOGS.debug(": saving a file ");*/ }catch(Exception exception){ highlight = true; System.out.println("Error in saving a file: " + exception.getMessage()); return "FAIL - Error in saving a file"; //throw new AutomationException("Error in uploading a file from location: " + localRuntimeException.getMessage()); } return "PASS"; } public String SwitchToPdfWindowAndVerifyText(String firstXpathKey, String secondXpathKey, String expText) throws ParseException { /*@HELP @class: Keywords @method: SwitchToPdfWindowAndVerifyText () @parameter: String firstXpathKey, Optional=>String secondXpathKey, Optional=> String expText @notes: Switches to child window and Verifies the Actual Text as compared to the Expected Text. Verification can be performed on the same page or on different pages. User can perform two different webelement's text comparision by passing argument as objectKeySecond. @returns: ("PASS" or "FAIL" with Exception in case if method not got executed because of some runtime exception) to executeKeywords method @END */ //System.out.println("----------------------------------------------- : "+returnElementIfPresent(firstXpathKey).isDisplayed()); //System.out.println("----------------------##------------------------- : "+returnElementIfPresent(firstXpathKey).getText()); highlight = false; System.out.println(": Verifying " + firstXpathKey + " Text on the Page"); APP_LOGS.debug(": Verifying " + firstXpathKey + " Text on the Page"); String regex = "[0-9].[0-9]"; if (expText.matches(regex)) { NumberFormat nf = NumberFormat.getInstance(); Number number = nf.parse(expText); long lnputValue = number.longValue(); expText = String.valueOf(lnputValue); } if (expText.isEmpty()) { getTextOrValues.put(secondXpathKey, returnElementIfPresent(secondXpathKey).getText()); expText = getTextOrValues.get(secondXpathKey).toString(); } try { String ParentWindow; String ChildWindow1; Set<String> set=driver.getWindowHandles(); Iterator<String> it=set.iterator(); ParentWindow=it.next(); ChildWindow1=it.next(); driver.switchTo().window(ChildWindow1); Thread.sleep(2000); getTextOrValues.put(firstXpathKey, returnElementIfPresent(firstXpathKey).getText()); actText = getTextOrValues.get(firstXpathKey).toString(); actText=actText.trim(); expText=expText.trim(); if (actText.compareTo(expText) == 0) { System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); APP_LOGS.debug(": Actual is-> " + actText + " AND Expected is->" + expText); } else { globalExpText=expText; System.out.println(": Actual is-> " + actText + " AND Expected is-> " + expText); return "FAIL - Actual is-> " + actText + " AND Expected is->" + expText; } } catch (Exception e) { highlight = true; return "FAIL - Not able to read text--" + firstXpathKey; } return "PASS"; } public String VerifyElementIsEditable(String firstXpathKey) throws Exception { try { if(returnElementIfPresent(firstXpathKey).isEnabled()){ System.out.println(": Element is editable "+firstXpathKey); APP_LOGS.debug(": Element is editable "+firstXpathKey); highlight = true; }else{ System.out.println(": Element is not editable "+firstXpathKey); APP_LOGS.debug(": Element is not editable "+firstXpathKey); return "FAIL - Element is not editable "; } }catch(Exception exception){ highlight = true; System.out.println("Error in saving a file: " + exception.getMessage()); return "FAIL - Error in saving a file"; //throw new AutomationException("Error in uploading a file from location: " + localRuntimeException.getMessage()); } return "PASS"; } public String deleteFilesFromFolder(String filePath){ String directoryName = "C:\\Users\\dhruval.patel\\Downloads"; try{ File directory = new File(directoryName); if(directory.isDirectory()){ for(int i = 0;i <directory.list().length;i++){ File file = new File(directory+"\\"+directory.list()[i]); file.delete(); } }else{ System.out.println("Parent Directory has not anything."); } System.out.println("Successfully deleted directory : "+directoryName); APP_LOGS.debug("Successfully deleted directory : "+directoryName); }catch(Exception ex){ highlight = true; System.out.println("Error in deleting contents of the directory : "+directoryName+" with exception "+ex.getMessage()); return "FAIL - Error in deleting contents of the directory : "+directoryName; } return "PASS"; } public String verifyFileIsDownloaded() { String directoryName = "C:\\Users\\dhruval.patel\\Downloads"; try{ File directory = new File(directoryName); // System.out.println(directory.getName()); if (directory.isDirectory()) { for (int i = 0; i < directory.list().length; i++) { File file = new File(directory + "\\" + directory.list()[i]); if (file.getName().contains(".pdf") || file.getName().contains(".xml")) { System.out .println("Successfully executed with file name of : " + file.getName()); } else { System.out .println("directory has files with different file extention or folders."); } } } else { System.out.println("It is not a directory."); } System.out.println("Successfully verified files : "+directoryName); APP_LOGS.debug("Successfully verified files : "+directoryName); }catch(Exception ex){ highlight = true; System.out.println("Error in verifing contents of the directory : "+directoryName+" with exception "+ex.getMessage()); return "FAIL - Error in verifing contents of the directory : "+directoryName; } return "PASS"; } }
true