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
678747bcab5dec91c3f3a8198491b02fe84e82f0
Java
nuelbruno/Qmatic
/app/src/main/java/ae/qmatic/tacme/activity/LocationActivity.java
UTF-8
4,528
2.171875
2
[]
no_license
package ae.qmatic.tacme.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.List; import ae.qmatic.tacme.R; import ae.qmatic.tacme.adapter.BranchAdapter; import ae.qmatic.tacme.model.GetAllBranchesOnMap; import ae.qmatic.tacme.networkManager.ServiceManager; import ae.qmatic.tacme.utils.ActivityConstant; import ae.qmatic.tacme.utils.GPSTracker; import ae.qmatic.tacme.utils.HttpConstants; import ae.qmatic.tacme.utils.NetworkUtils; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by mdev3 on 8/10/16. */ public class LocationActivity extends AppCompatActivity { ListView listviewBranhes; GPSTracker gps; double currentLatitude ; double currentLongitude ; //List<ServiceBranchModel> webserviceBranchData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location_activity_layout); ////// access toolbar //////////////// Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar); TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title); mTitle.setText(getResources().getString(R.string.branches)); ImageView imgRightIcon = (ImageView)toolbarTop.findViewById(R.id.imgRightIcon); ////// set map icon and it's listner //////////////// imgRightIcon.setImageResource(R.drawable.ic_map_black); imgRightIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent(LocationActivity.this,MapActivity.class); /*webserviceBranchData = new ArrayList<ServiceNearByModel>(); mIntent.putParcelableArrayListExtra("branch_data", webserviceBranchData);*/ startActivity(mIntent); overridePendingTransition(R.anim.activity_in, R.anim.activity_out); finish(); } }); if (NetworkUtils.getInstance(this).isOnline()) { listviewBranhes = (ListView)findViewById(R.id.listviewBranhes); getLocationDataFromService(); //getCurrentLocation(); } else { Toast.makeText(LocationActivity.this, "Please connect to internet.", Toast.LENGTH_LONG).show(); } } /*private void getCurrentLocation(){ // create class object gps = new GPSTracker(LocationActivity.this); // check if GPS enabled if(gps.canGetLocation()){ currentLatitude = gps.getLatitude(); currentLongitude = gps.getLongitude(); getLocationDataFromService(); //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + currentLatitude + "\nLong: " + currentLongitude, Toast.LENGTH_LONG).show(); }else{ Toast.makeText(LocationActivity.this, "Please enable your device location service.", Toast.LENGTH_SHORT).show(); } }*/ public void getLocationDataFromService(){ final ActivityConstant activityConstant = new ActivityConstant(); activityConstant.showProgressDialog(LocationActivity.this, "Loading..."); ServiceManager webServiceManager = new ServiceManager(); //Log.d("Lat: " + currentLatitude, "Long: " + currentLongitude, null); Call<List<GetAllBranchesOnMap>> call = webServiceManager.apiService.getAllBranchesMapAndListing(HttpConstants.auth); call.enqueue(new Callback<List<GetAllBranchesOnMap>>() { @Override public void onResponse(Call<List<GetAllBranchesOnMap>> call, Response<List<GetAllBranchesOnMap>> response) { System.out.println("Response: " + response.body().toString()); listviewBranhes.setAdapter(new BranchAdapter(LocationActivity.this, response.body())); } @Override public void onFailure(Call<List<GetAllBranchesOnMap>> call, Throwable t) { activityConstant.hideProgressDialog(); Toast.makeText(LocationActivity.this, "An error occured in getting data.", Toast.LENGTH_SHORT).show(); } }); activityConstant.hideProgressDialog(); } }
true
96f1e8d7f71217af2685fa47f6e7f5fe2ec77e73
Java
NaruemonK/OOP_359211110018
/src/ooplab8/Trang.java
UTF-8
251
2.4375
2
[]
no_license
package ooplab8; public class Trang implements Campus{ @Override public void getCampusName() { System.out.println("Trang Campus."); } @Override public void getArae() { System.out.println("Sikoww Trang."); } }
true
63577a6473d04767ede09b52b72458cbff35ca3c
Java
carlosray/taco-cloud
/src/main/java/tacos/web/WebConfig.java
UTF-8
2,460
1.96875
2
[]
no_license
package tacos.web; import org.apache.activemq.artemis.jms.client.ActiveMQQueue; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.PagedModel; import org.springframework.hateoas.server.EntityLinks; import org.springframework.hateoas.server.RepresentationModelProcessor; import org.springframework.jms.support.converter.MappingJackson2MessageConverter; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import tacos.model.Order; import tacos.model.Taco; import javax.jms.Destination; import java.util.HashMap; import java.util.Map; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public Destination destination() { return new ActiveMQQueue("tacocloud.order.queue"); } @Bean public MessageConverter rabbitMessageConverter() { return new Jackson2JsonMessageConverter(); } @Bean public MappingJackson2MessageConverter jmsMessageConverter() { MappingJackson2MessageConverter messageConverter = new MappingJackson2MessageConverter(); messageConverter.setTypeIdPropertyName("_typeId"); Map<String, Class<?>> typeIdMapping = new HashMap<>(); typeIdMapping.put("order", Order.class); messageConverter.setTypeIdMappings(typeIdMapping); return messageConverter; } @Bean public RepresentationModelProcessor<PagedModel<EntityModel<Taco>>> tacoProcessor(EntityLinks links) { return new RepresentationModelProcessor<PagedModel<EntityModel<Taco>>>() { @Override public PagedModel<EntityModel<Taco>> process(PagedModel<EntityModel<Taco>> model) { model.add( links.linkFor(Taco.class) .slash("recent") .withRel("recents") ); return model; } }; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("home"); registry.addViewController("/login"); } }
true
f239134b7be13723452c44233307af64f40fd875
Java
GuChenChen/rjgl
/src/main/java/com/fykj/scaffold/evaluation/service/IQuotationRulesSecondPartyService.java
UTF-8
787
1.875
2
[]
no_license
package com.fykj.scaffold.evaluation.service; import com.baomidou.mybatisplus.extension.service.IService; import com.fykj.scaffold.evaluation.domain.entity.QuotationRulesSecondParty; import java.util.List; /** * <p> * 报价规则乙方服务类 * </p> * * @author feihj * @since 2020-03-31 */ public interface IQuotationRulesSecondPartyService extends IService<QuotationRulesSecondParty> { /** * 获取功能列表信息 * @param type 分类 * @return */ List<QuotationRulesSecondParty> findBySecondParty(String type); /** * 获取性能测试信息 * @param type * @return */ QuotationRulesSecondParty findBySecondPerformance(String type); QuotationRulesSecondParty findByTypeAndNum(String type,String num); }
true
98d4cf917a63c09210a7f474a35f662eeb81fae7
Java
lastaflute/lastaflute
/src/main/java/org/lastaflute/web/servlet/request/scoped/ScopedAttributeHolder.java
UTF-8
2,929
2.265625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.lastaflute.web.servlet.request.scoped; import org.dbflute.optional.OptionalThing; /** * @author jflute */ public interface ScopedAttributeHolder { // second argument 'attributeType' is to write like this: // getAttribute("sea", SeaBean.class).ifPresent(seaBean -> ...) /** * Get the attribute value of the scope by the key. * @param <ATTRIBUTE> The type of attribute object. * @param key The string key of attribute saved in the scope. (NotNull) * @param attributeType The generic type of the result for the attribute. (NotNull) * @return The optional attribute object for the key. (NotNull, EmptyAllowed: when not found) */ <ATTRIBUTE> OptionalThing<ATTRIBUTE> getAttribute(String key, Class<ATTRIBUTE> attributeType); /** * Set the attribute value to the scope by your original key. * @param key The key of the attribute. (NotNull) * @param value The attribute value added to the scope. (NotNull) */ void setAttribute(String key, Object value); /** * Remove the attribute value by the key. * @param key The string key of attribute saved in the scope. (NotNull) */ void removeAttribute(String key); // useful but dangerous so remove it at least in first release ///** // * Get the attribute value of the scope by the value's type. // * @param <ATTRIBUTE> The type of attribute object. // * @param typeKey The type key of attribute saved in the scope. (NotNull) // * @return The optional attribute object for the type. (NotNull, EmptyAllowed: when not found) // */ //<ATTRIBUTE> OptionalThing<ATTRIBUTE> getAttribute(Class<ATTRIBUTE> typeKey); ///** // * Set the attribute value to the scope by the value's type. <br> // * You should not set string object to suppress mistake. <br> // * However you should not use this when the object might be extended. <br> // * (Then the key is changed to sub-class type so you might have mistakes...) // * @param value The attribute value added to the scope. (NotNull) // */ //void setAttribute(Object value); ///** // * Remove the attribute value by the value's type. // * @param type The type of removed object. (NotNull) // */ //void removeAttribute(Class<?> type); }
true
6c8f4e3eabf6cb9a4d2b0e7c25d200631a695ecf
Java
mba811/osiam
/src/main/java/org/osiam/resources/controller/GroupController.java
UTF-8
6,148
1.898438
2
[ "MIT" ]
permissive
/* * Copyright (C) 2013 tarent AG * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.osiam.resources.controller; import java.io.IOException; import java.net.URI; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osiam.resources.helper.AttributesRemovalHelper; import org.osiam.resources.helper.JsonInputValidator; import org.osiam.resources.helper.RequestParamHelper; import org.osiam.resources.provisioning.SCIMGroupProvisioning; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.SCIMSearchResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriTemplate; /** * HTTP Api for groups. You can create, delete, replace, update and search groups. */ @Controller @RequestMapping(value = "/Groups") @Transactional public class GroupController { @Autowired private SCIMGroupProvisioning scimGroupProvisioning; @Autowired private JsonInputValidator jsonInputValidator; private RequestParamHelper requestParamHelper = new RequestParamHelper(); private AttributesRemovalHelper attributesRemovalHelper = new AttributesRemovalHelper(); @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Group create(HttpServletRequest request, HttpServletResponse response) throws IOException { Group group = jsonInputValidator.validateJsonGroup(request); Group createdGroup = scimGroupProvisioning.create(group); setLocationUriWithNewId(request, response, createdGroup.getId()); return createdGroup; } private void setLocationUriWithNewId(HttpServletRequest request, HttpServletResponse response, String id) { String requestUrl = request.getRequestURL().toString(); URI uri = new UriTemplate("{requestUrl}{internalId}").expand(requestUrl + "/", id); response.setHeader("Location", uri.toASCIIString()); } private void setLocation(HttpServletRequest request, HttpServletResponse response) { String requestUrl = request.getRequestURL().toString(); response.setHeader("Location", requestUrl); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public Group get(@PathVariable final String id) { return scimGroupProvisioning.getById(id); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.OK) public void delete(@PathVariable final String id) { scimGroupProvisioning.delete(id); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public Group replace(@PathVariable final String id, HttpServletRequest request, HttpServletResponse response) throws IOException { Group group = jsonInputValidator.validateJsonGroup(request); Group createdGroup = scimGroupProvisioning.replace(id, group); setLocation(request, response); return createdGroup; } @RequestMapping(value = "/{id}", method = RequestMethod.PATCH) @ResponseStatus(HttpStatus.OK) @ResponseBody public Group update(@PathVariable final String id, HttpServletRequest request, HttpServletResponse response) throws IOException { Group group = jsonInputValidator.validateJsonGroup(request); Group createdGroup = scimGroupProvisioning.update(id, group); setLocation(request, response); return createdGroup; } @RequestMapping(method = RequestMethod.GET) @ResponseBody public SCIMSearchResult<Group> searchWithGet(HttpServletRequest request) { Map<String, Object> parameterMap = requestParamHelper.getRequestParameterValues(request); SCIMSearchResult<Group> scimSearchResult = scimGroupProvisioning.search((String) parameterMap.get("filter"), (String) parameterMap.get("sortBy"), (String) parameterMap.get("sortOrder"), (int) parameterMap.get("count"), (int) parameterMap.get("startIndex")); return attributesRemovalHelper.removeSpecifiedAttributes(scimSearchResult, parameterMap); } @RequestMapping(value = "/.search", method = RequestMethod.POST) @ResponseBody public SCIMSearchResult<Group> searchWithPost(HttpServletRequest request) { Map<String, Object> parameterMap = requestParamHelper.getRequestParameterValues(request); SCIMSearchResult<Group> scimSearchResult = scimGroupProvisioning.search((String) parameterMap.get("filter"), (String) parameterMap.get("sortBy"), (String) parameterMap.get("sortOrder"), (int) parameterMap.get("count"), (int) parameterMap.get("startIndex")); return attributesRemovalHelper.removeSpecifiedAttributes(scimSearchResult, parameterMap); } }
true
4f4a56bf9ba3d5f0930c38a939f2738e741e9150
Java
pauljabernathy/Toolbox
/src/toolbox/data/AnalyzerServlet.java
UTF-8
7,927
2.703125
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package toolbox.data; import javax.servlet.http.*; import java.io.*; import javax.servlet.ServletException; import javax.servlet.RequestDispatcher; import toolbox.Constants; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import java.util.Observer; import java.util.Observable; import java.util.regex.*; /** * * @author paul */ @WebServlet("/AnalyzerServlet") @MultipartConfig public class AnalyzerServlet extends HttpServlet implements Observer { private static final String DEFAULT_FILE_NAME = "thefile.csv"; private PrintWriter writer; protected static final String ENTER_COLUMNS_MESSAGE = "Please enter a list of columns"; protected static final String INVALID_COLUMNS_FORMAT_MESSAGE = "Please enter columns formated as numbers separated by commas"; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { this.writer = response.getWriter(); writer.println("<html><head><title>Analyzer Servlet</title><script src=\"ga.js\"></script></head><body>"); Analyzer a = new Analyzer(); //a.addWriterAppender(writer); a.addObserver(this); a.setEndLine("<br>\n"); String fileName = DEFAULT_FILE_NAME; String columnStr = ""; //fileName = "thefile.csv"; File dir = new File(getServletContext().getRealPath("")); if(request.getSession().getAttribute("fileName") != null) { fileName = (String)request.getSession().getAttribute("fileName"); fileName = getServletContext().getRealPath("") + File.separator + fileName; //a.analyzeFile(fileName, new int[] { 1, 2, 3, 4 }, ","); } else { writer.println("<br>did not receive a filename, using default: " + fileName); } int[] columns = null; if(request.getParameter("columns") != null) { try { columns = getColumns(request.getParameter("columns")); a.analyzeFile(fileName, columns, ","); } catch(Exception e) { writer.println("<p>" + e.getMessage() + "</p>"); } } //a.analyzeFile(fileName, new int[] { 1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13}, ","); writer.println("<br><br>Known issues:"); writer.println("<ul>"); writer.println("<li>when column 0 is entered, the list of columns is not computed correctly and the mutual information comparisons do not take place</li>"); writer.println("</ul>"); //RequestDispatcher dispatcher = request.getRequestDispatcher("footer.jsp"); //dispatcher.include(request, response); writer.println("<object name=\"footer\" type=\"text/html\" data=\"footer.html\"></object>"); writer.println("</body></html>"); } //TODO: remove spaces in the middle of the string so it is more user friendly protected int[] getColumns(String columnStr) throws Exception { if(columnStr == null || columnStr.length() == 0) { throw new Exception(AnalyzerServlet.ENTER_COLUMNS_MESSAGE); } columnStr = columnStr.trim(); if(columnStr.startsWith(",")) { if(columnStr.length() == 1) { throw new Exception(AnalyzerServlet.INVALID_COLUMNS_FORMAT_MESSAGE); } else { //remove the , at the beginning columnStr = columnStr.substring(1); } } if(columnStr.endsWith(",")) { if(columnStr.length() == 1) { throw new Exception(AnalyzerServlet.INVALID_COLUMNS_FORMAT_MESSAGE); } else { //remove the , at the end columnStr = columnStr.substring(0, columnStr.length() - 1); } } Pattern p = Pattern.compile("[^\\d^,]"); Matcher m = p.matcher(columnStr); if(m.find()) { //found a character that is not a number or comma //System.out.println(columnStr); //System.out.println(m.start() + " " + m.group()); throw new Exception(AnalyzerServlet.INVALID_COLUMNS_FORMAT_MESSAGE); } String[] nums = columnStr.split(","); if(nums.length < 1) { //empty list of numbers throw new Exception(AnalyzerServlet.INVALID_COLUMNS_FORMAT_MESSAGE); } int[] result = new int[nums.length]; for(int i = 0; i < nums.length; i++) { result[i] = Integer.parseInt(nums[i]); } return result; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); System.out.println("demo"); if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here //PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //ServletFileUpload upload = new ServletFileUpload(factory); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("")+ File.separator;// + UPLOAD_DIRECTORY; //writer.println("<br>uploadPath = " + uploadPath);writer.flush(); // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } String fileName = DEFAULT_FILE_NAME; try { // parses the request's content to extract file data //System.out.println(uploadPath); Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file"> //writer.println("<br>filePart.getName() = " + filePart.getName()); //filePart.getName() gives the name of the file input item from the form page //writer.println("<br>filePart.getSubmittedFileName() = " + filePart.getSubmittedFileName()); //getSubmittedFileName() gives the real file name //writer.println("<br>fileName = " + fileName); String filePath = uploadPath + File.separator + fileName; //use the generic file name so that new files overwrite the old so that we don't proliferate files on the server //writer.println("<br>file will be " + filePath);writer.flush(); filePart.write(filePath); request.setAttribute("message","Upload has been done successfully!"); //writer.println("demo Success"); } catch (Exception ex) { request.setAttribute("message","There was an error: " + ex.getMessage()); writer.println("demo Fail: " + ex.getMessage() ); } request.getSession().setAttribute("fileName", fileName); doGet(request, response); } public void update(Observable o, Object arg) { if(o instanceof Analyzer) { this.writer.println("<br>" + arg); this.writer.flush(); } } }
true
e88b8e8c4eb3dd2fa747e76d7a840ac85b077da4
Java
Ulicong/optimus-zeus
/optimus-model/optimus-model-api/src/main/java/com/optimus/module/user/web.rpc/UserInfoRpc.java
UTF-8
579
1.828125
2
[]
no_license
package com.optimus.module.user.web.rpc; import com.optimus.module.user.dal.entity.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** * Created by li.huan * Create Date 2017-06-20 16:17 */ @Controller public class UserInfoRpc { @Autowired private UserInfoAO userInfoAO; /** * 查询单个用户信息 * * @param user_id 用户ID * @return */ public UserInfo query_user_info_by_id(Integer user_id) { return userInfoAO.queryById(user_id); } }
true
0730fb30741882adcd3d0490721887ae654d2e19
Java
thaond/nsscttdt
/src/ext-lltnxp/ext-service/src/com/sgs/portlet/message_note/service/PmlMessageLocalService.java
UTF-8
2,968
1.890625
2
[]
no_license
package com.sgs.portlet.message_note.service; /** * <a href="PmlMessageLocalService.java.html"><b><i>View Source</i></b></a> * * <p> * ServiceBuilder generated this class. Modifications in this class will be * overwritten the next time is generated. * </p> * * <p> * This interface defines the service. The default implementation is * <code>com.sgs.portlet.message_note.service.impl.PmlMessageLocalServiceImpl</code>. * Modify methods in that class and rerun ServiceBuilder to populate this class * and all other generated classes. * </p> * * <p> * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM. * </p> * * @author Brian Wing Shun Chan * * @see com.sgs.portlet.message_note.service.PmlMessageLocalServiceUtil * */ public interface PmlMessageLocalService { public com.sgs.portlet.message_note.model.PmlMessage addPmlMessage( com.sgs.portlet.message_note.model.PmlMessage pmlMessage) throws com.liferay.portal.SystemException; public com.sgs.portlet.message_note.model.PmlMessage createPmlMessage( long messageId); public void deletePmlMessage(long messageId) throws com.liferay.portal.SystemException, com.liferay.portal.PortalException; public void deletePmlMessage( com.sgs.portlet.message_note.model.PmlMessage pmlMessage) throws com.liferay.portal.SystemException; public java.util.List<Object> dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery) throws com.liferay.portal.SystemException; public java.util.List<Object> dynamicQuery( com.liferay.portal.kernel.dao.orm.DynamicQuery dynamicQuery, int start, int end) throws com.liferay.portal.SystemException; public com.sgs.portlet.message_note.model.PmlMessage getPmlMessage( long messageId) throws com.liferay.portal.SystemException, com.liferay.portal.PortalException; public java.util.List<com.sgs.portlet.message_note.model.PmlMessage> getPmlMessages( int start, int end) throws com.liferay.portal.SystemException; public int getPmlMessagesCount() throws com.liferay.portal.SystemException; public com.sgs.portlet.message_note.model.PmlMessage updatePmlMessage( com.sgs.portlet.message_note.model.PmlMessage pmlMessage) throws com.liferay.portal.SystemException; public void deletePmlMessageList( java.util.List<com.sgs.portlet.message_note.model.PmlMessage> messageList) throws java.lang.Exception; public int getTotalDocumentByUser(java.util.List<Long> fromUserList, long toUserId) throws java.lang.Exception; public java.util.List<com.sgs.portlet.message_note.model.PmlMessage> getDocumentListByUser( long fromUserId, long toUserId, java.lang.Class clazz) throws java.lang.Exception; }
true
9c625ac8a1d6cde99fbe28157170e837dcd31389
Java
azabost/slf4android
/app/src/test/java/pl/brightinventions/slf4android/RobolectricTestRunner.java
UTF-8
832
2.109375
2
[ "MIT" ]
permissive
package pl.brightinventions.slf4android; import org.junit.runners.model.InitializationError; public class RobolectricTestRunner extends org.robolectric.RobolectricTestRunner { public RobolectricTestRunner(Class<?> testClass) throws InitializationError { super(testClass); } // // @Override // protected AndroidManifest getAppManifest(Config config) { // String manifestPath = "main/AndroidManifest.xml"; // String resPath = "main/res"; // AndroidManifest manifest = new AndroidManifest(Fs.fileFromPath(manifestPath), Fs.fileFromPath(resPath)) { // @Override // public int getTargetSdkVersion() { // return 18; // } // }; // manifest.setPackageName("pl.brightinventions.slf4android"); // return manifest; // } // }
true
fcf53d87f1b6f79b2ceff278c88d19907df154db
Java
renanvernabrogliato/BuscaV1
/app/src/main/java/br/usjt/ftce/desmob/clientev1/ViewHolder.java
UTF-8
1,039
2.25
2
[]
no_license
package br.usjt.ftce.desmob.clientev1; import android.widget.ImageView; import android.widget.TextView; /** * Created by arqdsis on 24/03/2017. */ public class ViewHolder { private ImageView fotoCliente; private TextView nameCliente, detalheCliente; public ViewHolder(ImageView fotoCliente, TextView nameCliente, TextView detalheCliente) { this.fotoCliente = fotoCliente; this.nameCliente = nameCliente; this.detalheCliente = detalheCliente; } public ImageView getFotoCliente() { return fotoCliente; } public void setFotoCliente(ImageView fotoCliente) { this.fotoCliente = fotoCliente; } public TextView getNameCliente() { return nameCliente; } public void setNameCliente(TextView nomeCliente) { this.nameCliente = nomeCliente; } public TextView getDetalheCliente() { return detalheCliente; } public void setDetalheCliente(TextView detalheCliente) { this.detalheCliente = detalheCliente; } }
true
733aeb0b8142a2e4cfcf068aa72e7ca3dcb9f0c4
Java
quzhaomei/admin
/src/com/rycf/gjb/annotation/MethodCache.java
GB18030
720
2.515625
3
[]
no_license
package com.rycf.gjb.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 󷽷ǩ * @author qzm * @since 2015-5-13 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MethodCache { /** * ĹΪreadʱΪ棬ΪupdataʱΪ» * @return */ String type() default MethodCache.CACHE_READ; /** * * @return */ String className(); public static final String CACHE_READ="read";// public static final String CACHE_UPDATE="update";// }
true
af932f6483ad540b3358e69ece57a866e9df8dd6
Java
svn2github/icefaces
/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/menu/MenuEvents.java
UTF-8
2,857
1.992188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2004-2013 ICEsoft Technologies Canada Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.icefaces.samples.showcase.example.ace.menu; import org.icefaces.samples.showcase.metadata.annotation.*; import org.icefaces.samples.showcase.metadata.context.ComponentExampleImpl; import javax.annotation.PostConstruct; import javax.faces.bean.CustomScoped; import javax.faces.bean.ManagedBean; import javax.faces.event.ActionEvent; import java.io.Serializable; @ComponentExample( parent = MenuBean.BEAN_NAME, title = "example.ace.menu.events.title", description = "example.ace.menu.events.description", example = "/resources/examples/ace/menu/menuEvents.xhtml" ) @ExampleResources( resources ={ // xhtml @ExampleResource(type = ResourceType.xhtml, title="menuEvents.xhtml", resource = "/resources/examples/ace/menu/menuEvents.xhtml"), // Java Source @ExampleResource(type = ResourceType.java, title="MenuEvents.java", resource = "/WEB-INF/classes/org/icefaces/samples/showcase"+ "/example/ace/menu/MenuEvents.java") } ) @ManagedBean(name= MenuEvents.BEAN_NAME) @CustomScoped(value = "#{window}") public class MenuEvents extends ComponentExampleImpl<MenuEvents> implements Serializable { public static final String BEAN_NAME = "menuEvents"; private String message; private String currentColor = "black"; public MenuEvents() { super(MenuEvents.class); } @PostConstruct public void initMetaData() { super.initMetaData(); } public String getMessage() { return message; } public String getCurrentColor() { return currentColor; } public void setMessage(String message) { this.message = message; } public void setCurrentColor(String currentColor) { this.currentColor = currentColor; } public String ourAction() { message = "Fired Action."; return null; } public void ourActionListener(ActionEvent event) { message = "Fired Action Listener."; } public void applyColor(ActionEvent event) { currentColor = event.getComponent() != null ? event.getComponent().getId() : "black"; } }
true
94e1f36245fb60c791f200a4539ca16576eff86c
Java
three-stacks/packerapi
/src/main/java/io/threestacks/packerapi/agenda/AgendaService.java
UTF-8
1,169
2.1875
2
[]
no_license
package io.threestacks.packerapi.agenda; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class AgendaService { @Autowired private AgendaRepository agendaRepository; public List<Agenda> getAllAgendas(){ List<Agenda> agendas = new ArrayList<>(); agendaRepository.findAll().forEach(agendas::add); return agendas; } public List<Agenda> getUserAgendas(long userId){ List<Agenda> agendas = new ArrayList<>(); agendaRepository.findByUserId(userId).forEach(agendas::add); return agendas; } public Agenda getAgenda(long id) { return agendaRepository.findOne(id); } public Agenda addAgenda(Agenda agenda){ agendaRepository.save(agenda); return agenda; } public Agenda updateAgenda(long id, Agenda agenda){ Agenda agendaFound = agendaRepository.findOne(id); agendaRepository.save(agenda); return agendaFound; } public void deleteAgenda(long id){ agendaRepository.delete(id); } }
true
d9e7eda4eb0522fd83897c4c0825e5a7954967ed
Java
diegoferose/reservaTennis
/comun/comun-dominio/src/main/java/com/ceiba/dominio/excepcion/ExcepcionReservaActiva.java
UTF-8
238
2.125
2
[]
no_license
package com.ceiba.dominio.excepcion; public class ExcepcionReservaActiva extends RuntimeException{ private static final long serialVersionUID = 1L; public ExcepcionReservaActiva(String mensaje) { super(mensaje); } }
true
04f79add2aac459cf82a504c78dd34354fed5cd3
Java
XC-LGY/maven_myBatisSpringSpringMVC6
/src/main/java/com/bf/mybatis/springboot/Application.java
UTF-8
1,119
2.328125
2
[]
no_license
package com.bf.mybatis.springboot; import java.util.List; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.bf.mybatis.springboot.mapper.CountryMapper; import com.bf.mybatis.springboot.model.Country; /** * Spring Boot 启动类 * @author Administrator */ @SpringBootApplication @MapperScan(value = {"com.bf.mybatis.springboot.mapper", "tk.mybatis.simple.mapper"},nameGenerator = MapperNameGenerator.class) public class Application implements CommandLineRunner{ @Autowired private CountryMapper countryMapper; @Override public void run(String... arg0) throws Exception { List<Country> countryList = countryMapper.selectAll(); if(countryList.size() > 0) { System.err.println("------------------------------------>" + countryList.get(0).getCountryname()); } } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
true
1f3c1e4c884d39b7a8a7ee21b8bf4750f2fe5b5b
Java
Sunbefore/xiyou-shop
/xiyou-shop-product/src/main/java/com/xiyou/product/service/RedisService.java
UTF-8
1,054
2.140625
2
[]
no_license
package com.xiyou.product.service; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.Set; @FeignClient(value = "xiyou-shop-redisTest") public interface RedisService { /** * 根据key得到value * @param key * @return */ @RequestMapping(value = "/getKey/{key}",method = RequestMethod.GET) public String getKey(@PathVariable("key") String key); /** * 将key,value存入redis中 * @param key * @param value */ @RequestMapping(value = "/setKey/{key}/{value}",method = RequestMethod.GET) public void setKey(@PathVariable("key") String key, @PathVariable("value") String value); /** * 得到所有的key对应的value * @return */ @RequestMapping(value = "/getAllProductKeys",method = RequestMethod.POST) public Set<String> getAllProductKeys(); }
true
6cfbdc686dbb6d36a6258cdb0c28f998a70cad7c
Java
richardtqd/mariaweb
/src/java/pe/marista/sigma/managedBean/ProcesoFilesMB.java
WINDOWS-1250
56,272
1.71875
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 pe.marista.sigma.managedBean; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import org.primefaces.context.RequestContext; import org.primefaces.event.RowEditEvent; import org.primefaces.event.SelectEvent; import pe.marista.sigma.MaristaConstantes; import pe.marista.sigma.bean.CodigoBean; import pe.marista.sigma.bean.EntidadBean; import pe.marista.sigma.bean.ProcesoFilesBean; import pe.marista.sigma.bean.TipoCodigoBean; import pe.marista.sigma.bean.UsuarioBean; import pe.marista.sigma.factory.BeanFactory; import pe.marista.sigma.service.CodigoService; import pe.marista.sigma.service.EntidadService; import pe.marista.sigma.service.ProcesoFilesService; import pe.marista.sigma.util.GLTLog; import pe.marista.sigma.util.MaristaUtils; import pe.marista.sigma.util.MensajePrime; import javax.faces.context.FacesContext; import pe.marista.sigma.bean.CajaGenBean; import pe.marista.sigma.bean.CuentasPorCobrarBean; import pe.marista.sigma.service.CajaGenService; import pe.marista.sigma.service.ProcesoFinalService; /** * * @author MS002 */ public class ProcesoFilesMB implements Serializable { /** * Creates a new instance of ProcesoFilesMB */ @PostConstruct public void ProcesoFilesMB() { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); obtenerProcesoFiles(); //Obteniendo Lista de Entidades EntidadService entidadService = BeanFactory.getEntidadService(); CajaGenBean cajaGenBean = new CajaGenBean(); getListaEntidadBean(); cajaGenBean.setAyudaBanco(true); cajaGenBean.getUniNeg().setUniNeg(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); // listaEntidadBean = entidadService.obtenerFlgFinanciero(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); CajaGenService cajaGenService = BeanFactory.getCajaGenService(); listaEntidadBean = cajaGenService.obtenerBancosDeposito(cajaGenBean); //Obteniendo Tipo de Archivos CodigoService codigoService = BeanFactory.getCodigoService(); getListaTipoArchivo(); listaTipoArchivo = codigoService.obtenerPorTipo(new TipoCodigoBean(MaristaConstantes.Tip_Archivo)); getListaTipoDefecto(); listaTipoDefecto = codigoService.obtenerPorTipo(new TipoCodigoBean(MaristaConstantes.TIP_Default)); //Obteniendo Tipos de Files obtenerCodigoTipoFile(); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //ProcesosFiles private List<ProcesoFilesBean> listaProcesoFilesBean; private List<ProcesoFilesBean> listaProcesoFilesDetBean; private List<ProcesoFilesBean> listaProcesoFilesIntDetBean; private List<ProcesoFilesBean> listaProcesoFilesDetDetBean; private ProcesoFilesBean procesoFilesBean; private ProcesoFilesBean procesoFilesDetaBean; private List<EntidadBean> listaEntidadBean; private List<CodigoBean> listaTipoFile; private List<CodigoBean> listaTipoDefecto; private String nombreFilePadre; private List<CodigoBean> listaTipoArchivo; //Listas de Edicion private List<ProcesoFilesBean> listaCabecera; private List<ProcesoFilesBean> listaDetalle; private List<ProcesoFilesBean> listaIntermedio; private ProcesoFilesBean fileDetaBean; //Ayudas private Integer valDel; private Integer flgPro; private Integer idpadre; private String ruc; private String nombre; public List<ProcesoFilesBean> getListaProcesoFilesBean() { if (listaProcesoFilesBean == null) { listaProcesoFilesBean = new ArrayList<>(); } return listaProcesoFilesBean; } public void setListaProcesoFilesBean(List<ProcesoFilesBean> listaProcesoFilesBean) { this.listaProcesoFilesBean = listaProcesoFilesBean; } public ProcesoFilesBean getProcesoFilesBean() { if (procesoFilesBean == null) { procesoFilesBean = new ProcesoFilesBean(); } return procesoFilesBean; } public void setProcesoFilesBean(ProcesoFilesBean procesoFilesBean) { this.procesoFilesBean = procesoFilesBean; } public List<EntidadBean> getListaEntidadBean() { if (listaEntidadBean == null) { listaEntidadBean = new ArrayList<>(); } return listaEntidadBean; } public void setListaEntidadBean(List<EntidadBean> listaEntidadBean) { this.listaEntidadBean = listaEntidadBean; } public ProcesoFilesBean getProcesoFilesDetaBean() { if (procesoFilesDetaBean == null) { procesoFilesDetaBean = new ProcesoFilesBean(); } return procesoFilesDetaBean; } public void setProcesoFilesDetaBean(ProcesoFilesBean procesoFilesDetaBean) { this.procesoFilesDetaBean = procesoFilesDetaBean; } public List<ProcesoFilesBean> getListaProcesoFilesDetBean() { if (listaProcesoFilesDetBean == null) { listaProcesoFilesDetBean = new ArrayList<>(); } return listaProcesoFilesDetBean; } public void setListaProcesoFilesDetBean(List<ProcesoFilesBean> listaProcesoFilesDetBean) { this.listaProcesoFilesDetBean = listaProcesoFilesDetBean; } public String getNombreFilePadre() { return nombreFilePadre; } public void setNombreFilePadre(String nombreFilePadre) { this.nombreFilePadre = nombreFilePadre; } public List<CodigoBean> getListaTipoFile() { if (listaTipoFile == null) { listaTipoFile = new ArrayList<>(); } return listaTipoFile; } public void setListaTipoFile(List<CodigoBean> listaTipoFile) { this.listaTipoFile = listaTipoFile; } public List<ProcesoFilesBean> getListaProcesoFilesDetDetBean() { if (listaProcesoFilesDetDetBean == null) { listaProcesoFilesDetDetBean = new ArrayList<>(); } return listaProcesoFilesDetDetBean; } public void setListaProcesoFilesDetDetBean(List<ProcesoFilesBean> listaProcesoFilesDetDetBean) { this.listaProcesoFilesDetDetBean = listaProcesoFilesDetDetBean; } public List<ProcesoFilesBean> getListaCabecera() { if (listaCabecera == null) { listaCabecera = new ArrayList<>(); } return listaCabecera; } public void setListaCabecera(List<ProcesoFilesBean> listaCabecera) { this.listaCabecera = listaCabecera; } public List<ProcesoFilesBean> getListaDetalle() { if (listaDetalle == null) { listaDetalle = new ArrayList<>(); } return listaDetalle; } public void setListaDetalle(List<ProcesoFilesBean> listaDetalle) { this.listaDetalle = listaDetalle; } public Integer getValDel() { return valDel; } public void setValDel(Integer valDel) { this.valDel = valDel; } public ProcesoFilesBean getFileDetaBean() { if (fileDetaBean == null) { fileDetaBean = new ProcesoFilesBean(); } return fileDetaBean; } public void setFileDetaBean(ProcesoFilesBean fileDetaBean) { this.fileDetaBean = fileDetaBean; } public Integer getFlgPro() { return flgPro; } public void setFlgPro(Integer flgPro) { this.flgPro = flgPro; } public List<CodigoBean> getListaTipoArchivo() { if (listaTipoArchivo == null) { listaTipoArchivo = new ArrayList<>(); } return listaTipoArchivo; } public void setListaTipoArchivo(List<CodigoBean> listaTipoArchivo) { this.listaTipoArchivo = listaTipoArchivo; } public Integer getIdpadre() { return idpadre; } public void setIdpadre(Integer idpadre) { this.idpadre = idpadre; } public String getRuc() { return ruc; } public void setRuc(String ruc) { this.ruc = ruc; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public List<ProcesoFilesBean> getListaProcesoFilesIntDetBean() { if (listaProcesoFilesIntDetBean == null) { listaProcesoFilesIntDetBean = new ArrayList<>(); } return listaProcesoFilesIntDetBean; } public void setListaProcesoFilesIntDetBean(List<ProcesoFilesBean> listaProcesoFilesIntDetBean) { this.listaProcesoFilesIntDetBean = listaProcesoFilesIntDetBean; } public List<ProcesoFilesBean> getListaIntermedio() { if (listaIntermedio == null) { listaIntermedio = new ArrayList<>(); } return listaIntermedio; } public void setListaIntermedio(List<ProcesoFilesBean> listaIntermedio) { this.listaIntermedio = listaIntermedio; } public List<CodigoBean> getListaTipoDefecto() { if (listaTipoDefecto == null) { listaTipoDefecto = new ArrayList<>(); } return listaTipoDefecto; } public void setListaTipoDefecto(List<CodigoBean> listaTipoDefecto) { this.listaTipoDefecto = listaTipoDefecto; } //Proceso File do public void obtenerProcesoFiles() { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); listaProcesoFilesBean = procesoFilesService.obtenerProcesosFiles(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerCodigoTipoFile() { try { CodigoService codigoService = BeanFactory.getCodigoService(); listaTipoFile = codigoService.obtenerPorTipo(new TipoCodigoBean(MaristaConstantes.Tip_File)); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void limpiarProcesoFiles() { try { procesoFilesBean = new ProcesoFilesBean(); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void limpiarFilesDeta() { try { procesoFilesDetaBean = new ProcesoFilesBean(); procesoFilesDetaBean.setIdFilePadre(procesoFilesBean.getIdFile()); procesoFilesDetaBean.getEntidadBean().setRuc(procesoFilesBean.getEntidadBean().getRuc()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public String insertarProcesosFiles() { String pagina = null; try { if (pagina == null) { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); procesoFilesService.insertarProcesosFilesBanco(procesoFilesBean); listaProcesoFilesBean = procesoFilesService.obtenerProcesosFiles(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); limpiarFilesDeta(); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } return pagina; } public String modificarProcesosFiles() { String pagina = null; try { if (pagina == null) { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); procesoFilesBean.setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarSuperFile(procesoFilesBean); listaProcesoFilesBean = procesoFilesService.obtenerProcesosFiles(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); limpiarFilesDeta(); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } return pagina; } public void guardarFiles() { try { if (procesoFilesBean.getIdFile() != null) { modificarProcesosFiles(); } else { insertarProcesosFiles(); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerSuperFile(SelectEvent event) { try { procesoFilesBean = (ProcesoFilesBean) event.getObject(); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); procesoFilesBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerResource(Integer resouce) { try { procesoFilesDetaBean = new ProcesoFilesBean(); flgPro = resouce; obtenerDetallesFile(procesoFilesBean, resouce); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerDetallesFile(Object object, Integer flgPro) { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); if (flgPro.equals(0)) { procesoFilesBean = (ProcesoFilesBean) object; idpadre = procesoFilesBean.getIdFile(); ruc = procesoFilesBean.getEntidadBean().getRuc(); nombre = procesoFilesBean.getNombre(); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); } if (flgPro.equals(1)) { procesoFilesDetaBean = new ProcesoFilesBean(); procesoFilesDetaBean.setIdFilePadre(idpadre); procesoFilesDetaBean.getEntidadBean().setRuc(ruc); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); } if (flgPro.equals(2)) { procesoFilesDetaBean = new ProcesoFilesBean(); procesoFilesDetaBean.setIdFilePadre(idpadre); procesoFilesDetaBean.getEntidadBean().setRuc(ruc); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idpadre, flgPro); } CodigoService codigoService = BeanFactory.getCodigoService(); CodigoBean codigoTipoFileCab = new CodigoBean(); codigoTipoFileCab = codigoService.obtenerPorCodigo(new CodigoBean(20001, "Cabecera", new TipoCodigoBean(MaristaConstantes.file_Cabecera))); CodigoBean codigoTipoFileDet = new CodigoBean(); codigoTipoFileDet = codigoService.obtenerPorCodigo(new CodigoBean(20002, "Detalle", new TipoCodigoBean(MaristaConstantes.file_Detalle))); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerSuper(Object object) { try { procesoFilesBean = (ProcesoFilesBean) object; ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); procesoFilesBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public String eliminarFile() { String pagina = null; try { if (pagina == null) { ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); procesoFilesService.eliminarProcesosFile(procesoFilesBean); listaProcesoFilesBean = procesoFilesService.obtenerProcesosFiles(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } return pagina; } //Detalles public void insertarProcesosFilesDeta() { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); Integer posFin = 0, posicion = 0, posini = 0, posfin = 0; posFin = procesoFilesService.obtenerMaxPosFin(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getEntidadBean().getRuc()); // if (posFin > procesoFilesDetaBean.getPosicionIni()) { // FacesMessage msg = new FacesMessage("Ingresar numero mayor al ltimo registro ", null); // FacesContext.getCurrentInstance().addMessage(null, msg); // } else { posFin = procesoFilesService.obtenerMaxPosFin(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getEntidadBean().getRuc()); posicion = procesoFilesService.obtenerUltimaPosicion(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesDetaBean.getTipoFile().getIdCodigo(), procesoFilesBean.getEntidadBean().getRuc(), flgPro); posini = posicion + 1; posfin = (procesoFilesDetaBean.getLongitud() - 1) + posini; if (procesoFilesDetaBean.getLongitud() != 0 && procesoFilesBean.getLongitud() != null) { procesoFilesDetaBean.setPosicionIni(posini); procesoFilesDetaBean.setPosicionFin(posfin); procesoFilesDetaBean.setFlgProceso(flgPro); procesoFilesDetaBean.getTipoDato().setIdCodigo(procesoFilesDetaBean.getDato()); procesoFilesDetaBean.setPosicionValor(getProcesoFilesDetaBean().getPosicionValor()); procesoFilesDetaBean.setComplemento(getProcesoFilesDetaBean().getComplemento()); procesoFilesDetaBean.setTipoValorEstado(getProcesoFilesDetaBean().getTipoValorEstado()); procesoFilesDetaBean.setConstante(getProcesoFilesDetaBean().getConstante()); procesoFilesService.insertarProcesosFilesDetaBanco(procesoFilesDetaBean, procesoFilesBean, flgPro); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); //Verificando Codigos CodigoService codigoService = BeanFactory.getCodigoService(); CodigoBean codigoTipoFileCab = new CodigoBean(); codigoTipoFileCab = codigoService.obtenerPorCodigo(new CodigoBean(20001, "Cabecera", new TipoCodigoBean(MaristaConstantes.file_Cabecera))); } else { listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); RequestContext.getCurrentInstance().addCallbackParam("error", true); } // } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void cambiarFile() { try { System.out.println(""); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); procesoFilesDetaBean.getTipoDato().setIdCodigo(procesoFilesDetaBean.getDato()); if (procesoFilesDetaBean.getTipoDato().getIdCodigo() != null) { guardarDetaFiles(); } Integer var = 0; if (procesoFilesDetaBean.getTipoFile().getIdCodigo().equals(20001)) { var = 1; } else { if (procesoFilesDetaBean.getTipoFile().getIdCodigo().equals(20002)) { var = 2; } else { if (procesoFilesDetaBean.getTipoFile().getIdCodigo().equals(20003)) { var = 3; } } } ProcesoFinalService procesoFinalService = BeanFactory.getProcesoFinalService(); // procesoFinalService.eliminarFile(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getEntidadBean().getRuc(), var); limpiarFilesDeta(); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public String actualizarProcesosFilesDeta() { String pagina = null; try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); if (procesoFilesDetaBean.getPosicionFin() > procesoFilesDetaBean.getPosicionIni() || procesoFilesDetaBean.getPosicionFin().equals(procesoFilesDetaBean.getPosicionIni())) { procesoFilesDetaBean.setModiPor(beanUsuarioSesion.getUsuario()); Integer longitud = 0; longitud = procesoFilesDetaBean.getPosicionFin() - procesoFilesDetaBean.getPosicionIni(); procesoFilesDetaBean.setLongitud(longitud); procesoFilesService.modificarProcesosFiles(procesoFilesDetaBean); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); limpiarFilesDeta(); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } else { listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); RequestContext.getCurrentInstance().addCallbackParam("error", true); limpiarFilesDeta(); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } return pagina; } public void guardarDetaFiles() { try { if (procesoFilesDetaBean.getIdFile() == null) { insertarProcesosFilesDeta(); } else { actualizarProcesosFilesDeta(); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerDato() { try { System.out.println(">>>" + procesoFilesDetaBean.getDato()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerFile() { try { procesoFilesDetaBean.getTipoFile().setIdCodigo(procesoFilesDetaBean.getFile()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerDefecto() { try { procesoFilesDetaBean.setIdDefecto(procesoFilesDetaBean.getIdDefecto()); System.out.println(procesoFilesDetaBean.getIdDefecto()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerLong() { try { System.out.println(">>>" + procesoFilesDetaBean.getLongitud()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerNombreDes() { try { System.out.println(">>>" + procesoFilesDetaBean.getNombre()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerDescrip() { try { System.out.println(">>>" + procesoFilesDetaBean.getDescripcion()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public String eliminarFileDeta() { String pagina = null; try { if (pagina == null) { CodigoService codigoService = BeanFactory.getCodigoService(); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); CodigoBean codigoTipoFileCab = new CodigoBean(); CodigoBean codigoTipoFileInt = new CodigoBean(); codigoTipoFileCab = codigoService.obtenerPorCodigo(new CodigoBean(20001, "Cabecera", new TipoCodigoBean(MaristaConstantes.file_Cabecera))); codigoTipoFileInt = codigoService.obtenerPorCodigo(new CodigoBean(20003, "Intermedio", new TipoCodigoBean(MaristaConstantes.file_Intermedio))); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); procesoFilesService.eliminarProcesosFile(fileDetaBean); Integer var = 0; if (fileDetaBean.getTipoFile().getIdCodigo().equals(20001)) { var = 1; } else { if (fileDetaBean.getTipoFile().getIdCodigo().equals(20002)) { var = 2; } else { if (fileDetaBean.getTipoFile().getIdCodigo().equals(20003)) { var = 3; } } } ProcesoFinalService procesoFinalService = BeanFactory.getProcesoFinalService(); procesoFinalService.eliminarFile(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getEntidadBean().getRuc(), var); if (fileDetaBean.getTipoFile().getIdCodigo().equals(codigoTipoFileCab.getIdCodigo())) { listaCabecera = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } else { if (fileDetaBean.getTipoFile().getIdCodigo().equals(codigoTipoFileInt.getIdCodigo())) { listaIntermedio = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } else { listaDetalle = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } } listaProcesoFilesDetBean = new ArrayList<>(); listaProcesoFilesDetDetBean = new ArrayList<>(); listaProcesoFilesIntDetBean = new ArrayList<>(); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } return pagina; } //Eventos Select public void onSelectFileCab(SelectEvent event) { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); procesoFilesDetaBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), Integer.parseInt(event.getObject().toString())); System.out.println(event.getObject().toString()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void onSelectFileDet(SelectEvent event) { try { System.out.println(event.getObject().toString()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerProcesoFile(Integer resource) { try { System.out.println(">>>" + resource); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); if (resource.equals(1)) { listaCabecera = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } else { if (resource.equals(0)) { listaDetalle = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } else { if (resource.equals(2)) { listaIntermedio = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } } } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void obtenerFileId(Object object) { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); fileDetaBean = (ProcesoFilesBean) object; fileDetaBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), fileDetaBean.getIdFile()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //-------------------------------------------------------------------------------------------------------------------------------------------------------- //Posicionamiento Cabecera DEF public void posicionarFileCab() { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); Integer posicion = 0; Integer file = 0; Integer tipoFile = 0; Integer k = 0; for (int i = 0; i < listaProcesoFilesDetBean.size(); i++) { Object objeto = listaProcesoFilesDetBean.get(i); Integer idFile = new Integer(objeto.toString()); procesoFilesDetaBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idFile); file = procesoFilesDetaBean.getIdFile(); posicion = procesoFilesDetaBean.getPosicionItem(); tipoFile = procesoFilesDetaBean.getTipoFile().getIdCodigo(); k = i + 1; actualizarPosiciones(procesoFilesDetaBean.getPosicionItem(), procesoFilesDetaBean.getIdFile(), procesoFilesDetaBean.getTipoFile().getIdCodigo(), k); } valDel = 1;//File Cabecera moverPosiciones(valDel); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //END //Posicionamiento Detalle DEF public void posicionarFileInt() { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); Integer posicion = 0; Integer file = 0; Integer tipoFile = 0; Integer k = 0; System.out.println(">>>" + listaProcesoFilesIntDetBean.size()); for (int i = 0; i < listaProcesoFilesIntDetBean.size(); i++) { Object objeto = listaProcesoFilesIntDetBean.get(i); Integer idFile = new Integer(objeto.toString()); procesoFilesDetaBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idFile); file = procesoFilesDetaBean.getIdFile(); posicion = procesoFilesDetaBean.getPosicionItem(); tipoFile = procesoFilesDetaBean.getTipoFile().getIdCodigo(); k = i + 1; actualizarPosiciones(procesoFilesDetaBean.getPosicionItem(), procesoFilesDetaBean.getIdFile(), procesoFilesDetaBean.getTipoFile().getIdCodigo(), k); } valDel = 2;//File Detalle moverPosiciones(valDel); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //Posicionamiento Detalle DEF public void posicionarFileDet() { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); Integer posicion = 0; Integer file = 0; Integer tipoFile = 0; Integer k = 0; for (int i = 0; i < listaProcesoFilesDetDetBean.size(); i++) { Object objeto = listaProcesoFilesDetDetBean.get(i); Integer idFile = new Integer(objeto.toString()); procesoFilesDetaBean = procesoFilesService.obtenerDetaFilesId(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), idFile); file = procesoFilesDetaBean.getIdFile(); posicion = procesoFilesDetaBean.getPosicionItem(); tipoFile = procesoFilesDetaBean.getTipoFile().getIdCodigo(); k = i + 1; actualizarPosiciones(procesoFilesDetaBean.getPosicionItem(), procesoFilesDetaBean.getIdFile(), procesoFilesDetaBean.getTipoFile().getIdCodigo(), k); } valDel = 0;//File Detalle moverPosiciones(valDel); listaProcesoFilesDetBean = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesIntDetBean = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaProcesoFilesDetDetBean = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); RequestContext.getCurrentInstance().addCallbackParam("operacionCorrecta", true); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //END //Actualizando Posiciones DEF public void actualizarPosiciones(Integer posicion, Integer file, Integer tipoFile, Integer k) { try { List<ProcesoFilesBean> listaCabecera = new ArrayList<>(); List<ProcesoFilesBean> listaDetalle = new ArrayList<>(); List<ProcesoFilesBean> listaIntermedio = new ArrayList<>(); Integer ini = 0; Integer fin = 0; //Verificando Codigos CodigoService codigoService = BeanFactory.getCodigoService(); CodigoBean codigoTipoFileCab = new CodigoBean(); CodigoBean codigoTipoFiltInt = new CodigoBean(); codigoTipoFileCab = codigoService.obtenerPorCodigo(new CodigoBean(20001, "Cabecera", new TipoCodigoBean(MaristaConstantes.file_Cabecera))); codigoTipoFiltInt = codigoService.obtenerPorCodigo(new CodigoBean(20003, "Intermedio", new TipoCodigoBean(MaristaConstantes.file_Intermedio))); UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); listaCabecera = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaDetalle = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaIntermedio = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); if (tipoFile.equals(codigoTipoFileCab.getIdCodigo())) { for (int j = 0; j < listaCabecera.size(); j++) { if (listaCabecera.get(j).getIdFile().equals(file)) { listaCabecera.get(j).setPosicionItem(k); listaCabecera.get(j).setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarPosicionFiles(listaCabecera.get(j)); break; } } } else { if (tipoFile.equals(codigoTipoFiltInt.getIdCodigo())) { for (int i = 0; i < listaIntermedio.size(); i++) { if (listaIntermedio.get(i).getIdFile().equals(file)) { listaIntermedio.get(i).setPosicionItem(k); listaIntermedio.get(i).setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarPosicionFiles(listaIntermedio.get(i)); break; } } } else { for (int i = 0; i < listaDetalle.size(); i++) { if (listaDetalle.get(i).getIdFile().equals(file)) { listaDetalle.get(i).setPosicionItem(k); listaDetalle.get(i).setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarPosicionFiles(listaDetalle.get(i)); break; } } } } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //END public void moverPosiciones(Integer valDel) { try { Integer ini = 1; Integer fin = 1; UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); List<ProcesoFilesBean> listaCabeceraFiles = new ArrayList<>(); List<ProcesoFilesBean> listaDetallesFiles = new ArrayList<>(); List<ProcesoFilesBean> listaIntFiles = new ArrayList<>(); listaCabeceraFiles = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaDetallesFiles = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaIntFiles = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro);; if (valDel.equals(1)) { System.out.println("Cabecera"); for (int m = 0; m < listaCabeceraFiles.size(); m++) { ini = fin; fin = fin + listaCabeceraFiles.get(m).getLongitud() - 1; listaCabeceraFiles.get(m).setPosicionIni(ini); listaCabeceraFiles.get(m).setPosicionFin(fin); listaCabeceraFiles.get(m).setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarPosicionesFiles(listaCabeceraFiles.get(m)); fin++; } } else { if (valDel.equals(0)) { System.out.println("Detalle"); for (int n = 0; n < listaDetallesFiles.size(); n++) { ini = fin; fin = fin + listaDetallesFiles.get(n).getLongitud() - 1; listaDetallesFiles.get(n).setPosicionIni(ini); listaDetallesFiles.get(n).setPosicionFin(fin); listaDetallesFiles.get(n).setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarPosicionesFiles(listaDetallesFiles.get(n)); fin++; } } else { if (valDel.equals(2)) { System.out.println("Intermedio"); for (int n = 0; n < listaIntFiles.size(); n++) { ini = fin; fin = fin + listaIntFiles.get(n).getLongitud() - 1; listaIntFiles.get(n).setPosicionIni(ini); listaIntFiles.get(n).setPosicionFin(fin); listaIntFiles.get(n).setModiPor(beanUsuarioSesion.getUsuario()); procesoFilesService.modificarPosicionesFiles(listaIntFiles.get(n)); fin++; } } } } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //-------------------------------------------------------------------------------------------------------------------------------------------------------- public void editarFile() { } public void cancelEditFile() { } public void onRowEditCab(RowEditEvent event) { try { UsuarioBean beanUsuarioSesion = (UsuarioBean) new MaristaUtils().sesionObtenerObjeto("usuarioLogin"); ProcesoFilesService procesoFilesService = BeanFactory.getProcesoFilesService(); Integer ini = 0; Integer fin = 0; Integer res = 0; Integer response = 0; Integer compare = 0; ini = ((ProcesoFilesBean) event.getObject()).getPosicionIni(); fin = ((ProcesoFilesBean) event.getObject()).getPosicionFin(); res = fin - ini; if (fin > ini || fin.equals(ini)) { procesoFilesDetaBean = new ProcesoFilesBean(); procesoFilesDetaBean.setNombre(((ProcesoFilesBean) event.getObject()).getNombre()); procesoFilesDetaBean.setPosicionIni(((ProcesoFilesBean) event.getObject()).getPosicionIni()); procesoFilesDetaBean.setPosicionFin(((ProcesoFilesBean) event.getObject()).getPosicionFin()); procesoFilesDetaBean.setDescripcion(((ProcesoFilesBean) event.getObject()).getDescripcion()); procesoFilesDetaBean.setLongitud(res + 1); procesoFilesDetaBean.setIdDefecto(((ProcesoFilesBean) event.getObject()).getIdDefecto()); procesoFilesDetaBean.getTipoDato().setIdCodigo(((ProcesoFilesBean) event.getObject()).getTipoDato().getIdCodigo()); procesoFilesDetaBean.getUnidadNegocioBean().setUniNeg(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg()); procesoFilesDetaBean.getEntidadBean().setRuc(((ProcesoFilesBean) event.getObject()).getEntidadBean().getRuc()); procesoFilesDetaBean.setIdDefecto(((ProcesoFilesBean) event.getObject()).getIdDefecto()); procesoFilesDetaBean.setIdFile(((ProcesoFilesBean) event.getObject()).getIdFile()); procesoFilesDetaBean.setPosicionValor(((ProcesoFilesBean) event.getObject()).getPosicionValor()); procesoFilesDetaBean.setTipoValorEstado(((ProcesoFilesBean) event.getObject()).getTipoValorEstado()); procesoFilesDetaBean.setConstante(((ProcesoFilesBean) event.getObject()).getConstante()); procesoFilesDetaBean.setComplemento(((ProcesoFilesBean) event.getObject()).getComplemento()); procesoFilesService.modificarCabeceraFiles(procesoFilesDetaBean); listaCabecera = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaDetalle = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaIntermedio = procesoFilesService.obtenerProcesosFilesIntDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); if (((ProcesoFilesBean) event.getObject()).getTipoFile().getIdCodigo().equals(20001)) { response = 1; } else { if (((ProcesoFilesBean) event.getObject()).getTipoFile().getIdCodigo().equals(20002)) { response = 2; } else { if (((ProcesoFilesBean) event.getObject()).getTipoFile().getIdCodigo().equals(20003)) { response = 3; } else { response = 0; } } } System.out.println("res: " + response); ProcesoFinalService procesoFinalService = BeanFactory.getProcesoFinalService(); // procesoFinalService.eliminarFile(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getEntidadBean().getRuc(), response); limpiarFilesDeta(); FacesMessage msg = new FacesMessage("Cambio exitoso: ", ((ProcesoFilesBean) event.getObject()).getNombre()); FacesContext.getCurrentInstance().addMessage(null, msg); } else { listaCabecera = procesoFilesService.obtenerProcesosFilesDetaCabPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); listaDetalle = procesoFilesService.obtenerProcesosFilesDetaDetPro(beanUsuarioSesion.getPersonalBean().getUnidadNegocioBean().getUniNeg(), procesoFilesBean.getIdFile(), flgPro); FacesMessage msg = new FacesMessage("Error de validacin: Posicion Final debe ser menor a la inicial", null); FacesContext.getCurrentInstance().addMessage(null, msg); } } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void onRowCancelCab(RowEditEvent event) { try { FacesMessage msg = new FacesMessage("Operacion Cancelada: ", ((ProcesoFilesBean) event.getObject()).getNombre()); FacesContext.getCurrentInstance().addMessage(null, msg); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } public void ponerCons() { try { getProcesoFilesDetaBean().setTipoValorEstado(getProcesoFilesDetaBean().getTipoValorEstado()); if (getProcesoFilesDetaBean().getTipoValorEstado().equals(1)) { getProcesoFilesDetaBean().setPosicionValorItem(false); } else { getProcesoFilesDetaBean().setPosicionValorItem(true); } System.out.println(">>>" + getProcesoFilesDetaBean().getTipoValorEstado()); } catch (Exception err) { new MensajePrime().addErrorGeneralMessage(); GLTLog.writeError(this.getClass(), err); } } //end }
true
4070b6e217684dc9fc9e2ee32d41e01f5e77cc32
Java
bellmit/MIOT-demo
/src/main/java/com/xiaomi/iot/example/typedef/Instance.java
UTF-8
1,315
2.125
2
[]
no_license
package com.xiaomi.iot.example.typedef; import org.json.JSONArray; public class Instance { private String description; private String type; private String subscriptionId; private String status; private JSONArray customized_services; private JSONArray services; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public JSONArray getCustomized_services() { return customized_services; } public void setCustomized_services(JSONArray customized_services) { this.customized_services = customized_services; } public JSONArray getServices() { return services; } public void setServices(JSONArray services) { this.services = services; } }
true
b144d6d48d83f65404c618c023ea7a7f74152707
Java
joedarby/gas-android-app
/app/src/main/java/com/darby/joe/gas/data/Pipeline.java
UTF-8
319
2.140625
2
[]
no_license
package com.darby.joe.gas.data; import java.util.Date; public class Pipeline { public String pipelineName; public double flowValue; public Date timestamp; public Pipeline(String name, double flow, Date stamp) { pipelineName = name; flowValue = flow; timestamp = stamp; } }
true
4a32d3167e0cf17e45f83312e62de6d71eb6fac3
Java
Tse-ChiKit/VISRA
/app/src/main/java/com/monash/eric/mytestingdemo/SearchActivity.java
UTF-8
10,199
1.945313
2
[]
no_license
package com.monash.eric.mytestingdemo; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.net.ssl.HttpsURLConnection; public class SearchActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { //Google GeoCoding URL Setitings private static final String GEO_BASE_URI = "https://maps.googleapis.com/maps/api/geocode/json?latlng="; //GeoCoding Response String geoCodingResponse; private static final String API_KEY = "AIzaSyCxzmhZsWml6UQUqK_ss8aPvPzBk1u-YrU"; private static final String TAG = "SearchActivity"; public double lng = 0; public double lat = 0; private static final String BASE_URI = "http://visra9535.cloudapp.net/api/searchall"; private EditText et_suburb; private EditText et_sprot; private CheckBox cb_indoor; private CheckBox cb_outdoor; private String intentStr =""; private String suburb; private String sports; JSONObject jObject = null; JSONArray jArray = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); et_suburb = (EditText)findViewById(R.id.searchact_editText_suburb); cb_indoor = (CheckBox)findViewById(R.id.searchact_checkBox_indoor); cb_outdoor = (CheckBox)findViewById(R.id.searchact_checkBox_outdoor); Intent intent = getIntent(); lng = intent.getDoubleExtra("lng",0); lat = intent.getDoubleExtra("lat",0); // for testing // CallGeoWS callGeoWS = new CallGeoWS(); // callGeoWS.execute(lng,lat); Button button = (Button) this.findViewById(R.id.button2_actsearch); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(et_suburb.getText().toString().equals("")) { Log.i("aa", "empty"); } Log.i("aa", et_suburb.getText().toString()); CallSearchSprostAPI callSearchSprostAPI = new CallSearchSprostAPI(); callSearchSprostAPI.execute("aa"); } }); // Spinner element Spinner spinner = (Spinner) findViewById(R.id.spinner); // Spinner click listener spinner.setOnItemSelectedListener(this); // Spinner Drop down elements List<String> categories = new ArrayList<String>(); categories.add("Soccer"); categories.add("Basketball"); categories.add("Table Tennis"); categories.add("Swimming"); categories.add("Badminton"); categories.add("Volleyball"); categories.add("Cricket"); categories.add("Snooker"); categories.add("Cycling"); categories.add("Hockey"); categories.add("Tennis"); categories.add("Rugby Union"); categories.add("Rugby Legue"); // Creating adapter for spinner ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories); // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // attaching data adapter to spinner spinner.setAdapter(dataAdapter); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // On selecting a spinner item sports = parent.getItemAtPosition(position).toString(); // Showing selected spinner item //Toast.makeText(parent.getContext(), "Selected: " + sports, Toast.LENGTH_LONG).show(); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } private class CallSearchSprostAPI extends AsyncTask<String,Void,String> { @Override protected String doInBackground(String... params) { return callSearchSportsWS(params[0]); } @Override protected void onPostExecute(String s) { intentStr = s; Intent intent = new Intent(); Log.i("TESTBACK",intentStr); intent.putExtra("result", intentStr); SearchActivity.this.setResult(RESULT_OK, intent); //关闭Activity SearchActivity.this.finish(); } } protected String callSearchSportsWS(String subrubs) { HashMap<String, String> postDataParams = new HashMap<>(); if(!et_suburb.getText().toString().equals("")) { postDataParams.put("suburbs",et_suburb.getText().toString()); } if(sports != null) { postDataParams.put("sports",sports); } if (cb_indoor.isChecked() && cb_outdoor.isChecked()) { Log.i("a","nothing"); } else if(!cb_indoor.isChecked() && !cb_outdoor.isChecked()) { } else if(cb_indoor.isChecked()) { postDataParams.put("indoor","1"); } else { Log.i("a","outdoor clicked"); postDataParams.put("indoor","0"); } URL url; String response = ""; try { url = new URL(BASE_URI); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode=conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; System.out.println(response); } } else { response=""; } } catch (Exception e) { e.printStackTrace(); } return response; } private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } System.out.println("RequestPara : " + result.toString()); return result.toString(); } private String callGeoWS(double lng, double lat) { URL url = null; HttpURLConnection conn = null; String textResult = ""; try { StringBuilder sb = new StringBuilder(); sb.append(GEO_BASE_URI); sb.append(lat); sb.append(","); sb.append(lng); sb.append("&key="); sb.append(API_KEY); Log.d(TAG,sb.toString()); url = new URL(sb.toString()); conn = (HttpURLConnection) url.openConnection(); //set the timeout conn.setReadTimeout(10000); conn.setConnectTimeout(15000); //set the connection method to POST conn.setRequestMethod("GET"); //set the output to true conn.setDoOutput(true); //Read the response Scanner inStream = new Scanner(conn.getInputStream()); //read the input steream and store it as string while (inStream.hasNextLine()) { textResult += inStream.nextLine(); } } catch (Exception e) { e.printStackTrace(); } finally { conn.disconnect(); } return textResult; } private class CallGeoWS extends AsyncTask<Double,Void,String> { @Override protected String doInBackground(Double... params) { return callGeoWS(params[0],params[1]); } @Override protected void onPostExecute(String result) { getSuburbFromJson(result); et_suburb.setText(suburb); } } private String getSuburbFromJson(String originalJson) { Gson gson = new Gson(); GeoResponse geoResponse = gson.fromJson(originalJson,GeoResponse.class); GeoResponse.address_component[] element = geoResponse.results[0].address_components; Log.d(TAG,element[0].long_name); for(int i = 0 ; i<element.length; i++) { if(element[i].types[0].equals("locality")) { suburb = element[i].long_name; } } return null; } }
true
5a346133ccce306c92fce1fa0d43592985ffc512
Java
SillyV/SillyVMovieList
/app/src/main/java/com/example/vasili/sillyvmovielist/db/MovieTableHandler.java
UTF-8
3,949
2.75
3
[]
no_license
package com.example.vasili.sillyvmovielist.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.util.Log; import java.util.ArrayList; import java.util.List; /** * Created by Vasili on 12/7/2015. */ public class MovieTableHandler { static final String MOVIES_TABLE_NAME = "movies"; static final String ID = "id"; static final String TITLE = "title"; static final String BODY = "body"; static final String URL = "url"; static final String YEAR = "year"; private static final String TAG = "SillyV.TableHandler"; private final MovieDBHelper dbHelper; public MovieTableHandler(Context context) { dbHelper = new MovieDBHelper(context); } public List<Movie> getAllMovies() { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(MOVIES_TABLE_NAME, null, null, null, null, null, null); List<Movie> movies = new ArrayList<>(); while (cursor.moveToNext()) { Movie movie = getMovie(cursor); movies.add(movie); } return movies; } public Movie getMovie(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(MOVIES_TABLE_NAME, null, ID + " = " + id, null, null, null, null); if (cursor.moveToFirst()) { return getMovie(cursor); } return null; } public long addMovie(Movie newMovie) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = getMovieValues(newMovie); try { return db.insert(MOVIES_TABLE_NAME, null, values); } catch (SQLiteException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } db.close(); return -1; } public void updateMovie(Movie editedMovie) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = getMovieValues(editedMovie); try { db.update(MOVIES_TABLE_NAME, values, ID + " = " + editedMovie.getID(), null); } catch (SQLiteException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } db.close(); } public void removeMovie(int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); try { db.delete(MOVIES_TABLE_NAME, ID + " = " + id, null); } catch (SQLiteException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } db.close(); } private static ContentValues getMovieValues(Movie movie) { ContentValues values = new ContentValues(); values.put(TITLE, movie.getTitle()); values.put(BODY, movie.getPlot()); values.put(URL, movie.getPoster()); values.put(YEAR, movie.getYear()); // values.put(OMDBID,""); return values; } private static Movie getMovie(Cursor cursor) { int id = cursor.getInt(cursor.getColumnIndex(ID)); String title = cursor.getString(cursor.getColumnIndex(TITLE)); String body = cursor.getString(cursor.getColumnIndex(BODY)); String url = cursor.getString(cursor.getColumnIndex(URL)); int year = cursor.getInt(cursor.getColumnIndex(YEAR)); return new Movie(id, title, year, body, url); } public void removeAll() { SQLiteDatabase db = dbHelper.getWritableDatabase(); try { db.delete(MOVIES_TABLE_NAME, null, null); } catch (SQLiteException e) { e.printStackTrace(); Log.e(TAG, e.getMessage()); } db.close(); } }
true
6f30dd1cfb25fd5a9fd0ae40416ac7f5d721e14e
Java
zwd1763532517/payment
/src/main/java/com/payment/domain/paybean/VenderPayManage.java
UTF-8
2,540
2.203125
2
[]
no_license
/** * @(#)VenderPayManage.java * Description: * Version : 1.0 * Copyright: Copyright (c) Xu minghua 版权所有 */ package com.payment.domain.paybean; import com.payment.service.VenderPayService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /** * 绑定,解绑service * * @author Xu minghua 2017/02/12 * @version 1.0 */ @Component public class VenderPayManage { private static final Logger logger = LoggerFactory.getLogger(VenderPayManage.class); private final Map<String, VenderPayService> payServiceMap = new ConcurrentHashMap<>(); private final Map<String, VenderPayService> callbackUrlMap = new ConcurrentHashMap<>(); public boolean hasVenderPayService(String payId) { return payServiceMap.containsKey(payId); } public VenderPayService getVenderPayService(String payId) { return payServiceMap.get(payId); } public boolean hasCallbackUrl(String CallbackUrl) { return callbackUrlMap.containsKey(CallbackUrl); } public VenderPayService getVenderPayServiceByCallbackUrl(String CallbackUrl) { return callbackUrlMap.get(CallbackUrl); } public void bindVenderPay(VenderPayService payService, Map attrs) { VenderPayServiceAnnounce announce = Objects.requireNonNull(payService.getAnnounce(), "found null announce"); logger.debug("Bind VenderPayService, payid = {}, ", announce.getPayId()); payServiceMap.put(announce.getPayId(), payService); if (announce.isHasCallback()) { callbackUrlMap.put(announce.getCallbackUrl(), payService); } logger.debug("Bind VenderPayService, payService size = {}, callbackUrl size = {}", payServiceMap.size(), callbackUrlMap.size()); } public void unbindVenderPay(VenderPayService payService) { if (payService != null) { VenderPayServiceAnnounce announce = payService.getAnnounce(); if (announce != null) { logger.debug("Unbind VenderPayService, payid = {}", announce.getPayId()); if (announce.isHasCallback()) { callbackUrlMap.remove(announce.getCallbackUrl()); } payServiceMap.remove(announce.getPayId()); } logger.debug("Unbind VenderPayService,payService size = {}, callbackUrl size = {}", payServiceMap.size(), callbackUrlMap.size()); } } }
true
fa1b7287c0562746770fe8ec7a8b5daf9291e1d7
Java
oracs/codekata
/worldclock/src/main/java/com/dy/kata/worldclock/v1/Waiter.java
UTF-8
291
2.421875
2
[]
no_license
package com.dy.kata.worldclock.v1; import com.dy.kata.worldclock.v1.impl.BeijingClock; public class Waiter { public void syncTime(WallClocks wallclocks, BeijingClock adjustTime) { for (Clock clock: wallclocks.clocks) { clock.syncTime(adjustTime); } } }
true
0c1f83f4b4e737961c31301ece682c3cbfc631e1
Java
yoursNicholas/springbootdubbo
/dubbo-provider/src/main/java/com/xuzhe/jpa/UserJPA.java
UTF-8
780
2.09375
2
[ "Apache-2.0" ]
permissive
package com.xuzhe.jpa; import com.xuzhe.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional public interface UserJPA extends JpaRepository<UserEntity,Long> { //查询大于20岁的用户 @Query(value = "select * from t_user where t_age > ?1",nativeQuery = true) public List<UserEntity> nativeQuery(int age); //根据用户名、密码删除一条数据 @Modifying @Query(value = "delete from t_user where t_name = ?1 and t_pwd = ?2",nativeQuery = true) public void deleteQuery(String name, String pwd); }
true
7eaf0ced57f57b07773ab058cc7fb5fa72a5806e
Java
martinpolley/codeine
/src/directory/codeine/servlets/RsyncSourceForVersionServlet.java
UTF-8
1,191
2.34375
2
[]
no_license
package codeine.servlets; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import codeine.model.Constants; import codeine.servlet.AbstractServlet; import codeine.version.RsyncSourceGetter; public class RsyncSourceForVersionServlet extends AbstractServlet{ private static final Logger log = Logger.getLogger(RsyncSourceForVersionServlet.class); private static final long serialVersionUID = 1L; private @Inject RsyncSourceGetter rsyncSourceGetter; @Override protected void myGet(HttpServletRequest request, HttpServletResponse response) { String version = request.getParameter("version"); String hostname = request.getParameter("peer"); log.info("get with params version " + version + " peer " + hostname); String rsyncSource = rsyncSourceGetter.getForVersion(version, hostname); log.info("rsync source is " + rsyncSource); if (null != rsyncSource){ getWriter(response).write(rsyncSource); } else{ getWriter(response).write(Constants.NO_VERSION); } } @Override protected boolean checkPermissions(HttpServletRequest request) { return true; } }
true
08c6b96750ff6c18819cf7a31d5a7edbd111afc7
Java
humwawe/leetcode
/src/main/java/minimum/number/of/days/to/make/m/bouquets/MinimumNumberOfDaysToMakeMBouquets.java
UTF-8
901
3.1875
3
[]
no_license
package minimum.number.of.days.to.make.m.bouquets; /** * @author hum */ public class MinimumNumberOfDaysToMakeMBouquets { public int minDays(int[] bloomDay, int m, int k) { int len = bloomDay.length; if (m * k > len) { return -1; } int l = 0; int r = (int) 1e9; while (l < r) { int mid = l + r >> 1; int count = 0; int res = 0; for (int i = 0; i < len; i++) { if (bloomDay[i] > mid) { res += count / k; count = 0; } else { count++; } } if (count > 0) { res += count / k; } if (res >= m) { r = mid; } else { l = mid + 1; } } return l; } }
true
be96ea5cdabba6c792f378478d9ecc9569b265ff
Java
DevinKin/JavaNote
/BeautiOfConcurrency/src/main/java/chapter1/daemon/TestUserThread.java
UTF-8
493
2.90625
3
[]
no_license
package chapter1.daemon; /** * @program: BeautiOfConcurrency * @author: devinkin * @create: 2019-07-31 15:13 * @description: 守护线程2 **/ public class TestUserThread { public static void main(String[] args) { Thread thread = new Thread(() -> { for (;;) { } }); // 设置为守护线程 thread.setDaemon(true); // 启动子线程 thread.start(); System.out.println("main thread is over"); } }
true
5da6ff72d6420967705b82867146a6bd8b10e73f
Java
gobbletsit/BookListingApp
/BookListingApp/app/src/main/java/com/example/android/booklistingapp/QueryUtils.java
UTF-8
7,205
2.96875
3
[]
no_license
package com.example.android.booklistingapp; import android.text.TextUtils; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * Created by gobov on 5/20/2017. */ public class QueryUtils { private static final String LOG_TAG = QueryUtils.class.getName(); private QueryUtils(){ } public static List<Book> fetchBooks(String requestUrl){ // CREATING AN URL OBJECT FOR MAKING A REQUEST URL url = createUrl(requestUrl); // MAKING A REQUEST String jsonResponse = null; try { jsonResponse = makeHttpRequest(url); } catch (IOException e){ Log.e(LOG_TAG, "fetchBooks ", e); } // PARSING THE JSON STRING INTO A CREATED LIST List<Book> bookList = extractBooks(jsonResponse); return bookList; } // TO EXTRACT THE BOOK DATA IN AN ARRAY LIST private static List<Book> extractBooks(String bookJson) { // TO RETURN EARLY IF THERE'S NO DATA if (TextUtils.isEmpty(bookJson)){ return null; } // CREATING AN EMPTY ARRAY LIST OT ADD DATA TO ArrayList<Book> books = new ArrayList<>(); // TRYING THE PARSE THE JSON OBJECT AND THROWING AN EXCEPTION IF THERE'S A PROBLEM try { // CREATING A JSON OBJECT JSONObject baseJsonResponse = new JSONObject(bookJson); // CREATING A LIST OF JSON OBJECTS JSONArray bookJsonArray = baseJsonResponse.getJSONArray("items"); // GOING THRU AN ARRAY LIST OF OBJECTS TO GET THE NEEDED DATA USING KEYWORDS for (int i = 0; i < bookJsonArray.length(); i++){ JSONObject currentBook = bookJsonArray.getJSONObject(i); JSONObject bookProperties = currentBook.getJSONObject("volumeInfo"); String title; String description; String rating; String url; // CHECKING IF THE KEY EXISTS AND RETURNING THE VALUES if (bookProperties.has("title")){ title = bookProperties.getString("title"); } else { title = "N/A"; } // CREATING A JSON ARRAY TO EXTRACT THE AUTHOR STRINGS FROM IT JSONArray authorsArray = null; String author = ""; // CHECKING IF THE KEY EXISTS AND RETURNING THE VALUES if (bookProperties.has("authors")) { authorsArray = bookProperties.getJSONArray("authors"); // GOING THRU AN ARRAY LIST OF STRINGS TO GET THE NEEDED DATA for (int a = 0; a < authorsArray.length(); a++) { author = authorsArray.getString(a); } } else { author = "N/A"; } // CHECKING IF THE KEY EXISTS AND RETURNING THE VALUES if (bookProperties.has("description")){ description = bookProperties.getString("description"); } else { description = "N/A"; } // CHECKING IF THE KEY EXISTS AND RETURNING THE VALUES if (bookProperties.has("averageRating")){ Double ratingDouble = bookProperties.getDouble("averageRating"); // CONVERTING THE DOUBLE VALUE TO A STRING rating = String.valueOf(ratingDouble); } else { rating = "N/A"; } // RETURNING THE STRING VALUES FOR THE BOOK LINK url = bookProperties.getString("previewLink"); // CREATING A BOOK OBJECT AND ADDING IT TO THE LIST Book book = new Book(title, description, author, rating, url); books.add(book); } } catch (JSONException e) { // If an error is thrown when executing any of the above statements in the "try" block, // catch the exception here, so the app doesn't crash. Print a log message // with the message from the exception. Log.e(LOG_TAG, "Problem parsing the book JSON results", e); } // RETURN BOOK LIST return books; } // TO CREATE A URL OBJECT USING A STRING PARAM private static URL createUrl(String stringUrl) { URL url = null; try { url = new URL(stringUrl); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Error with creating URL ", e); } return url; } // TO MAKE A REQUEST WITH A ULR PARAM AND TO RECEIVE A STRING private static String makeHttpRequest(URL url) throws IOException { // TO RETURN EARLY String jsonResponse = null; if (url == null){ return jsonResponse; } HttpURLConnection connection = null; InputStream inputStream = null; // TO TRY TO ESTABLISH A URL CONNECTION WITH A REQUEST KEYWORD AND CATCHING THE EXCEPTION IF THERE'S A PROBLEM WITH IT try { connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); connection.setRequestMethod("GET"); connection.connect(); // IF CONNECTION IS FULFILLED READ FROM STREAM if (connection.getResponseCode() == 200){ inputStream = connection.getInputStream(); jsonResponse = readStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + connection.getResponseCode()); } // CATCHING EXCEPTION } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the book JSON results." + e); // TO DISCONNECT AND CLOSE IF CONNECTION IS EXECUTED } finally { if (connection != null) { connection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; } // TO READ THE STREAM OF BYTES AND TRANSLATE IT TO A STRING private static String readStream(InputStream stream) throws IOException{ StringBuilder output = new StringBuilder(); if (stream != null){ InputStreamReader reader = new InputStreamReader(stream, Charset.forName("UTF-8")); BufferedReader bufferedReader = new BufferedReader(reader); String line = bufferedReader.readLine(); while (line != null){ output.append(line); line = bufferedReader.readLine(); } } return output.toString(); } }
true
b694efabe10f22ac335bc71a09aa8d84f7e9b458
Java
bobroalexandr/Clean-Architecture-Android
/app/src/main/java/demo/presentation/view/DemoView.java
UTF-8
1,647
2.09375
2
[]
no_license
package demo.presentation.view; import android.app.ProgressDialog; import android.content.Context; import android.support.design.widget.Snackbar; import android.view.View; import demo.R; import demo.presentation.presenter.DataPresenter; /** * Created on 12.11.2015. */ public class DemoView<VM, P extends DataPresenter> extends DataViewBase<VM, P, View> { ProgressDialog progressDialog; Snackbar snackbar; @Override public void showError(Throwable exception, boolean shouldRetry) { super.showError(exception, shouldRetry); snackbar = Snackbar.make(getRootView(), getTextForError(exception), shouldRetry ? Snackbar.LENGTH_INDEFINITE : Snackbar.LENGTH_LONG); if (shouldRetry) { snackbar.setAction(R.string.action_retry, new View.OnClickListener() { @Override public void onClick(View v) { getDataPresenter().retryLoading(); } }); } snackbar.show(); } @Override public void hideError() { super.hideError(); if(snackbar != null && snackbar.isShown()) { snackbar.dismiss(); } } protected String getTextForError(Throwable exception) { return getContext().getString(R.string.message_unknown_error); } @Override public void showLoading() { super.showLoading(); if(progressDialog == null) { progressDialog = new ProgressDialog(getContext()); progressDialog.show(); } else if(!progressDialog.isShowing()) { progressDialog.show(); } } @Override public void hideLoading() { super.hideLoading(); if(progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } protected Context getContext() { return getRootView().getContext(); } }
true
e0fb6faa6d5ecd1ad70aaaf590c05d8f23426457
Java
ZeroOneSummer/ptm
/src/pojo/view/Invest_msg.java
UTF-8
1,057
2.046875
2
[]
no_license
package pojo.view; import java.util.Date; /** * 视图实体类(三表联查:invest_product,invest_type,trade_record) * @author Administrator * */ public class Invest_msg { private String produceName; private int invTypeId; private double tradeMoney; private Date tradeDate; private int tradeStatus; public String getProduceName() { return produceName; } public void setProduceName(String produceName) { this.produceName = produceName; } public int getInvTypeId() { return invTypeId; } public void setInvTypeId(int invTypeId) { this.invTypeId = invTypeId; } public double getTradeMoney() { return tradeMoney; } public void setTradeMoney(double tradeMoney) { this.tradeMoney = tradeMoney; } public Date getTradeDate() { return tradeDate; } public void setTradeDate(Date tradeDate) { this.tradeDate = tradeDate; } public int getTradeStatus() { return tradeStatus; } public void setTradeStatus(int tradeStatus) { this.tradeStatus = tradeStatus; } }
true
6f8b9f1f99251fbe1a5d8ae419b0024922c21fb7
Java
Camelcade/Perl5-IDEA
/plugin/core/src/main/java/com/perl5/lang/perl/idea/intellilang/PerlStringLiteralEscaper.java
UTF-8
3,939
1.78125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015-2020 Alexandr Evstigneev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.perl5.lang.perl.idea.intellilang; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; import com.intellij.psi.ElementManipulators; import com.intellij.psi.LiteralTextEscaper; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtilCore; import com.perl5.lang.perl.psi.PerlCharSubstitution; import com.perl5.lang.perl.psi.mixins.PerlStringMixin; import it.unimi.dsi.fastutil.ints.IntArrayList; import org.jetbrains.annotations.NotNull; import java.util.Map; import static com.perl5.lang.perl.lexer.PerlElementTypesGenerated.*; public class PerlStringLiteralEscaper extends LiteralTextEscaper<PerlStringMixin> { private static final Logger LOG = Logger.getInstance(PerlStringLiteralEscaper.class); private static final Map<IElementType, String> ALIASES_MAP = Map.of( STRING_SPECIAL_TAB, "\t", STRING_SPECIAL_NEWLINE, "\n", STRING_SPECIAL_RETURN, "\r", STRING_SPECIAL_FORMFEED, "\f", STRING_SPECIAL_BACKSPACE, "\b", STRING_SPECIAL_ALARM, "" + (char)11, STRING_SPECIAL_ESCAPE, "" + (char)27 ); private final IntArrayList myHostOffsets = new IntArrayList(); public PerlStringLiteralEscaper(@NotNull PerlStringMixin host) { super(host); } @Override public boolean decode(@NotNull TextRange rangeInsideHost, @NotNull StringBuilder outChars) { PsiElement openQuoteElement = myHost.getOpenQuoteElement(); if (openQuoteElement == null) { LOG.error("No open quote for " + myHost); return false; } PsiElement run = openQuoteElement.getNextSibling(); int startOffset = rangeInsideHost.getStartOffset(); while (run != null && run.getTextRangeInParent().getStartOffset() < startOffset) { run = run.getNextSibling(); } if (run == null) { return false; } int lastElementEnd = 0; int endOffset = rangeInsideHost.getEndOffset(); while (run != null && run.getTextRangeInParent().getEndOffset() <= endOffset) { int startOffsetInParent = run.getStartOffsetInParent(); IElementType runType = PsiUtilCore.getElementType(run); CharSequence runChars; if (run instanceof PerlCharSubstitution) { int point = ((PerlCharSubstitution)run).getCodePoint(); runChars = Character.isValidCodePoint(point) ? String.valueOf(Character.toChars(point)) : run.getText(); } else { runChars = ALIASES_MAP.get(runType); if (runChars == null && runType != STRING_SPECIAL_ESCAPE_CHAR) { runChars = run.getNode().getChars(); } } if (runChars != null) { lastElementEnd = run.getTextRangeInParent().getEndOffset(); outChars.append(runChars); for (int i = 0; i < runChars.length(); i++) { myHostOffsets.add(startOffsetInParent + i); } } run = run.getNextSibling(); } myHostOffsets.add(lastElementEnd); return !myHostOffsets.isEmpty(); } @Override public int getOffsetInHost(int offsetInDecoded, @NotNull TextRange rangeInsideHost) { return myHostOffsets.getInt(offsetInDecoded); } @Override public boolean isOneLine() { return false; } @Override public @NotNull TextRange getRelevantTextRange() { return ElementManipulators.getValueTextRange(myHost); } }
true
ab32cab8ec6bc06d2214bb581cfbf6c9d2eddf63
Java
sitanshu-joshi/Zakariya
/src/com/example/eventmng/MainActivity.java
UTF-8
6,883
2.046875
2
[]
no_license
package com.example.eventmng; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.adapter.AdapterListEvent; import com.example.eventmng.data.Building; import com.example.eventmng.data.EventList; import com.example.evntmng.util.HttpHelper; import com.util.Constant; public class MainActivity extends Activity { ListView lstView; List<EventList> lsEventLists; TextView txtGetBuilding; Button btnCreateEvent; String buildingId = "0"; private Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; lstView = (ListView)findViewById(R.id.listView1); txtGetBuilding = (TextView)findViewById(R.id.txtGetEvent); btnCreateEvent = (Button)findViewById(R.id.btnCreateEvent); if (Constant.userId == null || Constant.userId.length() == 0) { btnCreateEvent.setVisibility(View.GONE); } else { btnCreateEvent.setVisibility(View.VISIBLE); } btnCreateEvent.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, CreateEvent.class); startActivity(intent); } }); txtGetBuilding.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub building(Constant.lstBuildings); } }); lstView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub EventList ev = lsEventLists.get(position); EventDetail.eventDetail = ev; Intent intent = new Intent(MainActivity.this, EventDetail.class); startActivity(intent); } }); txtGetBuilding.setText(Constant.lstBuildings.get(0).getTitle()); initialSetup(buildingId); } private void initialSetup(String buildingId){ String resp = HttpHelper.getEventList(buildingId); try { JSONObject jsonObject = new JSONObject(resp); JSONArray data = (JSONArray)jsonObject.get("datas"); JSONObject status = (JSONObject) data.get(0); lsEventLists = new ArrayList<EventList>(); int log = (Integer) status.get("status"); if (log == 1) { int size = (Integer) status.get("size"); for (int i = 0; i < size; i++) { JSONObject object = (JSONObject)status.get(i+""); System.out.println(object); String id = object.getString("id"); String title = object.getString("title"); String time = object.getString("time"); String description = object.getString("description"); String posterUserId = object.getString("poster_user_id"); String buildingtitle = object.getString("buildingtitle"); String latitude = object.getString("latitude"); String longitude = object.getString("longitude"); EventList eventList = new EventList(); eventList.setId(id); eventList.setTime(time); eventList.setTitle(title); eventList.setDescription(description); if (description != null && description.toString().equalsIgnoreCase("null")) { eventList.setPosterUserId(posterUserId); } eventList.setBuildingTitle(buildingtitle); if (latitude != null && latitude.toString().equalsIgnoreCase("null") && longitude != null && longitude.toString().equalsIgnoreCase("null")) { eventList.setLatitude(latitude); eventList.setLongitude(longitude); } lsEventLists.add(eventList); } System.out.println(lsEventLists); if (lsEventLists.size() > 0) { AdapterListEvent adapterStoreDetail = new AdapterListEvent(getApplicationContext(), lsEventLists); lstView.setAdapter(adapterStoreDetail); } } else { Toast.makeText(context, "No Events are available", Toast.LENGTH_LONG).show(); AdapterListEvent adapterStoreDetail = new AdapterListEvent(getApplicationContext(), lsEventLists); lstView.setAdapter(adapterStoreDetail); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void testSetup(){ EventList eventList = new EventList(); eventList.setBuildingId(444+""); eventList.setBuildingTitle("Safal Profitire"); eventList.setId(1+""); eventList.setLatitude(22.34+""); eventList.setLongitude(72.32+""); eventList.setPosterUserId(2+""); eventList.setTime("17/2/2014 12:45:23"); eventList.setTitle("Safal profitier"); eventList.setDescription("205-A corporate road"); lsEventLists = new ArrayList<EventList>(); lsEventLists.add(eventList); AdapterListEvent adapterStoreDetail = new AdapterListEvent(getApplicationContext(), lsEventLists); lstView.setAdapter(adapterStoreDetail); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private void building(List<Building> buildings){ List<String> strings = new ArrayList<String>(); for (int i = 0; i < buildings.size(); i++) { strings.add(buildings.get(i).getTitle()); } final CharSequence[] items = strings.toArray(new CharSequence[strings.size()]); // final CharSequence[] items = {"Visited","Store Was Close","Not Visited"}; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { // Call event list initialSetup(Constant.lstBuildings.get(item).getId()); txtGetBuilding.setText(Constant.lstBuildings.get(item).getTitle()); } }); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); builder.setTitle("Choose Building"); alert.show(); } }
true
d2e56c62ef41efed8e3bd2ccc968eecb587b7ab3
Java
glins97/TP2
/T2/PassiveAggresive/src/com/company/Output.java
UTF-8
2,655
3.234375
3
[]
no_license
package com.company; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; public class Output { public Output(){} public LinkedHashMap sortMapByValues(Map<String, Integer> map){ assert map.keySet().size() != 0: "Map has no keys! Did you load it?"; return map.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); } public String getIndentation(String word, Integer maxLevel){ assert word.length() != 0: "Can't calculate indent level of an empty word!"; assert maxLevel >= 0: "Max level can't be negative!"; String r = ""; for (int i = 0; i < maxLevel - (word.length() / 8); i++){ r = r + "\t"; } return r; } public Object printMap(Map<String, Integer> map, Integer maxRank){ assert map.keySet().size() != 0: "Map has no keys! Can't print!"; int index = 0; int tabSize = 1; int keyMaxSize = 0; for (String key: map.keySet()){ if (key.length() > keyMaxSize){ keyMaxSize = key.length(); tabSize = keyMaxSize / 8 - 1; } } String maxIndent = ""; for (int i = 0; i< tabSize; i++){ maxIndent = maxIndent + "\t"; } System.out.println("Rank\tWord" + maxIndent + "Count"); for (String key: map.keySet()){ if (index++ >= maxRank && maxRank > 0) break; System.out.println(index + "\t" + key + getIndentation(key, tabSize) + map.get(key)); } return map; } public Object saveMap(Map<String, Integer> map, String filename){ assert map.keySet().size() != 0: "Map has no keys! Can't save!"; assert filename.length() != 0: "Output filename must have at least one letter!"; int index = 0; try{ FileWriter file = new FileWriter("../resources/output/" + filename); BufferedWriter writer = new BufferedWriter(file); writer.write("Rank,Word,Count\n"); for (String key: map.keySet()){ writer.write(++index + "," + key + "," + map.get(key) + "\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } return map; } }
true
c60ffc1db10005b7ef11446bb90cbf0fed8d5f36
Java
bishion/mvnPlugin
/src/main/java/com/bizi/plugin/Forth.java
UTF-8
3,147
2.421875
2
[]
no_license
package com.bizi.plugin; import com.bizi.utils.FileUtil; import net.wicp.tams.commons.apiext.IOUtil; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import java.io.InputStream; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; /** * Created by guofangbi on 2017/3/17. * 文件替换,用于自动生成代码 */ @Mojo(name = "forth") public class Forth extends AbstractMojo{ @Parameter(property = "groupId",defaultValue = "com.bizi") private String groupId; @Parameter(property = "artifactId",defaultValue = "test") private String artifactId; public void execute() throws MojoExecutionException, MojoFailureException { String basePackage = groupId+"."+artifactId; String baseDir = basePackage.replaceAll("\\.","/"); Map<String,String> map = new HashMap<>(2); map.put("\\[projectName\\]",artifactId); map.put("\\[basepackage\\]",basePackage); try { System.out.println(getClass().getResource("/init").toURI()); String initPath = getClass().getResource("/init").getPath(); Map<String,InputStream> copyFilesMap = IOUtil.getFilesFromJar("jar:"+initPath,"init"); for (String fileName : copyFilesMap.keySet()){ String content = IOUtil.slurp(copyFilesMap.get(fileName)); String targetPath ; int lastIndex = fileName.lastIndexOf("/"); int firstIndex = fileName.indexOf("/")+1; String singleFileName = fileName.substring(lastIndex); if(fileName.endsWith(".java")){ targetPath =fileName.substring(firstIndex,lastIndex)+"/"+baseDir+singleFileName; }else { targetPath = fileName.substring(firstIndex); } FileUtil.writeContentToFile(getLog(),content,artifactId+"/"+targetPath,map); } } catch (Exception e) { e.printStackTrace(); getLog().error("初始化失败",e); throw new MojoFailureException("初始化失败",e); } } public static void main(String[] args) { String basePackage = "com.bizi.test"; String baseDir = basePackage.replaceAll("\\.","/"); String fileName = "init/src/main/java/application.java"; String targetPath ; int lastIndex = fileName.lastIndexOf("/"); int firstIndex = fileName.indexOf("/"); // String relativePath = fileName.substring(fileName.indexOf("/"),lastIndexOf); String singleFileName = fileName.substring(lastIndex); if(fileName.endsWith(".java")){ targetPath =fileName.substring(firstIndex,lastIndex)+"/"+baseDir+singleFileName; System.out.println(targetPath); }else { targetPath = fileName.substring(firstIndex+1); System.out.println(targetPath); } } }
true
a3c824d82b6106ad149d9c960f125abc40e3e252
Java
chrisdollar/BRS
/src/main/java/com/sotra/reservation/repository/user/UserRepository.java
UTF-8
263
1.835938
2
[ "MIT" ]
permissive
package com.sotra.reservation.repository.user; import com.sotra.reservation.model.user.User; import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository<User, Long> { User findByEmail(String email); }
true
5d25dd850178826f10c1a39ca16ebc96d6bef0f3
Java
ugurk/aasuite
/tool2/src/rule/CustomerContactPresentationExt_RULE.java
UTF-8
625
2.09375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package rule; import javax.swing.JComponent; /** * * @author Entokwaa */ public class CustomerContactPresentationExt_RULE extends CustomerContact_RULE { @Override public void runOnClick(JComponent comp) { super.runOnClick(comp); if (comp.getName().equals("btnTodayCallPresentation")) { displayToday("PRESENTATION"); } else if (comp.getName().equals("btnWeekCallPresentation")) { displayThisWeek("PRESENTATION"); } } }
true
2ca53c17fc026272306b27c1cfb7630c097c3ddb
Java
OlimpiadaFDI/Servicios
/OlimpiadaFDIModel/src/main/java/com/fdi/olimpiada/integration/persistence/entity/Insignias.java
UTF-8
1,725
2.40625
2
[ "Apache-2.0" ]
permissive
package com.fdi.olimpiada.integration.persistence.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.fdi.olimpiada.commons.persistence.DomainObject; /** * * @author agonzalez * */ @Entity @Table(name = "INSIGNIAS") public class Insignias implements DomainObject,java.io.Serializable { // Fields private static final long serialVersionUID = 1L; private Integer idInsignia; private String descCorta; private String descLarga; private Integer puntuacion; // Constructors /** default constructor */ public Insignias() { } /** full constructor */ public Insignias(Integer idInsignia,String descCorta,String descLarga,Integer puntuacion) { this.idInsignia = idInsignia; this.descCorta = descCorta; this.descLarga = descLarga; this.puntuacion = puntuacion; } // Property accessors @Id @Column(name = "ID_INSIGNIA", unique = true, nullable = false) public Integer getIdInsignia() { return this.idInsignia; } public void setIdInsignia(Integer idInsignia) { this.idInsignia = idInsignia; } @Column(name = "DESC_CORTA", nullable = false) public String getDescCorta() { return this.descCorta; } public void setDescCorta(String descCorta) { this.descCorta = descCorta; } @Column(name = "DESC_LARGA", nullable = false) public String getDescLarga() { return this.descLarga; } public void setDescLarga(String descLarga) { this.descLarga = descLarga; } @Column(name = "PUNTUACION", unique = true, nullable = false) public Integer getPuntuacion() { return this.puntuacion; } public void setPuntuacion(Integer puntuacion) { this.puntuacion = puntuacion; } }
true
7c4434ed25ea290a53f786c723cbc1520b1681ff
Java
GandhiTC/SeleniumTestSnippets
/src/test/java/com/github/GandhiTC/java/SeleniumTestSnippets/code/Tables_Dynamic.java
UTF-8
10,696
2.484375
2
[]
no_license
package com.github.GandhiTC.java.SeleniumTestSnippets.code; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.text.DecimalFormat; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; public class Tables_Dynamic { private static WebDriver driver; private static String pageURL1 = "https://finance.yahoo.com/gainers", pageURL2 = "https://demo.guru99.com/test/table.html"; private static int numRows = -1, numCols = -1, curFails = 0, maxFails = 10; public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./src/test/resources/Drivers/chromedriver.exe"); driver = new ChromeDriver(); System.out.println("\r\n"); moveBrowserRight(); driver.get(pageURL1); getNumOfRowsAndCols(); getByRowAndColNums(3, 3); getMaxPercentChanged(); getNumOfCells(); driver.close(); } public static void getNumOfRowsAndCols() { // Number of columns List<WebElement> cols = driver.findElements(By.xpath("//table//tr[1]/th")); System.out.println("Num of cols : " + cols.size()); // Number of rows List<WebElement> rows = driver.findElements(By.xpath("//table/tbody//tr/td[1]")); System.out.println("Num of rows : " + rows.size()); // Verify number of rows String rowsSelection = driver.findElement(By.xpath("//table//parent::div/following-sibling::div[1]/span/div/span/span")).getText(); int firstSpace = rowsSelection.indexOf(" "); int lastSpace = rowsSelection.lastIndexOf(" "); String actualRows = rowsSelection.substring(firstSpace, lastSpace).trim(); int expectedRows = Integer.parseInt(actualRows); System.out.println("Actual rows : " + actualRows); if(rows.size() == expectedRows) { System.out.println("\r\nNumber of rows counted correctly.\r\n\r\n"); } else { System.err.println("\r\nCounted rows does not match actual rows.\r\n\r\n"); } numRows = expectedRows; numCols = cols.size(); } public static void getByRowAndColNums(int numOfRow, int numOfCol) { // Make sure class variables are set first if((numRows == -1) || (numCols == -1)) { getNumOfRowsAndCols(); } // Make sure supplied parameters are within valid ranges numOfRow = Math.max(numOfRow, 1); numOfCol = Math.max(numOfCol, 1); numOfRow = Math.min(numOfRow, numRows); numOfCol = Math.min(numOfCol, numCols); // Get row and cell WebElements final WebElement bod = driver.findElement(By.xpath("//table/tbody")); final WebElement row = bod.findElement(By.xpath(".//tr[" + numOfRow + "]")); final WebElement col = row.findElement(By.xpath(".//td[" + numOfCol + "]")); // Row Option 1 - Easy single liner, but ugly to look at // String rowText = row.getText().replaceAll("\r", "\t").replaceAll("\n", "\t"); // System.out.println("Row content : " + rowText); // Row Option 2 - Add bigger spaces between each string final List<WebElement> cols = row.findElements(By.xpath(".//td")); final String replacement = " "; String rowText = ""; for(WebElement eachTD : cols) { rowText += (eachTD.getText() + replacement); } // Print whole row rowText.replaceAll("\r", replacement).replaceAll("\n", replacement); System.out.println("Whole row content : " + rowText); // Print selected cell String colText = col.getText(); System.out.println("Selected cell content : " + colText + "\r\n\r\n"); } public static synchronized void getMaxPercentChanged() { curFails = 0; waitForPageToLoad(); int errorSpanCount = driver.findElements(By.xpath("//span[contains(., 'Please try reloading the page.')]")).size(); if(errorSpanCount > 0) { driver.get(pageURL1); getMaxPercentChanged(); return; } // By default, the table is sorted by "% Change", // lets re-sort by "Volume" to make sure script works correctly. clickVolumeHeaderAndWait(true); // Get row and cell WebElements double max = 0.00; final WebElement tbod = driver.findElement(By.xpath("//table/tbody")); final List<WebElement> rows = tbod.findElements(By.xpath(".//tr")); List<Double> raws = updatedStringsList(rows); if(raws == null) { return; } for(int x = 0; x < raws.size(); x++) { DecimalFormat df2 = new DecimalFormat("#.00"); max = Math.max(max, raws.get(x)); System.out.println("Current val : " + df2.format(raws.get(x))); System.out.println("Max val : " + df2.format(max) + "\r\n"); } System.out.println(" "); } public static void getNumOfCells() { driver.get(pageURL2); WebElement table = driver.findElement(By.xpath("/html/body/table/tbody")); List<WebElement> rowList = table.findElements(By.tagName("tr")); int rowCount = rowList.size(); System.out.println("---------------------------------------------------- "); for(int row = 0; row < rowCount; row++) { List<WebElement> rowColsList = rowList.get(row).findElements(By.tagName("td")); int colCount = rowColsList.size(); String cells = colCount == 1 ? "cell" : "cells"; System.out.println(colCount + " " + cells + " in row " + (row + 1)); for(int col = 0; col < colCount; col++) { String celtext = rowColsList.get(col).getText(); System.out.println("[row " + (row + 1) + ", column " + (col + 1) + "] = " + celtext); } System.out.println("---------------------------------------------------- "); } } public static void clickVolumeHeaderAndWait(boolean reverseOrder) { try { // waitForPageToLoad(); // // int errorSpanCount = driver.findElements(By.xpath("//span[contains(., 'Please try reloading the page.')]")).size(); // // if(errorSpanCount > 0) // { // driver.get(pageURL1); // getMaxPercentChanged(); // return; // } // else // { int numOfClicks = reverseOrder ? 2 : 1; for(int x = 1; x <= numOfClicks; x++) { // Wait for the "Volume" header to become clickable, then click on it WebElement volumeHeader = driver.findElement(By.xpath("//table//tr[1]/th[contains(., 'Volume')]")); Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(1)) .ignoring(NoSuchElementException.class); fluentWait.until(ExpectedConditions.elementToBeClickable(volumeHeader)); Thread.sleep(500L); Actions actions = new Actions(driver); actions.moveToElement(volumeHeader).click().build().perform(); System.out.println("\"Volume\" header clicked."); } // } System.out.println(" "); } catch(StaleElementReferenceException ex) { clickVolumeHeaderAndWait(reverseOrder); } catch(InterruptedException e) { System.err.println(e.getMessage()); } } /** * Because the web page updates its data frequently, * we are likely to come across StaleElementReferenceException. * Therefore, we use a recursive method which restarts itself * only if/when it encounters the error/exception. * * @param rows A List<WebElement> representing a list of rows. */ public static List<Double> updatedStringsList(List<WebElement> rows) { List<Double> raws = new ArrayList<Double>(); boolean isFinished = false; while((curFails < maxFails) && !isFinished) { try { for(int x = 0; x < rows.size(); x++) { String raw = rows.get(x).findElement(By.xpath(".//td[5]")).getText().trim(); int idx = raw.lastIndexOf("%"); String str = raw.substring(0, idx); double val = Double.parseDouble(str); raws.add(val); } isFinished = true; } catch(StaleElementReferenceException ex) { int errorSpanCount = driver.findElements(By.xpath("//span[contains(., 'Please try reloading the page.')]")).size(); if(errorSpanCount > 0) { driver.get(pageURL1); getMaxPercentChanged(); return null; } else { curFails++; final WebElement newTBod = driver.findElement(By.xpath("//table/tbody")); final List<WebElement> newRows = newTBod.findElements(By.xpath(".//tr")); return updatedStringsList(newRows); } } finally { if(isFinished) { return raws; } else if(curFails >= maxFails) { System.err.println("Failure : " + curFails); System.err.println("Max failures reached, ending test."); return null; } else { System.err.println("Failure : " + curFails); System.err.println("isFinished : " + isFinished + "\r\n"); } } } return raws; } public static void waitForPageToLoad() { ExpectedCondition<Boolean> pageLoadCondition; Wait<WebDriver> wait; pageLoadCondition = new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { return ((JavascriptExecutor)driver) .executeScript("return document.readyState") .equals("complete"); } }; wait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(1)); wait.until(pageLoadCondition); } public static void moveBrowserRight() { // set focus on browser window JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.focus();"); try { Robot robot = new Robot(); // pressing keys robot.keyPress(KeyEvent.VK_WINDOWS); robot.keyPress(KeyEvent.VK_RIGHT); // releasing keys robot.keyRelease(KeyEvent.VK_WINDOWS); robot.keyRelease(KeyEvent.VK_RIGHT); } catch(AWTException e) { System.err.println("\r\n"+ e.getMessage() + "\r\n"); } } }
true
f73df04dd41d9cb059f16042cadd6d8ba090fae6
Java
pillik/EDDI
/xmpp-impl/src/main/java/ai/labs/xmpp/bootstrap/XmppModule.java
UTF-8
477
1.773438
2
[ "Apache-2.0" ]
permissive
package ai.labs.xmpp.bootstrap; import ai.labs.xmpp.endpoint.IXmppEndpoint; import ai.labs.runtime.bootstrap.AbstractBaseModule; import ai.labs.xmpp.endpoint.XmppEndpoint; import com.google.inject.Scopes; import lombok.extern.slf4j.Slf4j; /** * @author rpi */ @Slf4j public class XmppModule extends AbstractBaseModule { @Override protected void configure() { log.info("XMPP configure"); bind(IXmppEndpoint.class).to(XmppEndpoint.class); } }
true
4799b02f31a90ddb0332d1bed2a82dc8b534e711
Java
BT23/SeleniumJava
/src/pages/CatalogueDetails.java
UTF-8
11,081
1.859375
2
[]
no_license
package pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import pages.GlobalFunctions; public class CatalogueDetails { final WebDriver driver; GlobalFunctions objGlobalFunc; JavascriptExecutor jse; public CatalogueDetails (WebDriver driver){ this.driver = driver; //This initElements method will create all WebElements PageFactory.initElements(driver, this); objGlobalFunc = new GlobalFunctions(driver); jse = (JavascriptExecutor)driver; } /* * Page Factory - All WebElements */ @FindBy(how = How.ID, using = "txtComments") static WebElement txtComments; @FindBy(how = How.ID, using = "ddStore") static WebElement ddStore; @FindBy(how = How.ID, using = "EllipseSite") static WebElement EllipseSite; @FindBy(how = How.ID, using = "btnNewLevel1") static WebElement btnNewLevel1; @FindBy(how = How.ID, using = "txtCatalogueNo") static WebElement txtCatalogueNo; @FindBy(how = How.ID, using = "txtPartName") static WebElement txtPartName; @FindBy(how = How.ID, using = "txtStockOnHand") static WebElement txtStockOnHand; @FindBy(how = How.ID, using = "txtCostPerItem") static WebElement txtCostPerItem; @FindBy(how = How.ID, using = "txtAreaOfPlant") static WebElement txtAreaOfPlant; @FindBy(how = How.ID, using = "tbpDetails") static WebElement tbpDetails; @FindBy(how = How.ID, using = "tbpDocs") static WebElement tbpDocs; @FindBy(how = How.ID, using = "tbpSuppliers") static WebElement tbpSuppliers; @FindBy(how = How.ID, using = "tbpTransactions") static WebElement tbpTransactions; @FindBy(how = How.ID, using = "tbpAPL") static WebElement tbpAPL; @FindBy(how = How.ID, using = "bNewSupplier") static WebElement bNewSupplier; @FindBy(how = How.ID, using = "bSupplierDetails") static WebElement bSupplierDetails; @FindBy(how = How.ID, using = "bNewSupplierTab") static WebElement bNewSupplierTab; @FindBy(how = How.ID, using = "bNewStock") static WebElement bNewStock; @FindBy(how = How.ID, using = "bNewAPL") static WebElement bNewAPL; @FindBy(how = How.ID, using = "bNewCatalogue") static WebElement bNewCatalogue; @FindBy(how = How.ID, using = "ddSupplierContactID") static WebElement ddSupplierContactID; /* * Tabs click */ // Click on Details tab public void clickDetailsTab(){ objGlobalFunc.waitForClickable("tbpDetails"); tbpDetails.click(); } // Click on Suppliers tab public void clickSuppliersTab(){ objGlobalFunc.waitForClickable("tbpSuppliers"); tbpSuppliers.click(); } // Click on Docs tab public void clickDocsTab(){ objGlobalFunc.waitForClickable("tbpDocs"); tbpDocs.click(); } // Click on APL tab public void clickAPLTab(){ objGlobalFunc.waitForClickable("tbpAPL"); tbpAPL.click(); } // Click on Transactions tab public void clickTransactionsTab(){ objGlobalFunc.waitForClickable("tbpTransactions"); tbpTransactions.click(); } /* * Grid Column Listing */ public void tabOffSupplierField(){ objGlobalFunc.tabOffTheField(ddSupplierContactID); } /* * Buttons click */ /* Details tab */ // Click on New Catalogue button public void clickNewCatalogueBtn(){ objGlobalFunc.waitForClickable("bNewCatalogue"); bNewCatalogue.click(); } // Click on New Stock button public void clickNewStockBtn(){ objGlobalFunc.waitForClickable("bNewStock"); bNewStock.click(); } /* Supplier tab */ // Click on New line public void clickNewSupplierTabBtn(){ objGlobalFunc.waitForClickable("bNewSupplierTab"); bNewSupplierTab.click(); } // Click on Supplier Details button public void clickSupplierDetailsBtn(){ objGlobalFunc.waitForClickable("bSupplierDetails"); bSupplierDetails.click(); } // Click on New Supplier button public void clickNewSupplierBtn(){ objGlobalFunc.waitForClickable("bNewSupplier"); bNewSupplier.click(); } /* APL tab */ // Click on New APL button public void clickNewAPLBtn(){ objGlobalFunc.waitForClickable("bNewAPL"); bNewAPL.click(); } /* * Set values */ // Enter Comment public void enterComments(String strComments) { objGlobalFunc.waitForElement("grpCatalogueDetails2"); objGlobalFunc.setTextFieldValue(txtComments, strComments); } // Enter Store public void enterStore(String strDropDownValue) { objGlobalFunc.waitForElement("CatalogueDetailsDetailTab_StockDetailsSection"); WebElement kendoDropDown = driver.findElement(By.xpath("//div[@id='CatalogueDetailsDetailTab_StockDetailsSection']")); WebElement kendoDropDownArrow = kendoDropDown.findElement(By.cssSelector("span.k-select")); kendoDropDownArrow.click(); objGlobalFunc.waitForPresenceOfElementLocated("//div[@id='ddStore-list']"); objGlobalFunc.setKendoDropDownValue("div#ddStore-list ul#ddStore_listbox li.k-item", strDropDownValue); } // Enter Catalogue No. public void enterCatalogueNumber(String strCatalogueNumber){ objGlobalFunc.waitForElement("grpCatalogueDetails2"); objGlobalFunc.setTextFieldValue(txtCatalogueNo, strCatalogueNumber); } // Enter Part Name public void enterPartName(String strPartName){ objGlobalFunc.waitForElement("grpCatalogueDetails2"); objGlobalFunc.setTextFieldValue(txtPartName, strPartName); } // Enter Area of Plant public void enterAreaOfPlant(String strAreaOfPlant){ objGlobalFunc.waitForElement("grpCatalogueDetails2"); objGlobalFunc.setTextFieldValue(txtAreaOfPlant, strAreaOfPlant); } // Enter Stock On Hand public void enterStockOnHand(String strStockOnHand){ objGlobalFunc.waitForElement("grpCatalogueDetails2"); jse.executeScript("$('#txtStockOnHand').siblings('input:visible').focus();"); objGlobalFunc.setTextFieldValue(txtStockOnHand, strStockOnHand); } // Enter Cost Per Item public void enterCostPerItem(String strCostPerItem){ objGlobalFunc.waitForElement("grpCatalogueDetails2"); objGlobalFunc.setTextFieldValue(txtCostPerItem, strCostPerItem); } // Enter Supplier public void enterSupplier(String strSupplier){ objGlobalFunc.waitForElement("ddSupplierContactID"); objGlobalFunc.setTextFieldValue(ddSupplierContactID, strSupplier); } // Select Supplier from drop down public void selectSupplierFromDropDown(String strSupplier){ ddSupplierContactID.sendKeys(strSupplier); objGlobalFunc.waitForPresenceOfElementLocated("//div/div[@id='ddSupplierContactID-list']"); objGlobalFunc.setKendoDropDownValue("div.k-list-scroller ul#ddSupplierContactID_listbox li.k-item", strSupplier); } // Enter multiple Supplier. in Supplier tab public void enterMultipleSupplier(String strSupplier){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsSuppliersTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr")); WebElement desiredCell = rows.get(rows.size()-1).findElement(By.id("ddSupplierContactID")); desiredCell.sendKeys(strSupplier); objGlobalFunc.waitForPresenceOfElementLocated("//div[@id='ddSupplierContactID-list']"); objGlobalFunc.setKendoDropDownValue("ul#ddSupplierContactID_listbox", strSupplier); desiredCell.sendKeys(Keys.TAB); } // Enter Asset No. in APL tab public void enterAssetNo(String strAssetNo){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsAPLTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr")); WebElement desiredCell = rows.get(rows.size()-1).findElement(By.id("ddAssetID")); desiredCell.sendKeys(strAssetNo); objGlobalFunc.waitForPresenceOfElementLocated("//div[@id='ddAssetID-list']"); objGlobalFunc.setKendoDropDownValue("ul#ddAssetID_listbox", strAssetNo); desiredCell.sendKeys(Keys.TAB); } /* * Get values */ public String getCatalogueNumber() { try{ Thread.sleep(1000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } return objGlobalFunc.getTextFieldValue(txtCatalogueNo); } public String getPartName() { objGlobalFunc.waitForElement("CatalogueDetails_ContentHeaderSection"); return objGlobalFunc.getTextFieldValue(txtPartName); } public String getStockOnHandValue() { return objGlobalFunc.getTextFieldValue(txtStockOnHand); } // Get Action in Transactions tab public String getActionTransactionsTab(){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsTransactionsTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr/td[2]/div")); WebElement desiredCell = rows.get(rows.size()-1); System.out.println("Action: " + desiredCell.getText()); return desiredCell.getText(); } // Get Quantity in Transactions tab public String getQuantityTransactionsTab(){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsTransactionsTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr/td[4]")); WebElement desiredCell = rows.get(rows.size()-1); System.out.println("Quantity: " + desiredCell.getText()); return desiredCell.getText(); } // Get Account Code in Transactions tab public String getAccountCodeTransactionsTab(){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsTransactionsTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr/td[15]/div")); WebElement desiredCell = rows.get(rows.size()-1); System.out.println("Account Code: " + desiredCell.getText().toString()); return desiredCell.getText().toString(); } // Get Asset No in Transactions tab public String getAssetNoTransactionsTab(){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsTransactionsTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr/td[16]/div")); WebElement desiredCell = rows.get(rows.size()-1); System.out.println("Asset Number: " + desiredCell.getText().toString()); return desiredCell.getText().toString(); } // Get Issue To Return From in Transactions tab public String getIssueToReturnFromTransactionsTab(){ objGlobalFunc.waitForElement("UsrCtlCatalogueDetailsTransactionsTab"); List<WebElement> rows = driver.findElements(By.xpath("//table[@class='k-selectable']/tbody/tr/td[17]/div")); WebElement desiredCell = rows.get(rows.size()-1); System.out.println("Issue To Return To: " + desiredCell.getText().toString()); return desiredCell.getText().toString(); } /* * Verification */ public void verifySOHFieldEdiable() { if (objGlobalFunc.verifyTextFieldEditable(txtStockOnHand)) { System.out.println("SOH field is ediable"); } else { System.out.println("SOH field is locked up"); } } }
true
4ad0fcc6fc6524eed22cad497288064f0bf5d722
Java
sdmengchen12580/bihucj
/app/src/main/java/com/aganyun/acode/utils/ChangeActUtils.java
UTF-8
2,341
1.890625
2
[]
no_license
package com.aganyun.acode.utils; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.renderscript.BaseObj; import android.support.v4.app.ActivityCompat; /** * Created by 孟晨 on 2018/5/28. */ public class ChangeActUtils { public static void changeActivity_2_webAct(Context fromContext, Class<?> act, String keyValue1, String keyValue2) { Intent intent = new Intent(); intent.setClass(fromContext, act); intent.putExtra("title", keyValue1); intent.putExtra("weburl", keyValue2); fromContext.startActivity(intent); } public static void changeActivity_2_webShareAct(Context fromContext, Class<?> act, String keyValue1, String keyValue2, String keyValue3) { Intent intent = new Intent(); intent.setClass(fromContext, act); intent.putExtra("title", keyValue1); intent.putExtra("weburl", keyValue2); intent.putExtra("des", keyValue3); fromContext.startActivity(intent); } public static void changeActivity(Context fromContext, Class<?> act) { fromContext.startActivity(new Intent(fromContext, act)); } public static void changeToSignInActivity(Context fromContext, Class<?> act, boolean needSignIn){ Intent intent = new Intent(); intent.setClass(fromContext, act); intent.putExtra("needSignIn", needSignIn); fromContext.startActivity(intent); } public static void changeAct_withId(Context fromContext, Class<?> toClass, int id, String idKey) { Intent intent = new Intent(); intent.setClass(fromContext, toClass); intent.putExtra(idKey, id); fromContext.startActivity(intent); } //跳转应用市场列表 public static void changeToShop(Activity activity){ Intent intent=new Intent("android.intent.action.MAIN"); intent.addCategory("android.intent.category.APP_MARKET"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } }
true
2c901f86cdc11fec6e4a346d24cc8da7903067d3
Java
jwiszowata/code_reaper
/code/my-app/functions/27/saveHighScores_HighScore.java
UTF-8
1,055
2.390625
2
[]
no_license
public static boolean saveHighScores(List<HighScore> scores) { boolean ret = false; if (scores == null) return false; tidyScores(scores); File hsf = FreeColDirectories.getHighScoreFile(); try (FileOutputStream fos = new FileOutputStream(hsf); FreeColXMLWriter xw = new FreeColXMLWriter(fos, FreeColXMLWriter.WriteScope.toSave(), true)) { ret = true; xw.writeStartDocument("UTF-8", "1.0"); xw.writeStartElement(HIGH_SCORES_TAG); for (HighScore score : scores) score.toXML(xw); xw.writeEndElement(); xw.writeEndDocument(); xw.flush(); } catch (FileNotFoundException fnfe) { logger.log(Level.WARNING, "Failed to open high scores file.", fnfe); ret = false; } catch (IOException ioe) { logger.log(Level.WARNING, "Error creating FreeColXMLWriter.", ioe); ret = false; } catch (XMLStreamException xse) { logger.log(Level.WARNING, "Failed to write high scores file.", xse); ret = false; } return ret; }
true
f24c4898dc6d936335dbc8904ff1cd940db36ec0
Java
WeilerWebServices/Gradle
/db-example-large-multi-project/project19/src/main/java/org/gradle/test/performance/mediumjavamultiproject/project19/p97/Production1947.java
UTF-8
1,967
1.84375
2
[]
no_license
package org.gradle.test.performance.mediumjavamultiproject.project19.p97; public class Production1947 { private Production1944 property0; public Production1944 getProperty0() { return property0; } public void setProperty0(Production1944 value) { property0 = value; } private Production1945 property1; public Production1945 getProperty1() { return property1; } public void setProperty1(Production1945 value) { property1 = value; } private Production1946 property2; public Production1946 getProperty2() { return property2; } public void setProperty2(Production1946 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
true
cf3ae1a1a00c25830092a89b258f0a52edd290d7
Java
sb-cloud-race/sb-session
/src/main/java/io/github/sbcloudrace/sbsession/user/UserController.java
UTF-8
2,310
2.28125
2
[ "MIT" ]
permissive
package io.github.sbcloudrace.sbsession.user; import io.github.sbcloudrace.sbsession.tokensession.TokenSession; import io.github.sbcloudrace.sbsession.tokensession.TokenSessionRepository; import lombok.AllArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.Optional; import java.util.UUID; @Controller @RequestMapping(value = "/user") @AllArgsConstructor public class UserController { private final UserRepository userRepository; private final TokenSessionRepository tokenSessionRepository; @RequestMapping(value = "/{userId}", method = RequestMethod.GET) @ResponseBody public String createTemporarySession(@PathVariable long userId) { String securityToken = UUID.randomUUID().toString(); User user = new User(userId, securityToken, 15 * 60); userRepository.save(user); return securityToken; } @RequestMapping(value = "/{userId}/{token}", method = RequestMethod.GET) @ResponseBody public String createPermanentSession(@PathVariable long userId, @PathVariable String token) { return createPermanentSession(new User(userId, token, -1)).getToken(); } private User createPermanentSession(User user) { Optional<User> userById = userRepository.findById(user.getUserId()); if (userById.isPresent() && userById.get().getToken().equals(user.getToken())) { String securityToken = UUID.randomUUID().toString(); user.setToken(securityToken); user.setTimeToLive(300L); tokenSessionRepository.findById(userById.get().getToken()) .ifPresent(tokenSessionRepository::delete); userRepository.save(user); TokenSession tokenSession = new TokenSession( user.getToken(), user.getUserId(), 0L, "", 0L, 300L); tokenSessionRepository.save(tokenSession); return user; } return new User(); } }
true
160004086a0ae8567341120b13e2e6adc5b4057b
Java
rohitner/MA39011
/10/test1.java
UTF-8
1,305
3.171875
3
[]
no_license
import java.awt.*; import java.io.*; import java.lang.*; import javax.swing.*; import java.applet.*; public class test1 extends Applet { int x,y; String a = " "; public void init() { setBackground(Color.white); setForeground(Color.red); } public void paint(Graphics g) { try { BufferedReader o = new BufferedReader(new InputStreamReader(System.in)); a = o.readLine(); } catch(Exception t){} String[] arrOfStr = a.split(" ", 2); x = Integer.parseInt(arrOfStr[0]); y = Integer.parseInt(arrOfStr[1]); double a1=0,a2=0,b1=x,b2=0,c1=x,c2=x,d1=0,d2=x,t1,t2; double a1t,a2t,b1t,b2t,c1t,c2t,d1t,d2t; double side = x; int count =0; while(side>y) { System.out.println(side); g.drawLine((int)a1,(int)a2,(int)b1,(int)b2); g.drawLine((int)b1,(int)b2,(int)c1,(int)c2); g.drawLine((int)c1,(int)c2,(int)d1,(int)d2); g.drawLine((int)d1,(int)d2,(int)a1,(int)a2); g.drawOval((int)(((a1+c1)/2)-side/2),(int)(((a2+c2)/2)-side/2),(int)side,(int)side); System.out.println(count); a1t=(a1+b1)/2;a2t=(a2+b2)/2; b1t=(b1+c1)/2;b2t=(b2+c2)/2; c1t=(c1+d1)/2;c2t=(c2+d2)/2; d1t=(d1+a1)/2;d2t=(d2+a2)/2; a1=a1t;a2=a2t; b1=b1t;b2=b2t; c1=c1t;c2=c2t; d1=d1t;d2=d2t; side = Math.sqrt((((a1-b1)*(a1-b1))+((a2-b2)*(a2-b2)))); count ++; } } }
true
580f6cd52b8bd0c7449fd997140c74de7e819e9e
Java
BrunoDatoMeneses/AMOEBA3
/AMOEBAonAMAK/src/gui/DimensionSelector.java
UTF-8
2,255
2.921875
3
[]
no_license
package gui; import java.util.List; import java.util.concurrent.Semaphore; import agents.percept.Percept; import fr.irit.smac.amak.tools.RunLaterHelper; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.layout.HBox; /** * A graphical tool for selecting the dimensions to display * @author Hugo * */ public class DimensionSelector extends HBox { private ComboBox<Percept> dim1 = new ComboBox<>(); private ComboBox<Percept> dim2 = new ComboBox<>(); private EventHandler<ActionEvent> onChange; public DimensionSelector(List<Percept> percepts, EventHandler<ActionEvent> onChange) { this.setAlignment(Pos.CENTER); this.getChildren().addAll(dim1, dim2); this.onChange = onChange; this.update(percepts); } /** * Update percepts list * @param amoeba */ public void update(List<Percept> percepts) { Semaphore done = new Semaphore(0); dim1.setOnAction(null); dim2.setOnAction(null); RunLaterHelper.runLater(() -> { dim1.getItems().clear(); dim2.getItems().clear(); dim1.setItems(FXCollections.observableList(percepts)); dim2.setItems(FXCollections.observableList(percepts)); if(percepts.size() >= 2) { dim1.setValue(percepts.get(0)); dim2.setValue(percepts.get(1)); } else if (percepts.size() == 1) { dim1.setValue(percepts.get(0)); dim2.setValue(percepts.get(0)); } done.release(); }); try { done.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } dim1.setOnAction(onChange); dim2.setOnAction(onChange); } /** * Return the 1st selected dimension * @return selected percept */ public Percept d1() { return dim1.getValue(); } /** * Return the 2nd selected dimension * @return selected percept */ public Percept d2() { return dim2.getValue(); } /** * Set the handler called when selected dimension change. * @param onChange */ public void setOnChange(EventHandler<ActionEvent> onChange) { this.onChange = onChange; dim1.setOnAction(onChange); dim2.setOnAction(onChange); } }
true
f30a7282b901ecb48ea28bc12225ddc065ab93dd
Java
AmeerAyman/Cellular-Phone-Control-System
/src/cellular/phone/control/system/Receiver.java
UTF-8
2,793
2.359375
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 cellular.phone.control.system; import GUI.CellIdle; import GUI.CellOption; import GUI.CellRinging; import GUI.Idle; import GUI.InCall; import GUI.InCallCell; import GUI.MainClass; import GUI.NoSignal; import GUI.Ringing; import events.OnPressed; import java.util.ArrayList; import javax.swing.JFrame; /** * * @author omar1 */ public class Receiver { public void lostSignal() { // NoSignal s=new NoSignal(); // s.setVisible(true); MainClass.phone.getScreen().setVisible(false); MainClass.phone.getCellScreen().setVisible(false); CellOption.screenC.setVisible(false); } public void enterCall() { MainClass.phone.setCurrentState("In Call"); MainClass.phone.getScreen().setVisible(false); MainClass.phone.getCellScreen().setVisible(false); InCall window = new InCall(); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); MainClass.phone.setScreen(window); InCallCell window2 = new InCallCell(); window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window2.setVisible(true); MainClass.phone.setCellScreen(window2); } public void ringing(String recieverNumber, String senderNumber) { System.out.println("before checking number"); if (recieverNumber.equals(MainClass.phone.getNumber())) { System.out.println("Correct number0"); MainClass.phone.setCurrentState("Ringing") ; System.out.println("Correct number1"); MainClass.phone.setEnteredNumber(senderNumber); System.out.println("Correct number2"); MainClass.phone.getScreen().setVisible(false); MainClass.phone.getCellScreen().setVisible(false); System.out.println("Correct number3"); Ringing window = new Ringing(); System.out.println("Correct number4"); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); CellRinging window2 = new CellRinging(); System.out.println("Correct number4"); window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window2.setVisible(true); System.out.println("Correct number5"); window.setVisible(true); System.out.println("Correct number6"); MainClass.phone.setScreen(window); MainClass.phone.setCellScreen(window2); System.out.println("Correct number7"); } else { System.out.println("Wrong number"); } } }
true
931183dacf59ab345e1bfaf13a06ab5a23893645
Java
vinaychatraofficial/Practice
/src/epi/graph/KruskalMST.java
UTF-8
2,650
3.171875
3
[]
no_license
package epi.graph; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class KruskalMST { public static void main(String[] args) { List<Edge> edges = new ArrayList<>(); edges.add(new Edge(0,1,6)); edges.add(new Edge(0,2,8)); edges.add(new Edge(0,5,5)); edges.add(new Edge(1,2,7)); edges.add(new Edge(1,4,3)); edges.add(new Edge(1,0,6)); edges.add(new Edge(2,0,8)); edges.add(new Edge(2,1,7)); edges.add(new Edge(2,3,4)); edges.add(new Edge(3,2,4)); edges.add(new Edge(3,4,1)); edges.add(new Edge(3,5,1)); edges.add(new Edge(4,1,3)); edges.add(new Edge(4,3,1)); edges.add(new Edge(4,5,1)); edges.add(new Edge(5,0,5)); edges.add(new Edge(5,3,1)); edges.add(new Edge(5,4,1)); List<Integer> vertices = new ArrayList<>(); vertices.add(0); vertices.add(1); vertices.add(2); vertices.add(3); vertices.add(4); vertices.add(5); List<Edge> result = kruskal(edges, vertices); for(Edge edge:result) { System.out.println(edge.src+"->"+edge.dest); } } private static class Edge{ int src; int dest; int weight; public Edge(int src, int dest, int weight) { super(); this.src = src; this.dest = dest; this.weight = weight; } } private static class Subset{ int rank; int parent; } private static class EdgeComparator implements Comparator<Edge>{ @Override public int compare(Edge e1, Edge e2) { return Integer.compare(e1.weight, e2.weight); } } private static List<Edge> kruskal(List<Edge> edges, List<Integer> vertices) { Collections.sort(edges, new EdgeComparator()); Subset[] s = new Subset[vertices.size()]; List<Edge> result = new ArrayList<>(); for(int i=0;i<vertices.size();i++) { makeSet(s, i); } int count=0; for(Edge e:edges) { int xroot = find(s, e.src); int yroot = find(s, e.dest); if(count==vertices.size()-1) break; if(xroot!=yroot) { count++; result.add(e); union(e.src,e.dest,s); } } return result; } private static void union(int src, int dest, Subset[] s) { int xroot = find(s,src); int yroot = find(s,dest); if(s[xroot].rank!=s[yroot].rank) { if(s[xroot].rank>s[yroot].rank) { s[yroot].parent=xroot; }else { s[xroot].parent=yroot; } }else { s[yroot].parent=xroot; s[xroot].rank++; } } private static int find(Subset[] s, int src) { if(s[src].parent!=src) s[src].parent = find(s,s[src].parent); return s[src].parent; } private static void makeSet(Subset s[], int i) { s[i] = new Subset(); s[i].parent = i; s[i].rank = 0; } }
true
9bc4108abb4ab2de1d49f617065708620e6ce737
Java
sunilkmr5775/spring-boot-card-management
/src/test/java/com/mbanq/banksystem/CardControllerIntegrationTest.java
UTF-8
7,135
2.109375
2
[ "Apache-2.0" ]
permissive
package com.mbanq.banksystem; import com.mbanq.banksystem.dto.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.JacksonJsonParser; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; /** * * CardControllerIntegrationTest includes * * 1. shouldNotAllowAccessToUnauthenticatedUsers * 2. testListCardByConsumer * 3. testDetailCard * 4. activateShouldBeReturnOK * 5. deactivateShouldBeReturnOK * 6. changeDailyLimitShouldBeReturnOK * * * ***/ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class CardControllerIntegrationTest { @Autowired MockMvc mvc; @Autowired private WebApplicationContext wac; private String token; private static final String AUTH_SIGN_IN = "/v1/api/auth/signin"; private static final String URL_CARD_LIST = "/v1/api/card/list"; private static final String URL_CARD_DETAIL = "/v1/api/card/detail"; private static final String URLCARD_ACTIVATE = "/v1/api/card/activate"; private static final String UR_CARD_DEACTIVATE = "/v1/api/card/deactivate"; private static final String URL_CARD_DAILY_LIMIT = "/v1/api/card/daily-limit"; private static final Long cardID = 5L; @Before public void setUp() { DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac); this.mvc = builder.build(); // Signup AuthSignInRequest request = new AuthSignInRequest(); request.setPhoneNumber("093883292"); request.setPassword("123456"); try { token = signInAndGetAccessToken(request); } catch (Exception e) { e.printStackTrace(); } assertThat(token).isNotNull(); token = "Bearer "+ token; } @Test public void shouldNotAllowAccessToUnauthenticatedUsers() throws Exception { ResultMatcher forbidden = MockMvcResultMatchers.status() .isForbidden(); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(URL_CARD_LIST); this.mvc.perform(builder) .andExpect(forbidden); } @Test public void testListCardByConsumer() throws Exception { assertThat(token).isNotNull(); ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(URL_CARD_LIST) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .header("Authorization", token); this.mvc.perform(builder) .andExpect(ok); } @Test public void testDetailCard() throws Exception { assertThat(token).isNotNull(); ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); // request CardDetailRequest request = new CardDetailRequest(); request.setId(cardID); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get(URL_CARD_DETAIL) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .content(IntegrationTestUtil.convertObjectToJsonBytes(request)) .header("Authorization", token); this.mvc.perform(builder) .andExpect(ok); } @Test public void activateShouldBeReturnOK() throws Exception { assertThat(token).isNotNull(); ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); // request CardActivateRequest request = new CardActivateRequest(); request.setId(cardID); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(URLCARD_ACTIVATE) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .content(IntegrationTestUtil.convertObjectToJsonBytes(request)) .header("Authorization", token); this.mvc.perform(builder) .andExpect(ok); } @Test public void deactivateShouldBeReturnOK() throws Exception { assertThat(token).isNotNull(); ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); // request CardDeactivateRequest request = new CardDeactivateRequest(); request.setId(cardID); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(UR_CARD_DEACTIVATE) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .content(IntegrationTestUtil.convertObjectToJsonBytes(request)) .header("Authorization", token); this.mvc.perform(builder) .andExpect(ok); } @Test public void changeDailyLimitShouldBeReturnOK() throws Exception { assertThat(token).isNotNull(); ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); // request CardDailyLimitRequest request = new CardDailyLimitRequest(); request.setId(cardID); request.setDailyLimit(3000.00); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.put(URL_CARD_DAILY_LIMIT) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .content(IntegrationTestUtil.convertObjectToJsonBytes(request)) .header("Authorization", token); this.mvc.perform(builder) .andExpect(ok); } private String signInAndGetAccessToken(AuthSignInRequest request) throws Exception { ResultMatcher ok = MockMvcResultMatchers.status() .isOk(); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(AUTH_SIGN_IN) .content(IntegrationTestUtil.convertObjectToJsonBytes(request)) .contentType(IntegrationTestUtil.APPLICATION_JSON_UTF8) .accept("application/json;charset=UTF-8"); ResultActions result = this.mvc.perform(builder) .andExpect(ok); String resultString = result.andReturn().getResponse().getContentAsString(); JacksonJsonParser jsonParser = new JacksonJsonParser(); return jsonParser.parseMap(resultString).get("token").toString(); } }
true
ab65befa6716b20403843095fa02036632352de8
Java
moutainhigh/cms
/cms-biz/src/main/java/com/ymkj/cms/biz/service/apply/impl/ReturnedLoanBoxServiceImpl.java
UTF-8
1,227
1.890625
2
[]
no_license
package com.ymkj.cms.biz.service.apply.impl; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ymkj.base.core.biz.common.PageBean; import com.ymkj.base.core.biz.common.PageParam; import com.ymkj.base.core.biz.dao.BaseDao; import com.ymkj.base.core.biz.service.BaseServiceImpl; import com.ymkj.cms.biz.dao.apply.IReturnedLoanBoxDao; import com.ymkj.cms.biz.entity.apply.LoanBaseEntity; import com.ymkj.cms.biz.entity.apply.ReturnedLoanBoxSearchEntity; import com.ymkj.cms.biz.service.apply.IReturnedLoanBoxService; @Service public class ReturnedLoanBoxServiceImpl extends BaseServiceImpl<ReturnedLoanBoxSearchEntity> implements IReturnedLoanBoxService{ @Autowired private IReturnedLoanBoxDao iReturnedLoanBoxDao; @Override protected BaseDao<ReturnedLoanBoxSearchEntity> getDao() { return iReturnedLoanBoxDao; } @Override public PageBean<ReturnedLoanBoxSearchEntity> search(PageParam pageParam, Map<String, Object> paramMap) { return iReturnedLoanBoxDao.listPage(pageParam, paramMap); } @Override public int queryMessageCount(Map<String,Object> paramMap) { return iReturnedLoanBoxDao.getCount(paramMap); } }
true
50c294ecb84c396538248f0fafe5781abf2250bc
Java
ardyputra/1441180066TugasPBO
/Tugas 3/testlaptop.java
UTF-8
1,014
2.515625
3
[]
no_license
class testLaptop { public static void main(String[] args) { laptop akbar = new laptop(); System.out.println("warna=" +akbar.getwarna()); System.out.println("merk=" +akbar.getmerk()); System.out.println("wifi=" +akbar.getwifi()); System.out.println("batrai=" +akbar.getbaterai()); System.out.println(" "); laptop reza = new laptop("Acer","Ungu"); System.out.println("warna=" +reza.getwarna()); System.out.println("merk=" +reza.getmerk()); System.out.println(" "); laptop dan = new laptop("Thosiba","merah","Koneksi"); System.out.println("warna=" +dan.getwarna()); System.out.println("merk=" +dan.getmerk()); System.out.println("wifi=" +dan.getwifi()); System.out.println(""); laptop ardy = new laptop("Lenovo","Merah","Tak tersambung",70); System.out.println("warna=" +ardy.getwarna()); System.out.println("merk=" +ardy.getmerk()); System.out.println("wifi=" +ardy.getwifi()); System.out.println("batrai=" +ardy.getbaterai()); System.out.println(" "); } }
true
6376c46c25765b89f0bbdccdd9aa32cca48e6db6
Java
zentaury/SpringBootDemoApi
/src/main/java/com/mybooking/catalogservice/repositories/CatalogDbRepository.java
UTF-8
1,788
2.578125
3
[]
no_license
package com.mybooking.catalogservice.repositories; import com.mybooking.catalogservice.domain.entities.Author; import com.mybooking.catalogservice.domain.entities.Book; import com.mybooking.catalogservice.domain.entities.Category; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; @Service public class CatalogDbRepository { public List<Book> getBookInfoByCategoryName(JdbcTemplate connector, String categoryName) throws SQLException { List<Book> books = connector.query("SELECT book.name AS book_name, category.Name category_name, author.Name AS author_name, book.price FROM book \n" + "INNER JOIN category ON book.Category_Id = category.id \n" + "INNER JOIN author ON book.Author_Id = author.id " + "WHERE category.Name=\"" + categoryName + "\"", new RowMapper<Book>() { public Book mapRow(ResultSet rs, int rowNum) throws SQLException { Book book = new Book(); Author author = new Author(); author.setName(rs.getString("author_name")); Category category = new Category(); category.setName(rs.getString("category_name")); book.setAuthor(author); book.setName(rs.getString("book_name")); book.setCategory(category); book.setPrice(rs.getDouble("price")); return book; } } ); return books; } }
true
49a84730fcdf84b8d859fe9ad78f049c423465c3
Java
TommyTeaVee/Pano360
/app/src/main/java/org/cyanogenmod/focal/widgets/BurstModeWidget.java
UTF-8
4,138
1.960938
2
[]
no_license
package org.cyanogenmod.focal.widgets; import android.content.res.Resources; import android.hardware.Camera; import android.view.View; import org.cyanogenmod.focal.CameraActivity; import org.cyanogenmod.focal.feats.BurstCapture; import fr.xplod.focal.R; /** * Burst-shooting mode widget */ public class BurstModeWidget extends WidgetBase implements View.OnClickListener { private WidgetOptionButton mBtnOff; private WidgetOptionButton mBtn5; private WidgetOptionButton mBtn10; private WidgetOptionButton mBtn15; private WidgetOptionButton mBtnInf; private WidgetOptionButton mPreviousMode; private CameraActivity mCameraActivity; private BurstCapture mTransformer; private final static String DRAWABLE_TAG = "nemesis-burst-mode"; public BurstModeWidget(CameraActivity activity) { super(activity.getCamManager(), activity, R.drawable.ic_widget_burst); mCameraActivity = activity; // Create options // XXX: Move that into an XML mBtnOff = new WidgetOptionButton(R.drawable.ic_widget_burst_off, activity); mBtn5 = new WidgetOptionButton(R.drawable.ic_widget_burst_5, activity); mBtn10 = new WidgetOptionButton(R.drawable.ic_widget_burst_10, activity); mBtn15 = new WidgetOptionButton(R.drawable.ic_widget_burst_15, activity); mBtnInf = new WidgetOptionButton(R.drawable.ic_widget_burst_inf, activity); getToggleButton().setHintText(R.string.widget_burstmode); final Resources res = getWidget().getResources(); mBtn5.setHintText(String.format(res.getString(R.string.widget_burstmode_count_shots), 5)); mBtn10.setHintText(String.format(res.getString(R.string.widget_burstmode_count_shots), 10)); mBtn15.setHintText(String.format(res.getString(R.string.widget_burstmode_count_shots), 15)); mBtnOff.setHintText(R.string.widget_burstmode_off); mBtnInf.setHintText(R.string.widget_burstmode_infinite); addViewToContainer(mBtnOff); addViewToContainer(mBtn5); addViewToContainer(mBtn10); addViewToContainer(mBtn15); addViewToContainer(mBtnInf); mBtnOff.setOnClickListener(this); mBtn5.setOnClickListener(this); mBtn10.setOnClickListener(this); mBtn15.setOnClickListener(this); mBtnInf.setOnClickListener(this); mPreviousMode = mBtnOff; mPreviousMode.activeImage(DRAWABLE_TAG + "=off"); mTransformer = new BurstCapture(activity); } @Override public boolean isSupported(Camera.Parameters params) { // Burst mode is supported by everything. If we are in photo mode that is. if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_PHOTO) { return true; } else { return false; } } @Override public void onClick(View view) { mPreviousMode.resetImage(); if (view == mBtnOff) { // Disable the transformer mCameraActivity.setCaptureTransformer(null); mBtnOff.activeImage(DRAWABLE_TAG + "=off"); mPreviousMode = mBtnOff; } else if (view == mBtn5) { mTransformer.setBurstCount(5); mCameraActivity.setCaptureTransformer(mTransformer); mBtn5.activeImage(DRAWABLE_TAG + "=5"); mPreviousMode = mBtn5; } else if (view == mBtn10) { mTransformer.setBurstCount(10); mCameraActivity.setCaptureTransformer(mTransformer); mBtn10.activeImage(DRAWABLE_TAG + "=10"); mPreviousMode = mBtn10; } else if (view == mBtn15) { mTransformer.setBurstCount(15); mCameraActivity.setCaptureTransformer(mTransformer); mBtn15.activeImage(DRAWABLE_TAG + "=15"); mPreviousMode = mBtn15; } else if (view == mBtnInf) { // Infinite burst count mTransformer.setBurstCount(0); mCameraActivity.setCaptureTransformer(mTransformer); mBtnInf.activeImage(DRAWABLE_TAG + "=inf"); mPreviousMode = mBtnInf; } } }
true
8900902601febf8d27765cf0e9cfa1537b6ecf5a
Java
hyprd/spindle
/COMP160/S2/Lab18/TrafficLightPanel.java
UTF-8
3,257
3.671875
4
[]
no_license
/**COMP160 lab 18 - TrafficLightPanel.java - Ethan Simmonds - September 2016*/ import javax.swing.*; import java.awt.event.*; import java.awt.*; public class TrafficLightPanel extends JPanel { //data field declarations private JButton red, amber, green; private JLabel drawButtonPanel,pressPanel; private JPanel buttonPanel; /** This constructor creates and sets the size plus color of the frame objects, aswell as adding every object into the visible frame*/ public TrafficLightPanel(){ //create the LightPanel object LightPanel light = new LightPanel(); //create objects for traffic lights, frame labels aswell as a panel background for the buttons red = new JButton("Red"); amber = new JButton("Amber"); green = new JButton("Green"); drawButtonPanel = new JLabel("Button Panel"); pressPanel = new JLabel("last pressed"); buttonPanel = new JPanel(); buttonPanel.setPreferredSize(new Dimension(80,290)); buttonPanel.setBackground(Color.white); //create a listener object and bin them to each traffic light object, so that the buttons can perform an action on click ButtonListener listener = new ButtonListener(); red.addActionListener(listener); amber.addActionListener(listener); green.addActionListener(listener); //set the size and colour of TrafficLightPanel setPreferredSize(new Dimension(200,300)); setBackground(Color.blue); //create an instance of each object, visible on the frame buttonPanel.add(drawButtonPanel); buttonPanel.add(red); buttonPanel.add(amber); buttonPanel.add(green); add(buttonPanel); add(light); } /** This private class contains action logic when each button is pressed*/ private class ButtonListener implements ActionListener{ public void actionPerformed(ActionEvent event){ if (event.getSource() == red){ pressPanel.setText("red"); } else if (event.getSource() == amber){ pressPanel.setText("amber"); } else if (event.getSource() == green){ pressPanel.setText("green"); } repaint(); } } /** Once a button is pressed, this private class recolours the given traffic light by retrieving the value of the pressPanel object*/ private class LightPanel extends JPanel{ /** Method to set the colour and size of the panel which the button objects are placed*/ public LightPanel(){ setPreferredSize(new Dimension(80,290)); setBackground(Color.cyan); } /** Initially, this method will set the colour of the button objects to black. * Once an action is performed on any button, check the value of pressPanel and adjust accordingly*/ public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.black); g.fillOval(20,50,40,40); g.setColor(Color.black); g.fillOval(20,150,40,40); g.setColor(Color.black); g.fillOval(20,100,40,40); if (pressPanel.getText().equals("red")){ g.setColor(Color.red); g.fillOval(20,50,40,40); } else if (pressPanel.getText().equals("amber")){ g.setColor(Color.orange); g.fillOval(20,100,40,40); } else if (pressPanel.getText().equals("green")){ g.setColor(Color.green); g.fillOval(20,150,40,40); } } } }
true
d2287448f78f9221c56d697db01e0b8e03f501fc
Java
Spectrum3847/Robot-Ultraviolet
/Ultraviolet/src/subsystems/Camera.java
UTF-8
2,509
2.6875
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package subsystems; import driver.AutoAim; import driver.CamData; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * * @author root */ public class Camera extends Subsystem { // Put methods for controlling this subsystem // here. Call these from Commands. private int[] points; private CamData data; private static final boolean DEBUG = true; public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void connect(){ data = new CamData("10.38.47.133","8882"); SmartDashboard.putBoolean("Camera Running",true); } public void disconnect(){ try{ CamData.disconnect(); }catch(NullPointerException e){ System.out.println("No instance running"); } SmartDashboard.putBoolean("Camera Running",false); } public String getRaw(){ return CamData.receiveRaw(); } public int[] getData(){ return CamData.parseCamData(CamData.receiveRaw()); } public String toString(){ String str = ""; int[] data = getData(); for(int i = 0;i < data.length;i++){ str+=data[i] + "|"; } return str; } public double getDistance(){ if (isConnected() && points != null){ return AutoAim.getDistance(points); } else { return 9999; } } public double getOffset(){ if (isConnected() && points != null){ return AutoAim.getOffsetAngle(points); } else { return 9999; } } public double getRangeLow(){ if(isConnected() && points != null){ return AutoAim.getRangeLow(points); } else{ return 9999; } } public double getRangeHigh(){ if(isConnected() && points != null){ return AutoAim.getRangeHigh(points); } else{ return 9999; } } public void update(){ points = getData(); } public boolean isConnected(){ return CamData.isConnected(); } }
true
2a1364f7efeb7ec60e206441614e5e54eaa0ce58
Java
katpb/spark-mongo-test
/pankaj/SparkExamples/transent/src/com/verifone/isd/vsms2/sales/ent/trans/LoyaltyProgramDetails.java
UTF-8
2,105
2.59375
3
[]
no_license
package com.verifone.isd.vsms2.sales.ent.trans; import com.verifone.isd.vsms2.sys.util.MoneyAmount; /** * Value object to capture the loyalty program details from transaction needed * for transaction XML serialization. There will be one such entry for each * loyalty program applicable to the transaction. * * @author Anindya_D1 * */ public class LoyaltyProgramDetails { private String programName; // customer friendly loyalty program name private MoneyAmount autoDiscount = new MoneyAmount(0); // automatic ticket discount private MoneyAmount custDiscount = new MoneyAmount(0); // customer choice ticket discount private LoyaltyAuthDetails authDetail; // site level loyalty authorization details, when available public String getProgramName() { return programName; } public void setProgramName(String programName) { this.programName = programName; } public MoneyAmount getAutoDiscount() { return autoDiscount; } public void setAutoDiscount(MoneyAmount autoDiscount) { if (autoDiscount != null) { this.autoDiscount = autoDiscount.abs(); } } public MoneyAmount getCustDiscount() { return custDiscount; } public void setCustDiscount(MoneyAmount custDiscount) { if (custDiscount != null) { this.custDiscount = custDiscount.abs(); } } public LoyaltyAuthDetails getAuthDetail() { return authDetail; } public void setAuthDetail(LoyaltyAuthDetails authDetail) { this.authDetail = authDetail; } /** * Accumulate multiple automatic ticket level discounts from the same * loyalty program into a single entry at the transaction level program * detail. * * @param discount */ public void addAutoDiscount(MoneyAmount discount) { this.autoDiscount.add(discount.abs()); } /** * Accumulate multiple customer choice ticket level discounts from the same * loyalty program into a single entry at the transaction level program * detail * * @param discount */ public void addCustDiscount(MoneyAmount discount) { this.custDiscount.add(discount.abs()); } }
true
1b85cbb8fbb5da08403d47706ddb7bdd2b9b547d
Java
apoorv9990/Tribal-Scale
/app/src/test/java/com/tribalscale/ExampleUnitTest.java
UTF-8
4,569
2.296875
2
[]
no_license
package com.tribalscale; import com.tribalscale.models.Person; import com.tribalscale.network.CoreApi; import com.tribalscale.network.responses.GetPersonsResponse; import com.tribalscale.presenters.MainPresenter; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import java.io.IOException; import java.util.Collections; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.android.plugins.RxAndroidPlugins; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import io.reactivex.internal.schedulers.ExecutorScheduler; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { CoreApi apiService; GetPersonsResponse getPersonsResponse; private MainPresenter mainPresenter; private MainPresenter.MainView mView; @BeforeClass public static void setUpSuite() { final Scheduler immediate = new Scheduler() { @Override public Worker createWorker() { return new ExecutorScheduler.ExecutorWorker(new Executor() { @Override public void execute(@android.support.annotation.NonNull Runnable runnable) { runnable.run(); } }); } }; RxJavaPlugins.setInitIoSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { return immediate; } }); RxJavaPlugins.setInitComputationSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { return immediate; } }); RxJavaPlugins.setInitNewThreadSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { return immediate; } }); RxJavaPlugins.setInitSingleSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { return immediate; } }); RxAndroidPlugins.setInitMainThreadSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { return immediate; } }); } @AfterClass public static void tearDownSuite() { RxJavaPlugins.reset();; } @Before public void setUp() { apiService = mock(CoreApi.class); getPersonsResponse = mock(GetPersonsResponse.class); mView = mock(MainPresenter.MainView.class); mainPresenter = new MainPresenter(apiService); } @Test public void checkSuccessfulApiCall() throws IOException { when(apiService.getPersons(20)).thenReturn(Observable.just(getPersonsResponse)); mainPresenter.attachView(mView); mainPresenter.getPersons(); verify(mainPresenter.getView(), times(1)).showPersons(Collections.<Person>emptyList()); verify(mainPresenter.getView(), times(0)).showError(); } @Test public void checkErrorCall() throws IOException { when(apiService.getPersons(20)).thenReturn(Observable.<GetPersonsResponse>error(new IOException())); mainPresenter.attachView(mView); mainPresenter.getPersons(); verify(mainPresenter.getView(), times(1)).showError(); verify(mainPresenter.getView(), times(0)).showPersons(Collections.<Person>emptyList()); } }
true
b22c19eaf60dcaec0f5fe6afddf3c0c23b44dc9f
Java
seanbethard/ptkmodel
/ptkModel2/src/perceptron/ERC.java
UTF-8
2,132
3.109375
3
[]
no_license
package perceptron; public class ERC { private Candidate winner; private Candidate loser; private double[] learningVector; private LinguisticForm input; private ERC equivalentTo; private boolean accountedFor = false; public final static int E = 0; public final static int W = 1; public final static int L = -1; public Candidate getWinner() { return this.winner; } public Candidate setWinner(Candidate cand) { return this.winner = cand; } public Candidate getLoser() { return this.loser; } public Candidate setLoser(Candidate cand) { return this.loser = cand; } public LinguisticForm getInput() { return this.input; } public LinguisticForm setInput(LinguisticForm form) { return this.input = form; } public double[] getLearningVector() { return this.learningVector; } public double[] setLearningVector(double[] lv) { return this.learningVector = lv; } public boolean hasL() { boolean success = false; for (int i = 0; i < this.getLearningVector().length; i++) { if (this.getLearningVector()[i] == ERC.L) { success = true; break; } } return success; } public boolean hasW() { boolean success = false; for (int i = 0; i < this.getLearningVector().length; i++) { if (this.getLearningVector()[i] == ERC.W) { success = true; break; } } return success; } public boolean amountsTo(ERC erc) { boolean identical = true; if (this.getLearningVector().length == erc.getLearningVector().length) { for (int i = 0; i < this.getLearningVector().length; i++) { if (this.getLearningVector()[i] != erc.getLearningVector()[i]) identical = false; } } else { identical = false; } return identical; } public boolean setAccountedFor(boolean bool) { return this.accountedFor = bool; } public boolean isAccountedFor() { return this.accountedFor; } public ERC getEquivalent() { return this.equivalentTo; } public void setEquivalent(ERC erc) { this.equivalentTo = erc; } public String toString() { String str = this.getWinner().getOutput() + " ~ " + this.getLoser().getOutput(); return str; } }
true
9b782e303cf0d151c4af7eced4f3517231cf0328
Java
PiotrWtr/tuner
/src/HighFrequencyAnalyser.java
UTF-8
782
3.234375
3
[]
no_license
public class HighFrequencyAnalyser extends FrequencyAnalyser { double frequency = 0; double analyse(double[] signal, double samplingRate){ int zeros = 0; for (int i = 0; i < signal.length - 1; i++) { if (signal[i] <= 0 && signal[i + 1] > 0) { zeros++; } if (signal[i] >= 0 && signal[i + 1] < 0) { zeros++; } } double signalLength = signal.length / samplingRate; //in [s] frequency = ((zeros)/2) / signalLength; //System.out.println("Zeros: " + zeros); //System.out.print((100 - Math.abs((signal.sinFrequency - frequency)/ frequency)*100) + " ");//"Accuracy of high freq analyser:" + return frequency; } }
true
b8af29509f7b962703010c435d19a589ed523e76
Java
cash2one/ionic
/hsbank_cms/doc/易宝文档/易宝接口/JAVA/src/com/yeepay/server/ServerInfo.java
UTF-8
636
1.96875
2
[]
no_license
package com.yeepay.server; public class ServerInfo { private static String PageCharsetName = "gbk"; private static String ServerCharsetName = "iso-8859-1"; private static String YeepayCharsetName = "gbk"; public static String getPageCharsetName(){ return PageCharsetName; } public static void setPageCharsetName(String charsetName){ PageCharsetName = charsetName; } public static String getServerCharsetName(){ return ServerCharsetName; } public static void setServerCharsetName(String charsetName){ ServerCharsetName = charsetName; } public static String getYeepayCharsetName(){ return YeepayCharsetName; } }
true
3b2a193614c0e3495a6992f641d9d861d1e464f8
Java
mihigh/android-cycling
/android/src/org/mihigh/cycling/app/pe/route/GetUserHelpRunnable.java
UTF-8
4,533
2
2
[]
no_license
package org.mihigh.cycling.app.pe.route; import android.app.AlertDialog; import android.content.DialogInterface; import android.support.v4.app.FragmentActivity; import com.google.gson.reflect.TypeToken; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.mihigh.cycling.app.R; import org.mihigh.cycling.app.Utils; import org.mihigh.cycling.app.filter.ExceptionHandler; import org.mihigh.cycling.app.group.dto.Coordinates; import org.mihigh.cycling.app.http.HttpHelper; import org.mihigh.cycling.app.login.dto.UserInfo; import org.mihigh.cycling.app.pe.route.ui.PE_UI_MapFragment; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; public class GetUserHelpRunnable implements Runnable { private static final String PATH_CREATE_GROUP = "/api/v1/message/help/activity/1"; private final FragmentActivity activity; private PE_UI_MapFragment map; public GetUserHelpRunnable(FragmentActivity activity, PE_UI_MapFragment map) { this.activity = activity; this.map = map; } @Override public void run() { String url = activity.getString(R.string.server_url) + PATH_CREATE_GROUP; try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpCall = new HttpGet(url); // Auth headers httpCall.addHeader("Cookie", Utils.SESSION_ID + " = " + HttpHelper.session); httpCall.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpCall.setHeader(Utils.EMAIL, UserInfo.restore(activity) == null ? null : UserInfo.restore(activity).getEmail()); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpCall); // Check if response if (response.getStatusLine().getStatusCode() > 300) { throw new IOException("Received " + response.getStatusLine().getStatusCode()); } BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String responseBody = reader.readLine(); Type listType = new TypeToken<List<HelpRequest>>() { }.getType(); final List<HelpRequest> helpRequests = HttpHelper.getGson().fromJson(responseBody, listType); final List<AlertDialog.Builder> allAlerts = new ArrayList<AlertDialog.Builder>(); for (final HelpRequest helpRequest : helpRequests) { AlertDialog.Builder alert = new AlertDialog.Builder(activity); allAlerts.add(alert); final int index = helpRequests.indexOf(helpRequest); alert.setTitle(helpRequest.userInfo.getEmail()); alert.setMessage("Need help: " + helpRequest.text); alert.setPositiveButton("Show on map", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { map.openMarker(helpRequest.userInfo, helpRequest.lastLocation); } }); alert.setNegativeButton("Cancel All", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.setNeutralButton("Next", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { AlertDialog.Builder alert = allAlerts.size() == index + 1 ? null : allAlerts.get(index + 1); if (alert != null) { alert.show(); } } }); } if (!allAlerts.isEmpty()) { activity.runOnUiThread(new Runnable() { @Override public void run() { allAlerts.get(0).show(); } }); } } catch (Exception e) { new ExceptionHandler(activity).sendError(e, false); } } } class HelpRequest { public UserInfo userInfo; public Coordinates lastLocation; public String text; }
true
54e001ced1f13d0297e438c80a395ff5b6cd8bf9
Java
sflorezs1/Lab3
/Final Solution/src/Vertex.java
UTF-8
1,092
3.359375
3
[]
no_license
public class Vertex <E> { private int head = 0; private E data; private Vertex[] neighbors = new Vertex[8]; private boolean visited; private int level; public Vertex(E data) { this.data = data; } public Vertex(E data, int level) { this.data = data; this.level = level; } public void addNeighbor(Vertex<E> neighbor) { this.neighbors[this.head] = neighbor; this.head++; } public int neighborsSize() { return this.head + 1; } public E getData() { return data; } public void setData(E data) { this.data = data; } public Vertex[] getNeighbors() { return neighbors; } public void setNeighbors(Vertex[] neighbors) { this.neighbors = neighbors; } public boolean isVisited() { return visited; } public void setVisited(boolean visited) { this.visited = visited; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } }
true
4e675d0ace6f11aa11edb595eb865aa1691c5237
Java
lxllxllxs/AndroidWebSocket
/src/com/lxl/im/utils/EnumUtil.java
UTF-8
177
1.671875
2
[]
no_license
package com.lxl.im.utils; public class EnumUtil { public static enum MessageType{ Login,TextMessage,ImageMessage,RedPocketMessage,AddFriendMessage,LinkMan; } }
true
90b6a64e001bc892d5a3c8243deb5fe1ff877259
Java
jonnypjohnston/Microsoft-SimpleWeather-Android
/shared_resources/src/main/java/com/thewizrd/shared_resources/controls/SunPhaseViewModel.java
UTF-8
1,834
2.53125
3
[ "Apache-2.0" ]
permissive
package com.thewizrd.shared_resources.controls; import android.text.format.DateFormat; import com.thewizrd.shared_resources.DateTimeConstants; import com.thewizrd.shared_resources.SimpleLibrary; import com.thewizrd.shared_resources.utils.DateTimeUtils; import com.thewizrd.shared_resources.weatherdata.Astronomy; import java.time.format.DateTimeFormatter; public class SunPhaseViewModel { private final String sunrise; private final String sunset; private final DateTimeFormatter formatter; public SunPhaseViewModel(Astronomy astronomy) { if (DateFormat.is24HourFormat(SimpleLibrary.getInstance().getApp().getAppContext())) { formatter = DateTimeUtils.ofPatternForInvariantLocale(DateTimeConstants.CLOCK_FORMAT_24HR); } else { formatter = DateTimeUtils.ofPatternForInvariantLocale(DateTimeConstants.CLOCK_FORMAT_12HR_AMPM); } sunrise = astronomy.getSunrise().format(formatter); sunset = astronomy.getSunset().format(formatter); } public String getSunrise() { return sunrise; } public String getSunset() { return sunset; } public DateTimeFormatter getFormatter() { return formatter; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SunPhaseViewModel that = (SunPhaseViewModel) o; if (sunrise != null ? !sunrise.equals(that.sunrise) : that.sunrise != null) return false; return sunset != null ? sunset.equals(that.sunset) : that.sunset == null; } @Override public int hashCode() { int result = sunrise != null ? sunrise.hashCode() : 0; result = 31 * result + (sunset != null ? sunset.hashCode() : 0); return result; } }
true
598b325e758681fab93ba65bd24f28b00e9250ee
Java
TanayaKarmakar/ds_algo
/leetcode/src/com/app/questions/tree/BinarySearchTreeToDLLLeetcode426.java
UTF-8
1,222
3.375
3
[]
no_license
package com.app.questions.tree; public class BinarySearchTreeToDLLLeetcode426 { static class Node { public int val; public Node left; public Node right; public Node() {} public Node(int _val) { val = _val; } public Node(int _val,Node _left,Node _right) { val = _val; left = _left; right = _right; } }; static Node prev; static Node head; private static void convertRec(Node root) { if(root == null) return; convertRec(root.left); if(prev == null) { head = root; } else { prev.right = root; root.left = prev; } prev = root; convertRec(root.right); } private static Node treeToDoublyLinkedList(Node root) { if(root == null) return null; head = null; prev = null; convertRec(root); head.left = prev; prev.right = head; return head; } public static void main(String[] args) { Node root = new Node(4); root.left = new Node(2); root.right = new Node(5); root.left.left = new Node(1); root.left.right = new Node(3); Node head = treeToDoublyLinkedList(root); Node temp = head; while(temp != null) { System.out.print(temp.val + " "); temp = temp.right; } } }
true
122a67bff1c1f56fb54cd9262cb5353c6d17bd1d
Java
LuisFelipeJorge/POO-JAVA-USP
/Loja/src/Loja.java
UTF-8
4,292
3.140625
3
[]
no_license
public class Loja { private Produto[] produtos; private int capacidade; private int quantidadeDeProdutos; private Estoque estoque; public Loja() { this.capacidade = 100; this.produtos = new Produto[this.capacidade]; this.estoque = new Estoque(); } public Loja(int capacidade) { this.capacidade = capacidade; this.produtos = new Produto[this.capacidade]; this.estoque = new Estoque(); } public Produto[] getProdutos() { return produtos; } public int getCapacidade() { return capacidade; } public int getQuantidadeDeProdutos() { return quantidadeDeProdutos; } public boolean adicionarProdutos(Produto produto) { if(this.quantidadeDeProdutos < capacidade) { int posicao = this.buscarPosicaoPorNome(produto.getNome()); if(posicao > 0) { this.produtos[posicao].increaseAvailableQuantity(produto.getAvailableQuantity()); estoque.adicionarAoEstoque(produto, produto.getAvailableQuantity()); }else { this.produtos[this.quantidadeDeProdutos++] = produto; estoque.adicionarAoEstoque(produto, produto.getAvailableQuantity()); } return true; } return false; } public boolean adicionarProdutos(Produto[] produtosNovos) { if(this.quantidadeDeProdutos < capacidade) { int i = 0; while (this.quantidadeDeProdutos < capacidade && i < produtosNovos.length) { int posicao = this.buscarPosicaoPorNome(produtosNovos[i].getNome()); if(posicao > 0) { this.produtos[posicao].increaseAvailableQuantity(produtosNovos[i].getAvailableQuantity()); estoque.adicionarAoEstoque(produtosNovos[i], produtosNovos[i].getAvailableQuantity()); }else { this.produtos[this.quantidadeDeProdutos++] = produtosNovos[i]; estoque.adicionarAoEstoque(produtosNovos[i], produtosNovos[i].getAvailableQuantity()); } i++; } if(i == produtos.length) return true; } return false; } public Produto buscar(String nome) { int posicao = buscarPosicaoPorNome(nome); if(posicao > 0) { return this.produtos[posicao]; } return null; } public Produto buscar(int codigoDeBarra) { int posicao = buscarPosicaoPorCodigo(codigoDeBarra); if(posicao > 0) { return this.produtos[posicao]; } return null; } private int buscarPosicaoPorNome(String nome) { for (int i = 0; i < this.capacidade; i++) { if(this.produtos[i] != null && this.produtos[i].getNome().equals(nome)) { return i; } } return -1; } private int buscarPosicaoPorCodigo(int codigo) { for (int i = 0; i < this.capacidade; i++) { if(this.produtos[i] != null && this.produtos[i].getCodigoDeBarras() == codigo) { return i; } } return -1; } public boolean vender(int codigoDeBarras) { int posicao = buscarPosicaoPorCodigo(codigoDeBarras); if(posicao < 0) return false; if (this.produtos[posicao].decreaseAvailableQuantity()) { estoque.removerDoEstoque(this.produtos[posicao], 1); if(this.produtos[posicao].getAvailableQuantity() == 0) { this.produtos[posicao] = null; } return true; } return false; } public boolean vender(int codigoDeBarras, int amount) { int posicao = buscarPosicaoPorCodigo(codigoDeBarras); if (this.produtos[posicao].decreaseAvailableQuantity(amount)) { estoque.removerDoEstoque(this.produtos[posicao], amount); if(this.produtos[posicao].getAvailableQuantity() == 0) { this.produtos[posicao] = null; } return true; } return false; } public String obterEstoque() { String resultado = ""; resultado += "Livros:" + "\n" +"Dísponiveis: " + estoque.getQuantidaeDeLivros() + "\n"; for(Produto produto : produtos) { if (produto instanceof Livro) { resultado += produto; } } resultado += "\n" + "CDs:" + "\n" +"Dísponiveis: " + estoque.getQuantidadeDeCds() + "\n"; for(Produto produto : produtos) { if (produto instanceof CD) { resultado += produto; } } resultado += "\n" + "DVDs:" + "\n" +"Dísponiveis: " + estoque.getQuantidadeDeDvds() + "\n"; for(Produto produto : produtos) { if (produto instanceof Dvd) { resultado += produto; } } return resultado; } @Override public String toString() { String resultado = ""; for (Produto produto : this.produtos) { if(produto != null) { resultado += produto; } } return resultado; } }
true
41aab1c8f51a5296f5e3ab449b88171cb1955fc3
Java
wyg0405/springboot-demo
/rabbitmq/src/main/java/com/wyg/rabbitmq/javaclient/exchange/direct/ConsumeLogDirect.java
UTF-8
1,872
2.671875
3
[]
no_license
package com.wyg.rabbitmq.javaclient.exchange.direct; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.rabbitmq.client.*; /** * 消费产生的日志 * * @author wyg0405@gmail.com * @date 2019-11-16 17:06 * @since JDK1.8 * @version V1.0 */ public class ConsumeLogDirect { private static final String HOST = "wyginfo.cn"; private static final int PORT = 5672; private static final String USERNAME = "wyg"; private static final String PASSWORD = "fHn8RLOOFXPFkIF0"; private static final String EXCHANGE_NAME = "test04"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost(HOST); factory.setPort(PORT); factory.setUsername(USERNAME); factory.setPassword(PASSWORD); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); String exchangeType = "direct"; channel.exchangeDeclare(EXCHANGE_NAME, exchangeType); // 获取队列名 String queueName = channel.queueDeclare().getQueue(); // 不同获取routingKey,并对应队列与交换机绑定 for (String arg : args) { String routingKey = arg; channel.queueBind(queueName, EXCHANGE_NAME, routingKey); } DeliverCallback deliverCallback = new DeliverCallback() { @Override public void handle(String consumerTag, Delivery delivery) throws IOException { String message = new String(delivery.getBody(), "UTF-8"); System.out.println("routingKey:" + delivery.getEnvelope().getRoutingKey() + ",message:" + message); } }; channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { }); } }
true
92bac8f34db56c4b977153bc2be0ea003eccbeec
Java
Mittemi/WMPM_SS15
/code/src/main/java/carrental/MongoDbConfiguration.java
UTF-8
1,059
2.125
2
[]
no_license
package carrental; import com.mongodb.Mongo; import com.mongodb.MongoClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; /** * Created by Michael on 13.05.2015. */ @Configuration /* One time only: docker run --name mongo -d -v /mongo -p 27017:27017 -p 28017:28017 -e AUTH=no tutum/mongodb Start: docker start mongo Stop: docker stop mongo */ public class MongoDbConfiguration extends AbstractMongoConfiguration { @Autowired private CarRentalConfig carRentalConfig; @Override public String getDatabaseName() { return carRentalConfig.getPickupPoint().getMongo().getName(); } @Override @Bean public Mongo mongo() throws Exception { //return new MongoClient(properties.getMongoDBConf().getIpOrHostname()); return new MongoClient(carRentalConfig.getPickupPoint().getMongo().getHost()); } }
true
e739d180479d89e6e79bcf8c561ed3c27948c5aa
Java
learnwithuma/Java-8
/src/DateAndTimeAPIExample.java
UTF-8
1,119
3.484375
3
[]
no_license
// Lambda Expression and Collections import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; class DateAndTimeAPIExample { public static void main(String[] args) { LocalDate ld = LocalDate.now(); LocalTime lt = LocalTime.now(); LocalDateTime ldt = LocalDateTime.now(); System.out.println(ld); System.out.println(lt); System.out.println(ldt); System.out.println(ld.getDayOfMonth()); System.out.println(ld.getMonthValue()); System.out.println(ld.getYear()); System.out.println(lt.getHour()); System.out.println(lt.getMinute()); System.out.println(lt.getSecond()); LocalDateTime ldt1 = LocalDateTime.of(1988, 01, 01, 0, 0, 0, 0); System.out.println(ldt1); ldt1.plusDays(10); ldt1.minusDays(5); Period p = Period.between(ld, ld.plusDays(10)); System.out.println(p.getDays()); System.out.println(ZoneId.systemDefault()); ZoneId ca = ZoneId.of("America/Los_Angeles"); ZonedDateTime zt = ZonedDateTime.now(ca); System.out.println(zt.now()); } }
true
e6e354bc8ba7382ba9f63098b5de6b8a59771e38
Java
ElephantWithCode/ComearnApp
/wang_part/src/main/java/com/example/team/wang/engine/fragment/class_main/ClassMainFragment.java
UTF-8
6,489
2
2
[]
no_license
package com.example.team.wang.engine.fragment.class_main; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.team.wang_part.R; import com.example.team.wang.receiver.UpdateCountDownReceiver; import com.example.team.wang.service.CountDownService; import com.example.team.comearnlib.utils.ToastTools; import cn.iwgang.countdownview.CountdownView; public class ClassMainFragment extends Fragment implements ClassMainView, UpdateCountDownReceiver.OnReceiveListener { public static final String TAG = "CMF"; private TextView mStateTv; private TextView mQuitBtn; private CountdownView mCountDownView; private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { /* CountDownService.CountDownBinder binder = (CountDownService.CountDownBinder) service; CountDownService countDownService = binder.getService(); */ } @Override public void onServiceDisconnected(ComponentName name) { } }; private UpdateCountDownReceiver mReceiver; private ClassMainPresenter mPresenter = new ClassMainPresenter(); private static final String TAG_ON_CLASS = "on_class"; private boolean mOnClassState; private static final String TAG_STOP_TIME = "stop_time"; private long mStopTime; public static ClassMainFragment newInstance(boolean isOnclass, long stopTime) { Bundle args = new Bundle(); args.putBoolean(TAG_ON_CLASS, isOnclass); args.putLong(TAG_STOP_TIME, stopTime); ClassMainFragment fragment = new ClassMainFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { Bundle args = getArguments(); if (args != null){ mOnClassState = args.getBoolean(TAG_ON_CLASS, true); mStopTime = args.getLong(TAG_STOP_TIME); } mPresenter.attachView(this); mPresenter.saveStopTime(); mReceiver = new UpdateCountDownReceiver() .setListener(this); mReceiver.setmAction("update_count_time"); getActivity().registerReceiver(mReceiver, new IntentFilter("update_count_time")); getActivity().bindService(new Intent(getActivity(), CountDownService.class), mConnection, Context.BIND_AUTO_CREATE); super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_class_main, container, false); mCountDownView = view.findViewById(R.id.frag_class_main_cv_count); mCountDownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() { @Override public void onEnd(CountdownView cv) { // onCountDownEnd(); } }); mQuitBtn = view.findViewById(R.id.frag_class_main_btn_quit); mQuitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "quit button clicked"); if (getContext() != null) { new Handler().postDelayed(new Runnable() { @Override public void run() { if (ClassMainFragment.this.getActivity() != null) { mPresenter.mModel.saveFromQuitBtn(true); getContext().sendBroadcast(new Intent("start_count_down")); ToastTools.showToast(ClassMainFragment.this.getContext(), "管理员结束课堂"); ClassMainFragment.this.getActivity().finish(); } } }, 300); } } }); mStateTv = view.findViewById(R.id.frag_class_main_tv_show_state); mPresenter.refreshClassStateTv(mPresenter.getClassState()); mPresenter.startCountDown(); /* Calendar instance = Calendar.getInstance(); instance.setTimeInMillis(timeInMillis); Log.d(TAG, instance.toString()); instance.setTimeInMillis(mStopTime); Log.d(TAG, " " + instance.toString()); */ return view; } @Override public void onDestroy() { mPresenter.detachView(); getActivity().unregisterReceiver(mReceiver); getActivity().unbindService(mConnection); super.onDestroy(); } @Override public void startCountDown(long miliseconds) { mCountDownView.start(miliseconds); } @Override public long getStopTime(){ return mStopTime; } @Override public void refreshClassStateTv(boolean state) { if (state){ mStateTv.setText("距离课堂结束还有:"); mQuitBtn.setVisibility(View.VISIBLE); }else { mStateTv.setText("距离上课还有:"); mQuitBtn.setVisibility(View.INVISIBLE); } } public void onCountDownEnd(boolean state) { if (mPresenter.getClassState()){ // mPresenter.saveClassState(false); mPresenter.refreshClassStateTv(true); mPresenter.startCountDown(); }else { // mPresenter.saveClassState(true); mPresenter.refreshClassStateTv(false); ToastTools.showToast(getContext(), "倒计时结束"); } } @Override public boolean getClassState() { return mOnClassState; } @Override public void onReceive() { mPresenter.refreshClassStateTv(mPresenter.getClassState()); mPresenter.startCountDown(); } public ClassMainPresenter getPresenter(){ return mPresenter; } }
true
081f84180cfc434b20a683874c03c8a7d80401d5
Java
kprochazka/ass-2015
/server/src/main/java/ass/prochka6/InvalidRequestException.java
UTF-8
677
2.53125
3
[]
no_license
package ass.prochka6; /** * Parsing or general invalid request exception, translated by HttpProtocolHandler to HttpResponse with given Status. * * @author Kamil Prochazka */ class InvalidRequestException extends RuntimeException { private static final long serialVersionUID = 6569838532917408380L; private final Status status; public InvalidRequestException(Status status, String message) { super(message); this.status = status; } public InvalidRequestException(Status status, String message, Exception e) { super(message, e); this.status = status; } public Status getStatus() { return this.status; } }
true
e1f94f521330fab13a927d5e1e951ef6c8a65013
Java
michael041/bank-accounts-program
/SavingsAccount.java
UTF-8
961
3.203125
3
[]
no_license
package bankaccounts; public class SavingsAccount extends Account { public SavingsAccount(){ super(); //uses no-arg constructor of the super class } public SavingsAccount(Depositor dp, int an, String tp, double ba, String s){ super(dp,an,tp,ba,s); //uses parameterized constructor of the super class } public SavingsAccount(Account savings){ super(savings); } public int withdraws(double withdrawAmount) { if (withdrawAmount <= 0) { return 0; } else if (withdrawAmount > getBalance()) { return 1; } else { setBalance(getBalance()-withdrawAmount); } return 2; } public int deposits(double amountDeposit) { if (amountDeposit <= getBalance()) { return 0; } else { setBalance(getBalance()+amountDeposit); return 1; } } }
true
0517116d915772d8bc0e4088eec75fa881dbc666
Java
srcdeps/srcdeps-core
/srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java
UTF-8
2,506
2.359375
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.core.config.tree; import java.util.List; import java.util.Stack; import org.srcdeps.core.config.tree.walk.DefaultsAndInheritanceVisitor; import org.w3c.dom.NodeList; /** * The base interface for configuration tree nodes. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public interface Node { /** * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set * explicitly. See also {@link DefaultsAndInheritanceVisitor}. * * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. */ void applyDefaultsAndInheritance(Stack<Node> configurationStack); /** * @return a list of comment lines that should appear before this node */ List<String> getCommentBefore(); /** * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in * case this {@link Node} is an element of a {@link NodeList}. */ String getName(); /** * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. * * @param source the {@link Node} to take the values from */ void init(Node source); /** * @param stack the ancestor hierarchy of this {@link Node} * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the * instance or implementation specific default state. Otherwise returns {@code false} */ boolean isInDefaultState(Stack<Node> stack); /** * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise * returns {@code false} */ boolean shouldEscapeName(); }
true
80aa3a549cd37157902544795cf3f4049b0dd706
Java
Andy----/OOSAD2
/week11/src/CreateOrmtestData.java
UTF-8
1,060
2.640625
3
[]
no_license
/** * Licensee: Institute of Technology Tallaght * License Type: Academic */ import org.orm.*; public class CreateOrmtestData { public void createTestData() throws PersistentException { PersistentTransaction t = OrmtestPersistentManager.instance().getSession().beginTransaction(); try { Employee employee = EmployeeDAO.createEmployee(); employee.setName("Jim McGee"); employee.setPPS("HFGH54654"); employee.setAddress("132 sdfgdfgd"); employee.setYearsService(10); employee.setAge(50); EmployeeDAO.save(employee); Sales sales = SalesDAO.createSales(); sales.setTotalSales(100); sales.setFinancialYear("2010"); SalesDAO.save(sales); t.commit(); } catch (Exception e) { t.rollback(); } } public static void main(String[] args) { try { CreateOrmtestData createOrmtestData = new CreateOrmtestData(); try { createOrmtestData.createTestData(); } finally { OrmtestPersistentManager.instance().disposePersistentManager(); } } catch (Exception e) { e.printStackTrace(); } } }
true
3294e6d994b0c698ded7e080c2cbec5f13b9ab86
Java
Aayush67/SpringBootTodoWebApp
/src/main/java/com/project/springbootwebapp/SpringbootwebappApplication.java
UTF-8
453
1.679688
2
[]
no_license
package com.project.springbootwebapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication //@ComponentScan("com.project.springbootwebappp") public class SpringbootwebappApplication { public static void main(String[] args) { SpringApplication.run(SpringbootwebappApplication.class, args); } }
true
858a29f0f31887b4b7ed182a4a4e885546ad0dbf
Java
danghieu/dulich2009
/ dulich2009/CODE/Travel/src/com/ptit/travel/beans/SerializableBean.java
UTF-8
380
2.03125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ptit.travel.beans; import java.io.Serializable; /** * * @author D05CNPM */ public interface SerializableBean extends Serializable{ /** * combine all the attributes of Object into a string message * @return */ public String toMsg(); }
true
8bca1281ca61d29ca9f36b579e36871388f61364
Java
weston100721/wonderful-spring-boot
/src/main/java/info/zhaoliang/wonderful/exception/BusinessException.java
UTF-8
2,304
2.671875
3
[ "MIT" ]
permissive
package info.zhaoliang.wonderful.exception; /** * 业务异常. */ public class BusinessException extends RuntimeException { private static final long serialVersionUID = -3982645755980473694L; /** * 错误描述. */ private String msg; /** * 错误代码. */ private String code; /** * 构造方法. */ public BusinessException() { super(); } /** * 构造方法. * * @param resultCode the detail message. */ public BusinessException(IErrorCode resultCode) { super(resultCode.getMsg()); this.code = resultCode.getCode(); this.msg = resultCode.getMsg(); } /** * 构造方法. * * @param cause the cause. (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) */ public BusinessException(Throwable cause) { super(cause); } /** * 构造方法. * * @param resultCode the detail message. * @param cause the cause. (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) */ public BusinessException(IErrorCode resultCode, Throwable cause) { super(resultCode.getMsg(), cause); this.code = resultCode.getCode(); this.msg = resultCode.getMsg(); } /** * 构造方法. * * @param resultCode the detail message. * @param cause the cause. (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.) * @param enableSuppression whether or not suppression is enabled or disabled * @param writableStackTrace whether or not the stack trace should be writable */ public BusinessException(IErrorCode resultCode, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(resultCode.getMsg(), cause, enableSuppression, writableStackTrace); this.code = resultCode.getCode(); this.msg = resultCode.getMsg(); } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
true
321bafcc8369b8c2072a66ccca1e2d97411425a1
Java
datanucleus/tests
/jpa/TCK_1.0/src/com/sun/ts/tests/ejb30/persistence/query/flushmode/Client.java
UTF-8
81,928
1.679688
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * @(#)Client.java 1.13 06/04/17 */ package com.sun.ts.tests.ejb30.persistence.query.flushmode; import com.sun.javatest.Status; import com.sun.ts.lib.harness.*; import com.sun.ts.tests.ejb30.common.helper.TLogger; import com.sun.ts.tests.ejb30.persistence.common.PMClientBase; import com.sun.ts.tests.common.vehicle.ejb3share.EntityTransactionWrapper; import com.sun.ts.tests.ejb30.persistence.query.language.schema30.*; import com.sun.ts.tests.ejb30.persistence.query.language.Util; import java.util.Properties; import java.util.List; import java.util.Iterator; import java.util.Arrays; import java.util.Collection; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Vector; import javax.persistence.PersistenceException; import javax.persistence.Query; import javax.persistence.FlushModeType; public class Client extends PMClientBase { public static final int CUSTOMERREF = 1; public static final int ORDERREF = 2; public static final int ALIASREF = 3; public static final int PRODUCTREF = 4; public static final int NUMOFCUSTOMERS = 20; public static final int NUMOFORDERS = 20; public static final int NUMOFALIASES = 30; public static final int NUMOFALLPRODUCTS = 38; public static final int NUMOFPRODUCTS = 18; public static final int NUMOFSWPRODUCTS = 10; public static final int NUMOFHWPRODUCTS = 10; public static final int NUMOFADDRESSES = 36; public static final int NUMOFHOMEADDRESSES = 18; public static final int NUMOFWORKADDRESSES = 18; public static final int NUMOFPHONES = 36; public static final int NUMOFCREDITCARDS = 24; public static final int NUMOFLINEITEMS = 56; public static final int NUMOFSPOUSES = 6; public static final int NUMOFINFODATA = 6; public static final int NUMOFCOUNTRIES = 20; public static Phone phone[] = new Phone[50]; public static Address address[] = new Address[50]; public static Country country[] = new Country[50]; public static CreditCard creditCard[] = new CreditCard[50]; public static LineItem lineItem[] = new LineItem[60]; public static Spouse spouse[] = new Spouse[6]; public static Info info[] = new Info[6]; private static Customer customerRef[] = new Customer[50]; private static Order orderRef[] = new Order[50]; private static Alias aliasRef[] = new Alias[50]; private static Product productRef[] = new Product[50]; private static HardwareProduct hardwareRef[] = new HardwareProduct[20]; private static SoftwareProduct softwareRef[] = new SoftwareProduct[20]; private static ShelfLife shelfRef[] = new ShelfLife[20]; public static final Date d1 = getShelfDate(2000, 2, 14); public static final Date d2 = getShelfDate(2001, 6, 27); public static final Date d3 = getShelfDate(2002, 7, 7); public static final Date d4 = getShelfDate(2003, 3, 3); public static final Date d5 = getShelfDate(2004, 4, 10); public static final Date d6 = getShelfDate(2005, 2, 18); public static final Date d7 = getShelfDate(2000, 9, 17); public static final Date d8 = getShelfDate(2001, 11, 14); public static final Date d9 = getShelfDate(2002, 10, 4); public static final Date d10 = getShelfDate(2003, 1, 25); private static Properties props = null; private static List aliasCol = null; private static List custCol = null; private static List orderCol = null; private static List prodCol = null; public Client() { } public static void main(String[] args) { Client theTests = new Client(); Status s = theTests.run(args, System.out, System.err); s.exit(); } /* Test setup */ public void setup(String[] args, Properties p) throws Fault { TLogger.log("Entering Setup"); try { super.setup(args, p); schema30Setup(p); } catch (Exception e) { TLogger.log("Exception caught in Setup: " + e.getMessage()); throw new Fault("Setup failed:", e); } } public void cleanup() throws Fault { try { if ( getEntityTransaction().isActive() ) { getEntityTransaction().rollback(); } } catch (Exception re) { TLogger.log("Unexpection Exception in cleanup:" + re ); re.printStackTrace(); } //schemaExists = true; TLogger.log("cleanup ok, calling super.cleanup"); super.cleanup(); } /* Run test */ /* * @testName: flushModeTest1 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query accessing a simple field * The following updates the name of a customer and then executes an * EJBQL query selecting customers having the updated name. * */ public void flushModeTest1() throws Fault { boolean pass = true; String expectedPKs[] = null; List c = null; try { getEntityTransaction().begin(); TLogger.log("Starting flushModeTest1"); Customer cust1 = getEntityManager().find(Customer.class, "1"); cust1.setName("Michael Bouschen"); c = getEntityManager().createQuery( "SELECT c FROM Customer c WHERE c.name = 'Michael Bouschen'") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[1]; expectedPKs[0] ="1"; if (!Util.checkEJBs(c, CUSTOMERREF, expectedPKs) ) { TLogger.log("ERROR: Did not get expected results. Expected 1 references, got: " + c.size()); pass = false; } else { Customer newCust = getEntityManager().find(Customer.class, "1"); if ( newCust.getName().equals("Michael Bouschen") ) { pass = true; } TLogger.log("Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e) { TLogger.log("Caught exception flushModeTest1: " + e); throw new Fault( "flushModeTest1 failed", e); } if (!pass) throw new Fault( "flushModeTest1 failed"); } /* * @testName: flushModeTest2 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query navigating a single-valued relationship. * The following updates the customer relationship of an order. It then * executes an EJBQL query selecting orders where the related customer * has the name of the customer used in the setCustomer call. * */ public void flushModeTest2() throws Fault { boolean pass = true; String expectedPKs[] = null; try { getEntityTransaction().begin(); TLogger.log("Execute Starting flushModeTest2"); Order o1 = getEntityManager().find(Order.class, "1"); Customer cust2 = getEntityManager().find(Customer.class, "2"); o1.setCustomer(cust2); List result = getEntityManager().createQuery( "SELECT o FROM Order o WHERE o.customer.name = 'Arthur D. Frechette'") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[2]; expectedPKs[0] ="1"; expectedPKs[1] ="2"; if(!Util.checkEJBs(result, ORDERREF, expectedPKs)) { TLogger.log("ERROR: Did not get expected results. Expected 2 references, got: " + result.size() ); pass = false; } else { TLogger.log( "Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e) { TLogger.log("Caught exception flushModeTest2: " + e); throw new Fault( "flushModeTest2 failed", e); } if (!pass) throw new Fault( "flushModeTest2 failed"); } /* * @testName: flushModeTest3 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query navigating a single-valued relationship. * The following updates the name of a customer. It then executes an * EJBQL query selecting orders where the related customer has the * updated name. */ public void flushModeTest3() throws Fault { boolean pass = true; String expectedPKs[] = null; List o = null; try { getEntityTransaction().begin(); TLogger.log("Execute Starting flushModeTest3"); Customer cust1 = getEntityManager().find(Customer.class, "1"); cust1.setName("Michael Bouschen"); o = getEntityManager().createQuery( "SELECT o FROM Order o WHERE o.customer.name = 'Michael Bouschen'") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[1]; expectedPKs[0] = "1"; if(!Util.checkEJBs(o, ORDERREF, expectedPKs)) { TLogger.log( "ERROR: Did not get expected results. Expected 1 reference, got: " + o.size()); pass = false; } else { Customer newCust = getEntityManager().find(Customer.class, "1"); if ( newCust.getName().equals("Michael Bouschen") ) { pass = true; } TLogger.log("Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e) { TLogger.log("Caught exception flushModeTest3: " + e); throw new Fault( "flushModeTest3 failed", e); } if (!pass) throw new Fault( "flushModeTest3 failed"); } /* * @testName: flushModeTest4 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query navigating multiple single-valued relationships * The following updates the spouse relationship of a customer. It then * executes an EJBQL query selecting orders where the spouse of * the related customer has the name of the new spouse. * */ public void flushModeTest4() throws Fault { boolean pass = true; String expectedPKs[] = null; try { getEntityTransaction().begin(); TLogger.log("Execute Starting flushModeTest4"); Customer cust6 = getEntityManager().find(Customer.class, "6"); Spouse s4 = getEntityManager().find(Spouse.class, "4"); cust6.setSpouse(s4); getEntityManager().merge(cust6); s4.setCustomer(cust6); getEntityManager().merge(s4); List result = getEntityManager().createQuery( "SELECT o FROM Order o WHERE o.customer.spouse.lastName = 'Mullen'") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[1]; expectedPKs[0] ="6"; if(!Util.checkEJBs(result, ORDERREF, expectedPKs)) { TLogger.log("ERROR: Did not get expected results. Expected " + " 2 references, got: " + result.size() ); pass = false; } else { TLogger.log( "Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e){ TLogger.log("Caught exception flushModeTest4: " + e); throw new Fault( "flushModeTest4 failed", e); } if (!pass) throw new Fault( "flushModeTest4 failed"); } /* * @testName: flushModeTest5 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query navigating multiple single-valued relationships * The following updates the name of a spouse. It then executes an EJBQL * query selecting orders where the related spouse of the related * customer has the updated name. */ public void flushModeTest5() throws Fault { boolean pass = true; String expectedPKs[] = null; try { getEntityTransaction().begin(); TLogger.log("Starting flushModeTest5"); Spouse s4 = getEntityManager().find(Spouse.class, "4"); s4.setLastName("Miller"); List result = getEntityManager().createQuery( "SELECT o FROM Order o WHERE o.customer.spouse.lastName = 'Miller'") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[1]; expectedPKs[0] ="11"; if(!Util.checkEJBs(result, ORDERREF, expectedPKs)) { TLogger.log("ERROR: Did not get expected results. Expected " + " 1 reference, got: " + result.size() ); pass = false; } else { TLogger.log("Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e) { TLogger.log("Caught exception flushModeTest5: " + e); throw new Fault( "flushModeTest5 failed", e); } if (!pass) throw new Fault( "flushModeTest5 failed"); } /* * @testName: flushModeTest6 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query navigating a collection-valued relationship * The following removes an order from the customer's orders * relationship. It then executes an EJBQL query selecting customers * having an order with the removed number. */ public void flushModeTest6() throws Fault { boolean pass = true; String expectedPKs[] = null; try { getEntityTransaction().begin(); TLogger.log("Starting flushModeTest6"); Customer cust4 = getEntityManager().find(Customer.class, "4"); Order order4 = getEntityManager().find(Order.class, "4"); Order order9 = getEntityManager().find(Order.class, "9"); order9.setCustomer(cust4); getEntityManager().merge(order9); order4.setCustomer(null); getEntityManager().merge(order4); Vector<Order> orders = new Vector<Order>(); orders.add(order9); cust4.setOrders(orders); getEntityManager().merge(cust4); List result = getEntityManager().createQuery( "SELECT c FROM Customer c JOIN c.orders o where o.id = '4' ") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[0]; if(!Util.checkEJBs(result, CUSTOMERREF, expectedPKs)) { TLogger.log("ERROR: Did not get expected results. Expected " + " 0 references, got: " + result.size() ); pass = false; } else { TLogger.log("Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e) { TLogger.log("Caught exception flushModeTest6: " + e); throw new Fault( "flushModeTest6 failed", e); } if (!pass) throw new Fault( "flushModeTest6 failed"); } /* * @testName: flushModeTest7 * @assertion_ids: PERSISTENCE:JAVADOC:173 * @test_Strategy: Query navigating a single-valued and a collection-valued relationship * The following changes the number of a credit card. * It then executes an EJBQL query selecting a spouse whose customer * has an order with an credit card having the new number. */ public void flushModeTest7() throws Fault { boolean pass = true; String expectedPKs[] = null; List c = null; try { getEntityTransaction().begin(); TLogger.log("Starting flushModeTest7"); CreditCard c17 = getEntityManager().find(CreditCard.class, "17"); c17.setNumber("1111-1111-1111-1111"); List result = getEntityManager().createQuery( "SELECT s FROM Spouse s JOIN s.customer c JOIN c.orders o " + "WHERE o.creditCard.number = '1111-1111-1111-1111'") .setFlushMode(FlushModeType.AUTO) .getResultList(); expectedPKs = new String[1]; expectedPKs[0] ="2"; if( ! (result.size() == 1 )) { TLogger.log("ERROR: Did not get expected results. Expected " + " 1 reference, got: " + result.size() ); pass = false; } else { TLogger.log( "Expected results received"); } getEntityTransaction().rollback(); } catch (Exception e) { TLogger.log("Caught exception flushModeTest7: " + e); throw new Fault( "flushModeTest7 failed", e); } if (!pass) throw new Fault( "flushModeTest7 failed"); } /* * * Setup for EJB QL Tests * */ public void schema30Setup(Properties p) throws Exception { TLogger.log("Entering Schema 3.0 Setup"); try { props = p; TLogger.log( "Check if Schema already exists in Persistent Storage"); if(SchemaAlreadyExists()) return; TLogger.log("Create Schema Data"); createSchemaData(p); TLogger.log("Set Relationships"); createRelationships(); TLogger.log("Done creating Schema in Persistent Storage"); TLogger.log("Exiting setup . . ."); } catch (Exception e) { if ( getEntityTransaction().isActive() ) { getEntityTransaction().rollback(); } RemoveSchemaData(); e.printStackTrace(); throw new Exception("Exception occurred in Schema 3.0 setup: " + e); } finally { try { if ( getEntityTransaction().isActive() ) { getEntityTransaction().rollback(); } } catch (Exception re) { TLogger.log("Unexpection Exception in cleanup:" + re ); re.printStackTrace(); } } } private boolean SchemaAlreadyExists() throws Exception { getEntityTransaction().begin(); TLogger.log("SchemaAlreadyExists"); boolean schemaExists = true; TLogger.log("Invoke findAllCustomers"); custCol = getEntityManager().createQuery( "Select DISTINCT Object(c) From Customer c") .setMaxResults(NUMOFCUSTOMERS) .getResultList(); TLogger.log("Invoke findAllProducts"); prodCol = getEntityManager().createQuery( "Select DISTINCT Object(p) From Product p") .setMaxResults(NUMOFALLPRODUCTS+20) .getResultList(); TLogger.log("Invoke findAllOrders"); orderCol = getEntityManager().createQuery( "Select DISTINCT Object(o) From Order o") .setMaxResults(NUMOFORDERS+20) .getResultList(); TLogger.log("Invoke findAllAliases"); aliasCol = getEntityManager().createQuery( "Select DISTINCT Object(a) From Alias a") .setMaxResults(NUMOFALIASES) .getResultList(); if(custCol.size() != NUMOFCUSTOMERS || prodCol.size() != NUMOFALLPRODUCTS || orderCol.size() != NUMOFORDERS || aliasCol.size() != NUMOFALIASES) { TLogger.log("Number of customers found = " + custCol.size()); TLogger.log("Number of products found = " + prodCol.size()); TLogger.log("Number of orders found = " + orderCol.size()); TLogger.log("Number of aliases found = " + aliasCol.size()); schemaExists = false; } getEntityTransaction().commit(); if(schemaExists) { TLogger.log("Schema already exists in Persistent Storage"); return true; } else { TLogger.log("Schema does not exist in Persistent Storage"); RemoveSchemaData(); return false; } } private void RemoveSchemaData() { TLogger.log("RemoveSchemaData"); // Determine if additional persistent data needs to be removed try { getEntityTransaction().begin(); for (int i=0; i<NUMOFCUSTOMERS; i++ ) { Customer cust = getEntityManager().find(Customer.class, Integer.toString(i)); if (null != cust ) { getEntityManager().remove(cust); getEntityManager().flush(); TLogger.log("removed customer " + cust); } } for (int j=0; j<NUMOFALIASES; j++ ) { Alias alias = getEntityManager().find(Alias.class, Integer.toString(j)); if (null != alias ) { getEntityManager().remove(alias); getEntityManager().flush(); TLogger.log("removed alias " + alias); } } if (prodCol.size() != 0 ) { TLogger.log("Products found: cleaning up "); Iterator iterator = prodCol.iterator(); while(iterator.hasNext()) { Product pRef = (Product) iterator.next(); Product prod = getEntityManager().find(Product.class, (String)pRef.getId() ); if (null != prod ) { getEntityManager().remove(prod); getEntityManager().flush(); TLogger.log("removed product " + prod); } } } if ( orderCol.size() != 0 ) { TLogger.log("Orders found: cleaning up "); Iterator iterator = orderCol.iterator(); while(iterator.hasNext()) { Order oRef = (Order) iterator.next(); Order ord = getEntityManager().find(Order.class, (String)oRef.getId() ); if (null != ord ) { getEntityManager().remove(ord); getEntityManager().flush(); TLogger.log("removed order " + ord); } } } getEntityTransaction().commit(); } catch(Exception e) { TLogger.log("Exception encountered while removing entities:"); e.printStackTrace(); } finally { try { if ( getEntityTransaction().isActive() ) { getEntityTransaction().rollback(); } } catch (Exception re) { TLogger.log("Unexpection Exception in RemoveSchemaData:" + re ); re.printStackTrace(); } } } private static Date getShelfDate(int yy, int mm, int dd) { Calendar newCal = Calendar.getInstance(); newCal.clear(); newCal.set(yy,mm,dd); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String sDate = sdf.format(newCal.getTime()); //TLogger.log("returning date:" + java.sql.Date.valueOf(sDate) ); return java.sql.Date.valueOf(sDate); } private void doFlush() throws PersistenceException { TLogger.log("Entering doFlush method"); try { getEntityManager().flush(); } catch (PersistenceException pe) { throw new PersistenceException("Unexpected Exception caught while flushing: " + pe); } } private void createSchemaData(Properties p) throws Exception { getEntityTransaction().begin(); TLogger.log("Entered createSchemaData"); TLogger.log("Create " + NUMOFCOUNTRIES + " countries"); country[0] = new Country("United States", "USA"); country[1] = new Country("United States", "USA"); country[2] = new Country("United States", "USA"); country[3] = new Country("United States", "USA"); country[4] = new Country("United States", "USA"); country[5] = new Country("United States", "USA"); country[6] = new Country("United States", "USA"); country[7] = new Country("United States", "USA"); country[8] = new Country("United States", "USA"); country[9] = new Country("United States", "USA"); country[10] = new Country("England", "GBR"); country[11] = new Country("Ireland", "IRE"); country[12] = new Country("China", "CHA"); country[13] = new Country("Japan", "JPN"); country[14] = new Country("United States", "USA"); country[15] = new Country("England", "GBR"); country[16] = new Country("Ireland", "IRE"); country[17] = new Country("China", "CHA"); country[18] = new Country("China", "CHA"); country[19] = new Country("China", "CHA"); TLogger.log("Create " + NUMOFADDRESSES + " addresses"); address[0] = new Address( "1", "1 Oak Road", "Bedford", "MA", "02155"); address[1] = new Address( "2", "1 Network Drive", "Burlington", "MA", "00252"); address[2] = new Address( "3", "10 Griffin Road", "Lexington", "MA", "02277"); address[3] = new Address( "4", "1 Network Drive", "Burlington", "MA", "00252"); address[4] = new Address( "5", "125 Moxy Lane", "Swansea", "MA", "11345"); address[5] = new Address( "6", "1 Network Drive", "Burlington", "MA", "11345"); address[6] = new Address( "7", "2654 Brookline Avenue", "Brookline", "MA", "11678"); address[7] = new Address( "8", "1 Network Drive", "Burlington", "MA", "00252"); address[8] = new Address( "9", "100 Forrest Drive", "Hudson", "NH", "78654"); address[9] = new Address( "10", "1 Network Drive", "Burlington", "MA", "00252"); address[10] = new Address( "11", "200 Elliot Road", "Nashua", "NH", "65447"); address[11] = new Address( "12", "1 Network Drive", "Burlington", "MA", "00252"); address[12] = new Address( "13", "634 Goldstar Road", "Peabody", "MA", "88444"); address[13] = new Address( "14", "1 Network Drive", "Burlington", "MA", "00252"); address[14] = new Address( "15", "100 Forrest Drive", "Peabody", "MA", "88444"); address[15] = new Address( "16", "1 Network Drive", "Burlington", "MA", "00252"); address[16] = new Address( "17", "18 Rosewood Avenue", null, "MA", "87653"); address[17] = new Address( "18", "1 Network Drive", "Burlington", "MA", "00252"); address[18] = new Address( "19", null, "Belmont", "VT", "23083"); address[19] = new Address( "20", "1 Network Drive", "Burlington", "MA", "00252"); address[20] = new Address( "21", "3212 Boston Road", "Chelmsford", "MA", "01824"); address[21] = new Address( "22", "1 Network Drive", "Burlington", "MA", "00252"); address[22] = new Address( "23", "212 Edgewood Drive", "Claremont", "NH", "58976"); address[23] = new Address( "24", "1 Network Drive", "Burlington", null, "00252"); address[24] = new Address( "25", "47 Skyline Drive", "Attleboro", "MA", "76656"); address[25] = new Address( "26", "1 Network Drive", "Burlington", "MA", null); address[26] = new Address( "27", "4 Rangeway Road", "Lawrence", "RI", "53026"); address[27] = new Address( "28", "1 Network Drive", "Burlington", "MA", "00252"); address[28] = new Address( "29", "48 Sears Street", "Boston", "MA", "02110"); address[29] = new Address( "30", "1 Network Drive", "Burlington", "MA", "00252"); address[30] = new Address( "31", "1240 Davis Drive", "Northwood", "NH", "03260"); address[31] = new Address( "32", "1 Network Drive", "Burlington", "MA", "00252"); address[32] = new Address( "33", "455 James Avenue", "Roslindale", "NY", "57550"); address[33] = new Address( "34", "1 Network Drive", "Burlington", "MA", "00252"); address[34] = new Address( "35", "8 Beverly Lane", "HarwichPort", "PA", "45870"); address[35] = new Address( "36", "1 Network Drive", "Burlington", "MA", "00252"); for (int i=0; i<NUMOFADDRESSES; i++ ) { getEntityManager().persist(address[i]); TLogger.log("persisted address " + address[i]); } TLogger.log("Create " + NUMOFPHONES + " phone numbers"); phone[0] = new Phone("1", "617", "664-8122", address[0]); phone[1] = new Phone("2", "781", "442-8122", address[1]); phone[2] = new Phone("3", "508", "662-7117", address[2]); phone[3] = new Phone("4", "781", "442-4488", address[3]); phone[4] = new Phone("5", "992", "223-8888", address[4]); phone[5] = new Phone("6", "781", "442-1134", address[5]); phone[6] = new Phone("7", "442", "883-1597", address[6]); phone[7] = new Phone("8", "781", "442-6699", address[7]); phone[8] = new Phone("9", "603", "777-7890", address[8]); phone[9] = new Phone("10", "781", "442-2323", address[9]); phone[10] = new Phone("11", "603", "889-2355", address[10]); phone[11] = new Phone("12", "781", "442-9876", address[11]); phone[12] = new Phone("13", "222", "767-3124", address[12]); phone[13] = new Phone("14", "781", "442-1111", address[13]); phone[14] = new Phone("15", "222", "767-8898", address[14]); phone[15] = new Phone("16", "781", "442-4444", address[15]); phone[16] = new Phone("17", null, "564-9087", address[16]); phone[17] = new Phone("18", "781", "442-5341", address[17]); phone[18] = new Phone("19", null, null, address[18]); phone[19] = new Phone("20", "781", "442-1585", address[19]); phone[20] = new Phone("21", "207", "532-6354", address[20]); phone[21] = new Phone("22", "781", "442-0845", address[21]); phone[22] = new Phone("23", "913", null, address[22]); phone[23] = new Phone("24", "781", "442-7465", address[23]); phone[24] = new Phone("25", "678", "663-6091", address[24]); phone[25] = new Phone("26", "781", "442-2139", address[25]); phone[26] = new Phone("27", "890", "670-9138", address[26]); phone[27] = new Phone("28", "781", "442-0230", address[27]); phone[28] = new Phone("29", "450", "876-9087", address[28]); phone[29] = new Phone("30", "781", "442-6766", address[29]); phone[30] = new Phone("31", "908", "458-0980", address[30]); phone[31] = new Phone("32", "781", "442-6251", address[31]); phone[32] = new Phone("33", "432", "435-0909", address[32]); phone[33] = new Phone("34", "781", "442-8790", address[33]); phone[34] = new Phone("35", "415", "355-9008", address[34]); phone[35] = new Phone("36", "781", "442-2879", address[35]); for (int i=0; i<NUMOFPHONES; i++ ) { getEntityManager().persist(phone[i]); TLogger.log("persisted phone " + phone[i]); doFlush(); } TLogger.log("Create " + NUMOFCREDITCARDS + " creditcards"); creditCard[0] = new CreditCard( "1", "1234-2567-1222-9999", "VISA", "04/02", true, (double)5579); creditCard[1] = new CreditCard( "2", "3455-9876-1221-0060", "MCARD", "10/03", false, (double)15000); creditCard[2] = new CreditCard( "3", "1210-1449-2200-3254", "AXP", "11/02", true, (double)3000); creditCard[3] = new CreditCard( "4", "0002-1221-0078-0890", "VISA", "05/03", true, (double)8000); creditCard[4] = new CreditCard( "5", "1987-5555-8733-0011", "VISA", "05/03", true, (double)2500); creditCard[5] = new CreditCard( "6", "0000-0011-2200-3087", "MCARD", "11/02", true, (double)23000); creditCard[6] = new CreditCard( "7", "3341-7610-8880-9910", "AXP", "10/04", true, (double)13000); creditCard[7] = new CreditCard( "8", "2222-3333-4444-5555", "MCARD", "12/03", true, (double)2000); creditCard[8] = new CreditCard( "9", "8888-2222-0090-1348", "AXP", "01/02", true, (double)4500); creditCard[9] = new CreditCard( "10", "1762-5094-8769-3117", "VISA", "06/01", true, (double)14000); creditCard[10] = new CreditCard( "11", "1234-1234-1234-9999", "MCARD", "09/03", true, (double)7000); creditCard[11] = new CreditCard( "12", "9876-9876-1234-5678", "VISA", "04/04", false, (double)1000); creditCard[12] = new CreditCard( "13", "7777-8888-9999-0012", "MCARD", "01/02", true, (double)3500); creditCard[13] = new CreditCard( "14", "9099-8808-7718-4455", "AXP", "03/05", true, (double)4400); creditCard[14] = new CreditCard( "15", "7653-7901-2397-1768", "AXP", "02/04", true, (double)5000); creditCard[15] = new CreditCard( "16", "8760-8618-9263-3322", "VISA", "04/05", false, (double)750); creditCard[16] = new CreditCard( "17", "9870-2309-6754-3210", "MCARD", "03/03", true, (double)500); creditCard[17] = new CreditCard( "18", "8746-8754-9090-1234", "AXP", "08/04", false, (double)1500); creditCard[18] = new CreditCard( "19", "8736-0980-8765-4869", "MCARD", "09/02", true, (double)5500); creditCard[19] = new CreditCard( "20", "6745-0979-0970-2345", "VISA", "02/05", true, (double)1400); creditCard[20] = new CreditCard( "21", "8033-5896-9901-4566", "AXP", "09/07", true, (double)400); creditCard[21] = new CreditCard( "22", "4390-5671-4385-0091", "MCARD", "03/06", false, (double)7400); creditCard[22] = new CreditCard( "23", "3456-0909-3434-2134", "VISA", "04/08", true, (double)9500); creditCard[23] = new CreditCard( "24", "5643-2090-4569-2323", "MCARD", "01/06", false, (double)1000); for (int i=0; i<NUMOFCREDITCARDS; i++ ) { getEntityManager().persist(creditCard[i]); TLogger.log("persisted creditCard " + creditCard[i]); doFlush(); } TLogger.log("Create " + NUMOFLINEITEMS + " lineitems"); lineItem[0] = new LineItem("1", 1); lineItem[1] = new LineItem("2", 1); lineItem[2] = new LineItem("3", 1); lineItem[3] = new LineItem("4", 1); lineItem[4] = new LineItem("5", 1); lineItem[5] = new LineItem("6", 1); lineItem[6] = new LineItem("7", 1); lineItem[7] = new LineItem("8", 1); lineItem[8] = new LineItem("9", 1); lineItem[9] = new LineItem("10", 1); lineItem[10] = new LineItem("11", 1); lineItem[11] = new LineItem("12", 1); lineItem[12] = new LineItem("13", 1); lineItem[13] = new LineItem("14", 1); lineItem[14] = new LineItem("15", 1); lineItem[15] = new LineItem("16", 1); lineItem[16] = new LineItem("17", 1); lineItem[17] = new LineItem("18", 1); lineItem[18] = new LineItem("19", 1); lineItem[19] = new LineItem("20", 1); lineItem[20] = new LineItem("21", 1); lineItem[21] = new LineItem("22", 1); lineItem[22] = new LineItem("23", 1); lineItem[23] = new LineItem("24", 1); lineItem[24] = new LineItem("25", 1); lineItem[25] = new LineItem("26", 1); lineItem[26] = new LineItem("27", 1); lineItem[27] = new LineItem("28", 1); lineItem[28] = new LineItem("29", 1); lineItem[29] = new LineItem("30", 5); lineItem[30] = new LineItem("31", 3); lineItem[31] = new LineItem("32", 8); lineItem[32] = new LineItem("33", 1); lineItem[33] = new LineItem("34", 1); lineItem[34] = new LineItem("35", 6); lineItem[35] = new LineItem("36", 1); lineItem[36] = new LineItem("37", 2); lineItem[37] = new LineItem("38", 3); lineItem[38] = new LineItem("39", 5); lineItem[39] = new LineItem("40", 3); lineItem[40] = new LineItem("41", 2); lineItem[41] = new LineItem("42", 1); lineItem[42] = new LineItem("43", 1); lineItem[43] = new LineItem("44", 3); lineItem[44] = new LineItem("45", 1); lineItem[45] = new LineItem("46", 2); lineItem[46] = new LineItem("47", 3); lineItem[47] = new LineItem("48", 3); lineItem[48] = new LineItem("49", 4); lineItem[49] = new LineItem("50", 5); lineItem[50] = new LineItem("51", 2); lineItem[51] = new LineItem("52", 1); lineItem[52] = new LineItem("53", 3); lineItem[53] = new LineItem("54", 1); lineItem[54] = new LineItem("55", 3); lineItem[55] = new LineItem("56", 1); for (int i=0; i<NUMOFLINEITEMS; i++ ) { getEntityManager().persist(lineItem[i]); TLogger.log("persisted lineItem " + lineItem[i]); doFlush(); } TLogger.log("Create " + NUMOFCUSTOMERS + " customers"); customerRef[0] = new Customer( "1", "Alan E. Frechette", address[0], address[1], country[0]); customerRef[1] = new Customer( "2", "Arthur D. Frechette", address[2], address[3], country[1]); customerRef[2] = new Customer( "3", "Shelly D. McGowan", address[4], address[5], country[2]); customerRef[3] = new Customer( "4", "Robert E. Bissett", address[6], address[7], country[3]); customerRef[4] = new Customer( "5", "Stephen S. D'Milla", address[8], address[9], country[4]); customerRef[5] = new Customer( "6", "Karen R. Tegan", address[10], address[11], country[5]); customerRef[6] = new Customer( "7", "Stephen J. Caruso", address[12], address[13], country[6]); customerRef[7] = new Customer( "8", "Irene M. Caruso", address[14], address[15], country[7]); customerRef[8] = new Customer( "9", "William P. Keaton", address[16], address[17], country[8]); customerRef[9] = new Customer( "10", "Kate P. Hudson", address[18], address[19], country[9]); customerRef[10] = new Customer( "11", "Jonathan K. Smith", address[20], address[21], country[10]); customerRef[11] = new Customer( "12", null, address[22], address[23], country[11]); customerRef[12] = new Customer( "13", "Douglas A. Donahue", address[24], address[25], country[12]); customerRef[13] = new Customer( "14", "Kellie A. Sanborn", address[26], address[27], country[13]); customerRef[14] = new Customer( "15", "Margaret Mills", address[28], address[29], country[14]); customerRef[15] = new Customer( "16", "Sonya C. Sanders", address[30], address[31], country[15]); customerRef[16] = new Customer( "17", "Jack B. Grace", address[32], address[33], country[16]); customerRef[17] = new Customer( "18", "Ron F. Bender", address[34], address[35], country[17]); customerRef[18] = new Customer( "19", "Lisa M. Presley", country[18]); customerRef[19] = new Customer( "20", " David R. Vincent ", country[19]); for (int i=0; i<NUMOFCUSTOMERS; i++ ) { getEntityManager().persist(customerRef[i]); TLogger.log("persisted customer " + customerRef[i]); doFlush(); } TLogger.log("Create " + NUMOFINFODATA + " spouse info data"); info[0] = new Info(); info[0].setId("1"); info[0].setStreet("634 Goldstar Road"); info[0].setCity("Peabody"); info[0].setState("MA"); info[0].setZip("88444"); info[1] = new Info(); info[1].setId("2"); info[1].setStreet("3212 Boston Road"); info[1].setCity("Chelmsford"); info[1].setState("MA"); info[1].setZip("01824"); info[2] = new Info(); info[2].setId("3"); info[2].setStreet("47 Skyline Drive"); info[2].setCity("Attleboro"); info[2].setState("MA"); info[2].setZip("76656"); info[3] = new Info(); info[3].setId("4"); info[3].setStreet(null); info[3].setCity("Belmont"); info[3].setState("VT"); info[3].setZip("23083"); info[4] = new Info(); info[4].setId("5"); info[4].setStreet("212 Edgewood Drive"); info[4].setCity("Claremont"); info[4].setState("NH"); info[4].setZip("58976"); info[5] = new Info(); info[5].setId("6"); info[5].setStreet("11 Richmond Lane"); info[5].setCity("Chatham"); info[5].setState("NJ"); info[5].setZip("65490"); TLogger.log("Create " + NUMOFSPOUSES + " spouses"); spouse[0] = new Spouse( "1", "Kathleen", "Jones", "Porter", "034-58-0988", info[0], customerRef[6]); spouse[1] = new Spouse( "2", "Judith", "Connors", "McCall", "074-22-6431", info[1], customerRef[10]); spouse[2] = new Spouse( "3", "Linda", "Kelly", "Morrison", "501-22-5940", info[2], customerRef[12]); spouse[3] = new Spouse( "4", "Thomas", null, "Mullen", "210-23-3456", info[3], customerRef[9]); spouse[4] = new Spouse( "5", "Mitchell", null, "Jackson", "476-44-3349", info[4], customerRef[11]); spouse[5] = new Spouse( "6", "Cynthia", "White", "Allen", "508-908-7765", info[5]); for (int i=0; i<NUMOFSPOUSES; i++ ) { getEntityManager().persist(spouse[i]); TLogger.log("persisted spouse " + spouse[i]); doFlush(); } TLogger.log("Create " + NUMOFPRODUCTS + " products"); productRef[0] = new Product( "1", "Java 2 Unleashed Programming", (double)54.95, 100, (long)987654321); productRef[1] = new Product( "2", "Java 2 Network Programming", (double)37.95, 100, (long)876543219); productRef[2] = new Product( "3", "CORBA Programming", (double)44.95, 55, (long)765432198); productRef[3] = new Product( "4", "WEB Programming with JSP's & Servlet's", (double)33.95, 25, (long)654321987); productRef[4] = new Product( "5", "Dell Laptop PC", (double)1095.95, 50, (long)543219876); productRef[5] = new Product( "6", "Compaq Laptop PC", (double)995.95, 33, (long)432198765); productRef[6] = new Product( "7", "Toshiba Laptop PC", (double)1210.95, 22, (long)321987654); productRef[7] = new Product( "8", "Gateway Laptop PC", (double)1100.95, 11, (long)219876543); productRef[8] = new Product( "9", "Free Samples", (double)0.00, 10, (long)000000000); productRef[9] = new Product( "10", "Designing Enterprise Applications", (double)39.95, 500, (long)123456789); productRef[10] = new Product( "11", "Complete Guide to XML", (double)38.85, 300, (long)234567891); productRef[11] = new Product( "12", "Programming for Dummies", (double)24.95, 45, (long)345678912); productRef[12] = new Product( "13", "Introduction to Java", (double)60.95, 95, (long)456789123); productRef[13] = new Product( "14", "Ultra System", (double)5095.95, 250, (long)567891234); productRef[14] = new Product( "15", "Very Best Tutorial", (double)25.99, 0, (long)678912345); productRef[15] = new Product( "16", "Home Grown Programming Examples", (double)10.95, 25, (long)789123456); productRef[16] = new Product( "17", "Programming in ANSI C", (double)23.95, 10, (long)891234567); productRef[17] = new Product( "18", "Trial Software", (double)10.00, 75, (long)912345678); for (int i=0; i<NUMOFPRODUCTS; i++ ) { getEntityManager().persist(productRef[i]); TLogger.log("persisted product " + productRef[i]); doFlush(); } TLogger.log("Create 10 ShelfLife Instances"); shelfRef[0] = new ShelfLife(d1, null); shelfRef[1] = new ShelfLife(d2, null); shelfRef[2] = new ShelfLife(d3, null); shelfRef[3] = new ShelfLife(d4, null); shelfRef[4] = new ShelfLife(d5, null); shelfRef[5] = new ShelfLife(null, null); shelfRef[6] = new ShelfLife(null, d6); shelfRef[7] = new ShelfLife(null, d7); shelfRef[8] = new ShelfLife(d8, d9); shelfRef[9] = new ShelfLife(null, d10); TLogger.log("Create " + NUMOFHWPRODUCTS + " Hardware Products"); hardwareRef[0] = new HardwareProduct(); hardwareRef[0].setId("19"); hardwareRef[0].setName("Gateway E Series"); hardwareRef[0].setPrice((double)600.00); hardwareRef[0].setQuantity(25); hardwareRef[0].setPartNumber((long)238945678); hardwareRef[0].setShelfLife(shelfRef[0]); hardwareRef[0].setWareHouse("Columbia"); hardwareRef[0].setModelNumber(2578); getEntityManager().persist(hardwareRef[0]); hardwareRef[1] = new HardwareProduct(); hardwareRef[1].setId("20"); hardwareRef[1].setName("Java Desktop Systems"); hardwareRef[1].setPrice((double)890.00); hardwareRef[1].setQuantity(50); hardwareRef[1].setPartNumber((long)304506708); hardwareRef[1].setModelNumber(10050); hardwareRef[1].setWareHouse("Lowell"); getEntityManager().persist(hardwareRef[1]); hardwareRef[2] = new HardwareProduct(); hardwareRef[2].setId("21"); hardwareRef[2].setName("Dell Inspiron"); hardwareRef[2].setPrice((double)1100.00); hardwareRef[2].setQuantity(5); hardwareRef[2].setPartNumber((long)373767373); hardwareRef[2].setModelNumber(01100); hardwareRef[2].setWareHouse("Richmond"); hardwareRef[2].setShelfLife(shelfRef[1]); getEntityManager().persist(hardwareRef[2]); hardwareRef[3] = new HardwareProduct(); hardwareRef[3].setId("22"); hardwareRef[3].setName("Toshiba"); hardwareRef[3].setPrice((double)250.00); hardwareRef[3].setQuantity(40); hardwareRef[3].setPartNumber((long)285764839); hardwareRef[3].setModelNumber(00720); hardwareRef[3].setWareHouse("Richmond"); getEntityManager().persist(hardwareRef[3]); hardwareRef[4] = new HardwareProduct(); hardwareRef[4].setId("23"); hardwareRef[4].setName("SunBlade"); hardwareRef[4].setPrice((double)450.00); hardwareRef[4].setQuantity(80); hardwareRef[4].setPartNumber((long)987290102); hardwareRef[4].setModelNumber(00150); getEntityManager().persist(hardwareRef[4]); hardwareRef[5] = new HardwareProduct(); hardwareRef[5].setId("24"); hardwareRef[5].setName("Opteron"); hardwareRef[5].setPrice((double)800.00); hardwareRef[5].setQuantity(33); hardwareRef[5].setPartNumber((long)725109484); hardwareRef[5].setModelNumber(00050); hardwareRef[5].setWareHouse("Lowell"); hardwareRef[5].setShelfLife(shelfRef[2]); getEntityManager().persist(hardwareRef[5]); hardwareRef[6] = new HardwareProduct(); hardwareRef[6].setId("25"); hardwareRef[6].setName("Sun Enterprise"); hardwareRef[6].setPrice((double)15000.00); hardwareRef[6].setQuantity(100); hardwareRef[6].setPartNumber((long)773620626); hardwareRef[6].setModelNumber(10000); getEntityManager().persist(hardwareRef[6]); hardwareRef[7] = new HardwareProduct(); hardwareRef[7].setId("26"); hardwareRef[7].setName("Dell Dimension"); hardwareRef[7].setPrice((double)950.00); hardwareRef[7].setQuantity(70); hardwareRef[7].setPartNumber((long)927262628); hardwareRef[7].setModelNumber(3000); getEntityManager().persist(hardwareRef[7]); hardwareRef[8] = new HardwareProduct(); hardwareRef[8].setId("27"); hardwareRef[8].setName("Dell Dimension"); hardwareRef[8].setPrice((double)795.00); hardwareRef[8].setQuantity(20); hardwareRef[8].setPartNumber((long)482726166); hardwareRef[8].setModelNumber(04500); hardwareRef[8].setShelfLife(shelfRef[3]); hardwareRef[8].setWareHouse("Columbia"); getEntityManager().persist(hardwareRef[8]); hardwareRef[9] = new HardwareProduct(); hardwareRef[9].setId("28"); hardwareRef[9].setName("SunBlade"); hardwareRef[9].setPrice((double)1000.00); hardwareRef[9].setQuantity(20); hardwareRef[9].setPartNumber((long)312010108); hardwareRef[9].setModelNumber(00100); hardwareRef[9].setShelfLife(shelfRef[4]); getEntityManager().persist(hardwareRef[9]); TLogger.log("Flush hardware products"); doFlush(); TLogger.log("Create " + NUMOFSWPRODUCTS + " Software Products"); softwareRef[0] = new SoftwareProduct(); softwareRef[0].setId("29"); softwareRef[0].setName("SunOS 9"); softwareRef[0].setPrice((double)500.00); softwareRef[0].setQuantity(500); softwareRef[0].setPartNumber((long)837373379); softwareRef[0].setRevisionNumber((double)1.0); softwareRef[0].setShelfLife(shelfRef[5]); getEntityManager().persist(softwareRef[0]); softwareRef[1] = new SoftwareProduct(); softwareRef[1].setId("30"); softwareRef[1].setName("Patch 590-009"); softwareRef[1].setPrice((double)55.00); softwareRef[1].setQuantity(23); softwareRef[1].setPartNumber((long)285764891); softwareRef[1].setRevisionNumber((double)1.1); getEntityManager().persist(softwareRef[1]); softwareRef[2] = new SoftwareProduct(); softwareRef[2].setId("31"); softwareRef[2].setName("NetBeans"); softwareRef[2].setPrice((double)35.00); softwareRef[2].setQuantity(15); softwareRef[2].setPartNumber((long)174983901); softwareRef[2].setRevisionNumber((double)4.0); softwareRef[2].setShelfLife(shelfRef[6]); softwareRef[2].setWareHouse("Lowell"); getEntityManager().persist(softwareRef[2]); softwareRef[3] = new SoftwareProduct(); softwareRef[3].setId("32"); softwareRef[3].setName("J2SE"); softwareRef[3].setPrice((double)150.00); softwareRef[3].setQuantity(100); softwareRef[3].setPartNumber((long)173479765); softwareRef[3].setRevisionNumber((double)5.0); softwareRef[3].setShelfLife(shelfRef[7]); getEntityManager().persist(softwareRef[3]); softwareRef[4] = new SoftwareProduct(); softwareRef[4].setId("33"); softwareRef[4].setName("Creator"); softwareRef[4].setPrice((double)125.00); softwareRef[4].setQuantity(60); softwareRef[4].setPartNumber((long)847651234); softwareRef[4].setRevisionNumber((double)4.0); softwareRef[4].setShelfLife(shelfRef[8]); getEntityManager().persist(softwareRef[4]); softwareRef[5] = new SoftwareProduct(); softwareRef[5].setId("34"); softwareRef[5].setName("Java Programming Examples"); softwareRef[5].setPrice((double)175.00); softwareRef[5].setQuantity(200); softwareRef[5].setPartNumber((long)376512908); softwareRef[5].setRevisionNumber((double)1.5); getEntityManager().persist(softwareRef[5]); softwareRef[6] = new SoftwareProduct(); softwareRef[6].setId("35"); softwareRef[6].setName("Tutorial"); softwareRef[6].setPrice((double)250.00); softwareRef[6].setQuantity(35); softwareRef[6].setPartNumber((long)837462890); softwareRef[6].setRevisionNumber((double)1.4); softwareRef[6].setWareHouse(null); getEntityManager().persist(softwareRef[6]); softwareRef[7] = new SoftwareProduct(); softwareRef[7].setId("36"); softwareRef[7].setName("Testing Tools"); softwareRef[7].setPrice((double)300.00); softwareRef[7].setQuantity(20); softwareRef[7].setPartNumber((long)372615467); softwareRef[7].setRevisionNumber((double)1.0); getEntityManager().persist(softwareRef[7]); softwareRef[8] = new SoftwareProduct(); softwareRef[8].setId("37"); softwareRef[8].setName("Patch 395-478"); softwareRef[8].setPrice((double)55.00); softwareRef[8].setQuantity(25); softwareRef[8].setPartNumber((long)847628901); softwareRef[8].setRevisionNumber((double)1.1); softwareRef[8].setShelfLife(shelfRef[9]); softwareRef[8].setWareHouse("Lowell"); getEntityManager().persist(softwareRef[8]); softwareRef[9] = new SoftwareProduct(); softwareRef[9].setId("38"); softwareRef[9].setName("Appserver 8"); softwareRef[9].setPrice((double)0.00); softwareRef[9].setQuantity(150); softwareRef[9].setPartNumber((long)873657891); softwareRef[9].setRevisionNumber((double)1.1); getEntityManager().persist(softwareRef[9]); TLogger.log("Flush software products"); doFlush(); TLogger.log("Create " + NUMOFORDERS + " Orders"); orderRef[0] = new Order("1", customerRef[0]); orderRef[1] = new Order("2", customerRef[1]); orderRef[2] = new Order("3", customerRef[2]); orderRef[3] = new Order("4", customerRef[3]); orderRef[4] = new Order("5", customerRef[4]); orderRef[5] = new Order("6", customerRef[5]); orderRef[6] = new Order("7", customerRef[6]); orderRef[7] = new Order("8", customerRef[7]); orderRef[8] = new Order("9", customerRef[3]); orderRef[9] = new Order("10", customerRef[8]); orderRef[10] = new Order("11", customerRef[9]); orderRef[11] = new Order("12", customerRef[10]); orderRef[12] = new Order("13", customerRef[11]); orderRef[13] = new Order("14", customerRef[12]); orderRef[14] = new Order("15", customerRef[13]); orderRef[15] = new Order("16", customerRef[13]); orderRef[16] = new Order("17", customerRef[14]); orderRef[17] = new Order("18", customerRef[15]); orderRef[18] = new Order("19"); orderRef[19] = new Order("20"); for (int i=0; i<NUMOFORDERS; i++ ) { getEntityManager().persist(orderRef[i]); TLogger.log("persisted order " + orderRef[i]); doFlush(); } TLogger.log("Create " + NUMOFALIASES + " Aliases"); aliasRef[0] = new Alias("1", "aef"); aliasRef[1] = new Alias("2", "al"); aliasRef[2] = new Alias("3", "fish"); aliasRef[3] = new Alias("4", "twin"); aliasRef[4] = new Alias("5", "adf"); aliasRef[5] = new Alias("6", "art"); aliasRef[6] = new Alias("7", "sdm"); aliasRef[7] = new Alias("8", "sh_ll"); aliasRef[8] = new Alias("9", "reb"); aliasRef[9] = new Alias("10", "bobby"); aliasRef[10] = new Alias("11", "bb"); aliasRef[11] = new Alias("12", "ssd"); aliasRef[12] = new Alias("13", "steved"); aliasRef[13] = new Alias("14", "stevie"); aliasRef[14] = new Alias("15", ""); aliasRef[15] = new Alias("16", ""); aliasRef[16] = new Alias("17", "sjc"); aliasRef[17] = new Alias("18", "stevec"); aliasRef[18] = new Alias("19", "imc"); aliasRef[19] = new Alias("20", "iris"); aliasRef[20] = new Alias("21", "bro"); aliasRef[21] = new Alias("22", "sis"); aliasRef[22] = new Alias("23", "kell"); aliasRef[23] = new Alias("24", "bill"); aliasRef[24] = new Alias("25", "suzy"); aliasRef[25] = new Alias("26", "jon"); aliasRef[26] = new Alias("27", "jk"); aliasRef[27] = new Alias("28", "kellieann"); aliasRef[28] = new Alias("29", "smitty"); aliasRef[29] = new Alias("30", null); for (int i=0; i<NUMOFALIASES; i++ ) { getEntityManager().persist(aliasRef[i]); TLogger.log("persisted alias " + aliasRef[i]); doFlush(); } getEntityTransaction().commit(); TLogger.log("Done Creating Schema in Persistent Storage"); } private void createRelationships() throws Exception { double totalPrice; getEntityTransaction().begin(); TLogger.log("Setting additional relationships for Order 1"); lineItem[0].setProduct(productRef[0]); lineItem[0].setOrder(orderRef[0]); getEntityManager().merge(lineItem[0]); lineItem[1].setProduct(productRef[1]); lineItem[1].setOrder(orderRef[0]); getEntityManager().merge(lineItem[1]); lineItem[2].setProduct(productRef[7]); lineItem[2].setOrder(orderRef[0]); getEntityManager().merge(lineItem[2]); lineItem[28].setProduct(productRef[8]); lineItem[28].setOrder(orderRef[0]); getEntityManager().merge(lineItem[28]); orderRef[0].getLineItems().add(lineItem[0]); orderRef[0].getLineItems().add(lineItem[1]); orderRef[0].getLineItems().add(lineItem[2]); orderRef[0].setSampleLineItem(lineItem[28]); totalPrice = productRef[0].getPrice() + productRef[1].getPrice() + productRef[7].getPrice() + productRef[8].getPrice(); orderRef[0].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[0]); creditCard[1].setOrder(orderRef[0]); creditCard[1].setCustomer(customerRef[0]); getEntityManager().merge(creditCard[1]); doFlush(); TLogger.log("Done with Order 1 relationships"); TLogger.log("Setting additional relationships for Order 2"); lineItem[3].setProduct(productRef[0]); lineItem[3].setOrder(orderRef[1]); getEntityManager().merge(lineItem[3]); lineItem[4].setProduct(productRef[1]); lineItem[4].setOrder(orderRef[1]); getEntityManager().merge(lineItem[4]); lineItem[5].setProduct(productRef[2]); lineItem[5].setOrder(orderRef[1]); getEntityManager().merge(lineItem[5]); lineItem[6].setProduct(productRef[3]); lineItem[6].setOrder(orderRef[1]); getEntityManager().merge(lineItem[6]); lineItem[7].setProduct(productRef[4]); lineItem[7].setOrder(orderRef[1]); getEntityManager().merge(lineItem[7]); orderRef[1].getLineItems().add(lineItem[3]); orderRef[1].getLineItems().add(lineItem[4]); orderRef[1].getLineItems().add(lineItem[5]); orderRef[1].getLineItems().add(lineItem[6]); orderRef[1].getLineItems().add(lineItem[7]); totalPrice = productRef[0].getPrice() + productRef[1].getPrice() + productRef[2].getPrice() + productRef[3].getPrice() + productRef[4].getPrice(); orderRef[1].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[1]); creditCard[3].setOrder(orderRef[1]); creditCard[3].setCustomer(customerRef[1]); getEntityManager().merge(creditCard[3]); doFlush(); TLogger.log("Done Setting relationships for Order 2"); TLogger.log("Setting additional relationships for Order 3"); lineItem[8].setProduct(productRef[2]); lineItem[8].setOrder(orderRef[2]); getEntityManager().merge(lineItem[8]); lineItem[9].setProduct(productRef[5]); lineItem[9].setOrder(orderRef[2]); getEntityManager().merge(lineItem[9]); orderRef[2].getLineItems().add(lineItem[8]); orderRef[2].getLineItems().add(lineItem[9]); totalPrice = productRef[2].getPrice() + productRef[5].getPrice(); orderRef[2].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[2]); creditCard[4].setOrder(orderRef[2]); creditCard[4].setCustomer(customerRef[2]); getEntityManager().merge(creditCard[4]); doFlush(); TLogger.log("Done Setting Relationships for Order 3"); TLogger.log("Setting additional relationships for Order 4"); lineItem[10].setProduct(productRef[6]); lineItem[10].setOrder(orderRef[3]); getEntityManager().merge(lineItem[10]); orderRef[3].getLineItems().add(lineItem[10]); totalPrice = productRef[6].getPrice(); orderRef[3].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[3]); creditCard[5].setOrder(orderRef[3]); creditCard[5].setCustomer(customerRef[3]); getEntityManager().merge(creditCard[5]); doFlush(); TLogger.log("Done Setting Relationships for Order 4"); TLogger.log("Setting additional relationships for Order 5"); lineItem[11].setProduct(productRef[0]); lineItem[11].setOrder(orderRef[4]); getEntityManager().merge(lineItem[11]); lineItem[12].setProduct(productRef[1]); lineItem[12].setOrder(orderRef[4]); getEntityManager().merge(lineItem[12]); lineItem[13].setProduct(productRef[2]); lineItem[13].setOrder(orderRef[4]); getEntityManager().merge(lineItem[13]); lineItem[14].setProduct(productRef[3]); lineItem[14].setOrder(orderRef[4]); getEntityManager().merge(lineItem[14]); lineItem[15].setProduct(productRef[4]); lineItem[15].setOrder(orderRef[4]); getEntityManager().merge(lineItem[15]); lineItem[16].setProduct(productRef[5]); lineItem[16].setOrder(orderRef[4]); getEntityManager().merge(lineItem[16]); lineItem[17].setProduct(productRef[6]); lineItem[17].setOrder(orderRef[4]); getEntityManager().merge(lineItem[17]); lineItem[18].setProduct(productRef[7]); lineItem[18].setOrder(orderRef[4]); getEntityManager().merge(lineItem[18]); orderRef[4].getLineItems().add(lineItem[11]); orderRef[4].getLineItems().add(lineItem[12]); orderRef[4].getLineItems().add(lineItem[13]); orderRef[4].getLineItems().add(lineItem[14]); orderRef[4].getLineItems().add(lineItem[15]); orderRef[4].getLineItems().add(lineItem[16]); orderRef[4].getLineItems().add(lineItem[17]); orderRef[4].getLineItems().add(lineItem[18]); totalPrice = productRef[0].getPrice() + productRef[1].getPrice() + productRef[2].getPrice() + productRef[3].getPrice() + productRef[4].getPrice() + productRef[5].getPrice() + productRef[6].getPrice() + productRef[7].getPrice(); orderRef[4].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[4]); creditCard[7].setOrder(orderRef[4]); creditCard[7].setCustomer(customerRef[4]); getEntityManager().merge(creditCard[7]); doFlush(); TLogger.log("Done Setting Relationships for Order 5"); TLogger.log("Setting additional relationships for Order 6"); lineItem[19].setProduct(productRef[3]); lineItem[19].setOrder(orderRef[5]); getEntityManager().merge(lineItem[19]); lineItem[20].setProduct(productRef[6]); lineItem[20].setOrder(orderRef[5]); getEntityManager().merge(lineItem[20]); lineItem[29].setProduct(productRef[8]); lineItem[29].setOrder(orderRef[5]); getEntityManager().merge(lineItem[29]); orderRef[5].getLineItems().add(lineItem[19]); orderRef[5].getLineItems().add(lineItem[20]); orderRef[5].setSampleLineItem(lineItem[29]); totalPrice = productRef[3].getPrice() + productRef[6].getPrice() + productRef[8].getPrice(); orderRef[5].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[5]); creditCard[10].setOrder(orderRef[5]); creditCard[10].setCustomer(customerRef[5]); getEntityManager().merge(creditCard[10]); doFlush(); TLogger.log("Done Setting Relationships for Order 6"); TLogger.log("Setting additional relationships for Order 7"); lineItem[21].setProduct(productRef[2]); lineItem[21].setOrder(orderRef[6]); getEntityManager().merge(lineItem[21]); lineItem[22].setProduct(productRef[3]); lineItem[22].setOrder(orderRef[6]); getEntityManager().merge(lineItem[22]); lineItem[23].setProduct(productRef[7]); lineItem[23].setOrder(orderRef[6]); getEntityManager().merge(lineItem[23]); orderRef[6].getLineItems().add(lineItem[21]); orderRef[6].getLineItems().add(lineItem[22]); orderRef[6].getLineItems().add(lineItem[23]); totalPrice = productRef[2].getPrice() + productRef[3].getPrice() + productRef[7].getPrice(); orderRef[6].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[6]); creditCard[11].setOrder(orderRef[6]); creditCard[11].setCustomer(customerRef[6]); getEntityManager().merge(creditCard[11]); doFlush(); TLogger.log("Done Setting additional relationships for Order 7"); TLogger.log("Setting additional relationships for Order 8"); lineItem[24].setProduct(productRef[0]); lineItem[24].setOrder(orderRef[7]); getEntityManager().merge(lineItem[24]); lineItem[25].setProduct(productRef[4]); lineItem[25].setOrder(orderRef[7]); getEntityManager().merge(lineItem[25]); orderRef[7].getLineItems().add(lineItem[24]); orderRef[7].getLineItems().add(lineItem[25]); totalPrice = productRef[0].getPrice() + productRef[4].getPrice(); orderRef[7].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[7]); creditCard[13].setOrder(orderRef[7]); creditCard[13].setCustomer(customerRef[7]); getEntityManager().merge(creditCard[13]); doFlush(); TLogger.log("Done Setting additional relationships for Order 8"); TLogger.log("Setting additional relationships for Order 9"); lineItem[26].setProduct(productRef[0]); lineItem[26].setOrder(orderRef[8]); getEntityManager().merge(lineItem[26]); lineItem[27].setProduct(productRef[1]); lineItem[27].setOrder(orderRef[8]); getEntityManager().merge(lineItem[27]); orderRef[8].getLineItems().add(lineItem[26]); orderRef[8].getLineItems().add(lineItem[27]); totalPrice = productRef[0].getPrice() + productRef[1].getPrice(); orderRef[8].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[8]); creditCard[6].setOrder(orderRef[8]); creditCard[6].setCustomer(customerRef[3]); getEntityManager().merge(creditCard[6]); doFlush(); TLogger.log("Done Setting additional relationships for Order 9"); TLogger.log("Setting additional relationships for Order 10"); lineItem[30].setProduct(productRef[9]); lineItem[30].setOrder(orderRef[9]); getEntityManager().merge(lineItem[30]); lineItem[31].setProduct(productRef[16]); lineItem[31].setOrder(orderRef[9]); getEntityManager().merge(lineItem[31]); orderRef[9].getLineItems().add(lineItem[30]); orderRef[9].getLineItems().add(lineItem[31]); totalPrice = productRef[9].getPrice() + productRef[16].getPrice(); orderRef[9].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[9]); creditCard[14].setOrder(orderRef[9]); creditCard[14].setCustomer(customerRef[8]); getEntityManager().merge(creditCard[14]); doFlush(); TLogger.log("Done Setting additional relationships for Order 10"); TLogger.log("Setting additional relationships for Order 11"); lineItem[32].setProduct(productRef[13]); lineItem[32].setOrder(orderRef[10]); getEntityManager().merge(lineItem[32]); orderRef[10].getLineItems().add(lineItem[32]); totalPrice = productRef[13].getPrice(); orderRef[10].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[10]); creditCard[15].setOrder(orderRef[10]); creditCard[15].setCustomer(customerRef[9]); getEntityManager().merge(creditCard[15]); doFlush(); TLogger.log("Done Setting additional relationships for Order 11"); TLogger.log("Setting additional relationships for Order 12"); lineItem[33].setProduct(productRef[10]); lineItem[33].setOrder(orderRef[11]); getEntityManager().merge(lineItem[33]); lineItem[34].setProduct(productRef[12]); lineItem[34].setOrder(orderRef[11]); getEntityManager().merge(lineItem[34]); orderRef[11].getLineItems().add(lineItem[33]); orderRef[11].getLineItems().add(lineItem[34]); totalPrice = productRef[10].getPrice() + productRef[12].getPrice(); orderRef[11].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[11]); creditCard[16].setOrder(orderRef[11]); creditCard[16].setCustomer(customerRef[10]); getEntityManager().merge(creditCard[16]); doFlush(); TLogger.log("Done Setting additional relationships for Order 12"); TLogger.log("Setting additional relationships for Order 13"); lineItem[35].setProduct(productRef[17]); lineItem[35].setOrder(orderRef[12]); getEntityManager().merge(lineItem[35]); orderRef[12].getLineItems().add(lineItem[35]); totalPrice = productRef[17].getPrice(); orderRef[12].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[12]); creditCard[17].setOrder(orderRef[12]); creditCard[17].setCustomer(customerRef[11]); getEntityManager().merge(creditCard[17]); doFlush(); TLogger.log("Done Setting additional relationships for Order 13"); TLogger.log("Setting additional relationships for Order 14"); lineItem[36].setProduct(productRef[7]); lineItem[36].setOrder(orderRef[13]); getEntityManager().merge(lineItem[36]); lineItem[37].setProduct(productRef[14]); lineItem[37].setOrder(orderRef[13]); getEntityManager().merge(lineItem[37]); lineItem[38].setProduct(productRef[15]); lineItem[38].setOrder(orderRef[13]); getEntityManager().merge(lineItem[38]); orderRef[13].getLineItems().add(lineItem[36]); orderRef[13].getLineItems().add(lineItem[37]); orderRef[13].getLineItems().add(lineItem[38]); totalPrice = productRef[7].getPrice() + productRef[14].getPrice() + productRef[15].getPrice(); orderRef[13].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[13]); creditCard[18].setOrder(orderRef[13]); creditCard[18].setCustomer(customerRef[12]); getEntityManager().merge(creditCard[18]); doFlush(); TLogger.log("Done Setting additional relationships for Order 14"); TLogger.log("Setting additional relationships for Order 15"); lineItem[39].setProduct(productRef[1]); lineItem[39].setOrder(orderRef[14]); getEntityManager().merge(lineItem[39]); lineItem[40].setProduct(productRef[2]); lineItem[40].setOrder(orderRef[14]); getEntityManager().merge(lineItem[40]); lineItem[41].setProduct(productRef[12]); lineItem[41].setOrder(orderRef[14]); getEntityManager().merge(lineItem[41]); lineItem[42].setProduct(productRef[15]); lineItem[42].setOrder(orderRef[14]); getEntityManager().merge(lineItem[42]); orderRef[14].getLineItems().add(lineItem[39]); orderRef[14].getLineItems().add(lineItem[40]); orderRef[14].getLineItems().add(lineItem[41]); orderRef[14].getLineItems().add(lineItem[42]); totalPrice = productRef[1].getPrice() + productRef[2].getPrice() + productRef[12].getPrice() + productRef[15].getPrice(); orderRef[14].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[14]); creditCard[19].setOrder(orderRef[14]); creditCard[19].setCustomer(customerRef[13]); getEntityManager().merge(creditCard[19]); doFlush(); TLogger.log("Done Setting additional relationships for Order 15"); TLogger.log("Setting additional relationships for Order 16"); lineItem[43].setProduct(productRef[13]); lineItem[43].setOrder(orderRef[15]); getEntityManager().merge(lineItem[43]); orderRef[15].getLineItems().add(lineItem[43]); totalPrice = productRef[13].getPrice(); orderRef[15].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[15]); creditCard[19].setOrder(orderRef[15]); creditCard[19].setCustomer(customerRef[13]); getEntityManager().merge(creditCard[19]); doFlush(); TLogger.log("Done Setting additional relationships for Order 16"); TLogger.log("Setting additional relationships for Order 17"); lineItem[44].setProduct(hardwareRef[0]); lineItem[44].setOrder(orderRef[16]); getEntityManager().merge(lineItem[44]); lineItem[45].setProduct(hardwareRef[1]); lineItem[45].setOrder(orderRef[16]); getEntityManager().merge(lineItem[45]); lineItem[46].setProduct(softwareRef[0]); lineItem[46].setOrder(orderRef[16]); getEntityManager().merge(lineItem[46]); orderRef[16].getLineItems().add(lineItem[44]); orderRef[16].getLineItems().add(lineItem[45]); orderRef[16].getLineItems().add(lineItem[46]); totalPrice = hardwareRef[0].getPrice() + hardwareRef[1].getPrice() + softwareRef[0].getPrice(); orderRef[16].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[16]); creditCard[20].setOrder(orderRef[16]); creditCard[20].setCustomer(customerRef[14]); getEntityManager().merge(creditCard[20]); doFlush(); TLogger.log("Done Setting additional relationships for Order 17"); TLogger.log("Setting additional relationships for Order 18"); lineItem[47].setProduct(hardwareRef[2]); lineItem[47].setOrder(orderRef[17]); getEntityManager().merge(lineItem[47]); lineItem[48].setProduct(softwareRef[1]); lineItem[48].setOrder(orderRef[17]); getEntityManager().merge(lineItem[48]); lineItem[49].setProduct(hardwareRef[3]); lineItem[49].setOrder(orderRef[17]); getEntityManager().merge(lineItem[49]); lineItem[50].setProduct(softwareRef[2]); lineItem[50].setOrder(orderRef[17]); getEntityManager().merge(lineItem[50]); orderRef[17].getLineItems().add(lineItem[47]); orderRef[17].getLineItems().add(lineItem[48]); orderRef[17].getLineItems().add(lineItem[49]); orderRef[17].getLineItems().add(lineItem[50]); totalPrice = hardwareRef[2].getPrice() + hardwareRef[3].getPrice() + softwareRef[1].getPrice() + softwareRef[2].getPrice(); orderRef[17].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[17]); creditCard[21].setOrder(orderRef[17]); creditCard[21].setCustomer(customerRef[15]); getEntityManager().merge(creditCard[21]); doFlush(); TLogger.log("Done Setting additional relationships for Order 18"); TLogger.log("Setting additional relationships for Order 19"); lineItem[51].setProduct(hardwareRef[4]); lineItem[51].setOrder(orderRef[18]); getEntityManager().merge(lineItem[51]); lineItem[52].setProduct(softwareRef[3]); lineItem[52].setOrder(orderRef[18]); getEntityManager().merge(lineItem[52]); lineItem[53].setProduct(softwareRef[4]); lineItem[53].setOrder(orderRef[18]); getEntityManager().merge(lineItem[53]); orderRef[18].getLineItems().add(lineItem[51]); orderRef[18].getLineItems().add(lineItem[52]); orderRef[18].getLineItems().add(lineItem[53]); totalPrice = hardwareRef[4].getPrice() + softwareRef[3].getPrice() + softwareRef[4].getPrice(); orderRef[18].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[18]); creditCard[22].setOrder(orderRef[18]); creditCard[22].setCustomer(customerRef[16]); getEntityManager().merge(creditCard[22]); doFlush(); TLogger.log("Done Setting additional relationships for Order 19"); TLogger.log("Setting additional relationships for Order 20"); lineItem[54].setProduct(hardwareRef[5]); lineItem[54].setOrder(orderRef[19]); getEntityManager().merge(lineItem[54]); lineItem[55].setProduct(softwareRef[5]); lineItem[55].setOrder(orderRef[19]); getEntityManager().merge(lineItem[55]); orderRef[19].getLineItems().add(lineItem[54]); orderRef[19].getLineItems().add(lineItem[55]); totalPrice = hardwareRef[5].getPrice() + softwareRef[5].getPrice(); orderRef[19].setTotalPrice((double)totalPrice); getEntityManager().merge(orderRef[19]); creditCard[23].setOrder(orderRef[19]); creditCard[23].setCustomer(customerRef[17]); getEntityManager().merge(creditCard[23]); doFlush(); TLogger.log("Done Setting additional relationships for Order 20"); TLogger.log("Setting additional relationships for Customer 1"); aliasRef[0].getCustomers().add(customerRef[0]); getEntityManager().merge(aliasRef[0]); aliasRef[1].getCustomers().add(customerRef[0]); getEntityManager().merge(aliasRef[1]); aliasRef[2].getCustomers().add(customerRef[0]); getEntityManager().merge(aliasRef[2]); aliasRef[3].getCustomers().add(customerRef[0]); getEntityManager().merge(aliasRef[3]); orderRef[0].setCustomer(customerRef[0]); getEntityManager().merge(orderRef[0]); creditCard[0].setCustomer(customerRef[0]); getEntityManager().merge(creditCard[0]); creditCard[1].setCustomer(customerRef[0]); getEntityManager().merge(creditCard[1]); creditCard[2].setCustomer(customerRef[0]); getEntityManager().merge(creditCard[2]); doFlush(); TLogger.log("Setting additional relationships for Customer 2"); aliasRef[2].getCustomers().add(customerRef[1]); getEntityManager().merge(aliasRef[2]); aliasRef[3].getCustomers().add(customerRef[1]); getEntityManager().merge(aliasRef[3]); aliasRef[4].getCustomers().add(customerRef[1]); getEntityManager().merge(aliasRef[4]); aliasRef[5].getCustomers().add(customerRef[1]); getEntityManager().merge(aliasRef[5]); orderRef[1].setCustomer(customerRef[1]); getEntityManager().merge(orderRef[1]); creditCard[3].setCustomer(customerRef[1]); getEntityManager().merge(creditCard[3]); doFlush(); TLogger.log("Setting additional relationships for Customer 3"); aliasRef[6].getCustomers().add(customerRef[2]); getEntityManager().merge(aliasRef[6]); aliasRef[7].getCustomers().add(customerRef[2]); getEntityManager().merge(aliasRef[7]); orderRef[2].setCustomer(customerRef[2]); getEntityManager().merge(orderRef[2]); creditCard[4].setCustomer(customerRef[2]); getEntityManager().merge(creditCard[4]); doFlush(); TLogger.log("Setting additional relationships for Customer 4"); aliasRef[8].getCustomers().add(customerRef[3]); getEntityManager().merge(aliasRef[8]); aliasRef[9].getCustomers().add(customerRef[3]); getEntityManager().merge(aliasRef[9]); aliasRef[10].getCustomers().add(customerRef[3]); getEntityManager().merge(aliasRef[10]); orderRef[3].setCustomer(customerRef[3]); getEntityManager().merge(orderRef[3]); creditCard[5].setCustomer(customerRef[3]); getEntityManager().merge(creditCard[5]); creditCard[6].setCustomer(customerRef[3]); getEntityManager().merge(creditCard[6]); doFlush(); TLogger.log("Setting additional relationships for Customer 5"); aliasRef[11].getCustomers().add(customerRef[4]); getEntityManager().merge(aliasRef[11]); aliasRef[12].getCustomers().add(customerRef[4]); getEntityManager().merge(aliasRef[12]); aliasRef[13].getCustomers().add(customerRef[4]); getEntityManager().merge(aliasRef[13]); orderRef[4].setCustomer(customerRef[4]); getEntityManager().merge(orderRef[4]); creditCard[7].setCustomer(customerRef[4]); getEntityManager().merge(creditCard[7]); creditCard[8].setCustomer(customerRef[4]); getEntityManager().merge(creditCard[8]); doFlush(); TLogger.log("Setting additional relationships for Customer 6"); // aliasRef[14] - Not Set // aliasRef[15] - Not Set orderRef[5].setCustomer(customerRef[5]); getEntityManager().merge(orderRef[5]); creditCard[9].setCustomer(customerRef[5]); getEntityManager().merge(creditCard[9]); creditCard[10].setCustomer(customerRef[5]); getEntityManager().merge(creditCard[10]); doFlush(); TLogger.log("Setting additional relationships for Customer 7"); aliasRef[13].getCustomers().add(customerRef[6]); getEntityManager().merge(aliasRef[13]); aliasRef[16].getCustomers().add(customerRef[6]); getEntityManager().merge(aliasRef[16]); aliasRef[17].getCustomers().add(customerRef[6]); getEntityManager().merge(aliasRef[17]); orderRef[6].setCustomer(customerRef[6]); getEntityManager().merge(orderRef[6]); creditCard[11].setCustomer(customerRef[6]); getEntityManager().merge(creditCard[11]); doFlush(); TLogger.log("Setting additional relationships for Customer 8"); aliasRef[18].getCustomers().add(customerRef[7]); getEntityManager().merge(aliasRef[18]); aliasRef[19].getCustomers().add(customerRef[7]); getEntityManager().merge(aliasRef[19]); orderRef[7].setCustomer(customerRef[7]); getEntityManager().merge(orderRef[7]); creditCard[12].setCustomer(customerRef[7]); getEntityManager().merge(creditCard[12]); creditCard[13].setCustomer(customerRef[7]); getEntityManager().merge(creditCard[13]); doFlush(); TLogger.log("Setting additional relationships for Customer 9"); aliasRef[23].getCustomers().add(customerRef[8]); getEntityManager().merge(aliasRef[23]); orderRef[9].setCustomer(customerRef[8]); getEntityManager().merge(orderRef[9]); creditCard[14].setCustomer(customerRef[8]); getEntityManager().merge(creditCard[14]); doFlush(); TLogger.log("Setting additional relationships for Customer 10"); aliasRef[21].getCustomers().add(customerRef[9]); getEntityManager().merge(aliasRef[21]); aliasRef[29].getCustomers().add(customerRef[9]); getEntityManager().merge(aliasRef[29]); orderRef[10].setCustomer(customerRef[9]); getEntityManager().merge(orderRef[10]); creditCard[15].setCustomer(customerRef[9]); getEntityManager().merge(creditCard[15]); doFlush(); TLogger.log("Setting additional relationships for Customer 11"); aliasRef[25].getCustomers().add(customerRef[10]); getEntityManager().merge(aliasRef[25]); aliasRef[26].getCustomers().add(customerRef[10]); getEntityManager().merge(aliasRef[26]); aliasRef[28].getCustomers().add(customerRef[10]); getEntityManager().merge(aliasRef[28]); orderRef[11].setCustomer(customerRef[10]); getEntityManager().merge(orderRef[11]); creditCard[16].setCustomer(customerRef[10]); getEntityManager().merge(creditCard[16]); doFlush(); TLogger.log("Setting additional relationships for Customer 12"); aliasRef[24].getCustomers().add(customerRef[11]); getEntityManager().merge(aliasRef[24]); orderRef[12].setCustomer(customerRef[11]); getEntityManager().merge(orderRef[12]); creditCard[17].setCustomer(customerRef[11]); getEntityManager().merge(creditCard[17]); doFlush(); TLogger.log("Setting additional relationships for Customer 13"); aliasRef[20].getCustomers().add(customerRef[12]); getEntityManager().merge(aliasRef[20]); orderRef[13].setCustomer(customerRef[12]); getEntityManager().merge(orderRef[13]); creditCard[18].setCustomer(customerRef[12]); getEntityManager().merge(creditCard[18]); doFlush(); TLogger.log("Setting additional relationships for Customer 14"); aliasRef[22].getCustomers().add(customerRef[13]); getEntityManager().merge(aliasRef[22]); aliasRef[27].getCustomers().add(customerRef[13]); getEntityManager().merge(aliasRef[27]); orderRef[14].setCustomer(customerRef[13]); getEntityManager().merge(orderRef[14]); orderRef[15].setCustomer(customerRef[13]); getEntityManager().merge(orderRef[15]); creditCard[19].setCustomer(customerRef[13]); getEntityManager().merge(creditCard[19]); doFlush(); TLogger.log("Setting additional relationships for Customer 15"); // No Aliases orderRef[16].setCustomer(customerRef[14]); getEntityManager().merge(orderRef[16]); creditCard[20].setCustomer(customerRef[14]); getEntityManager().merge(creditCard[20]); doFlush(); TLogger.log("Setting additional relationships for Customer 16"); // No Aliases orderRef[17].setCustomer(customerRef[15]); getEntityManager().merge(orderRef[17]); creditCard[21].setCustomer(customerRef[15]); getEntityManager().merge(creditCard[21]); doFlush(); TLogger.log("Setting additional relationships for Customer 17"); // No Aliases orderRef[18].setCustomer(customerRef[16]); getEntityManager().merge(orderRef[18]); creditCard[22].setCustomer(customerRef[16]); getEntityManager().merge(creditCard[22]); doFlush(); TLogger.log("Setting additional relationships for Customer 18"); // No Aliases orderRef[19].setCustomer(customerRef[17]); getEntityManager().merge(orderRef[19]); creditCard[23].setCustomer(customerRef[17]); getEntityManager().merge(creditCard[23]); doFlush(); TLogger.log("Done with createRelationships"); getEntityTransaction().commit(); } }
true
973dbef1d339d2ecf8cec7fd696f39c7ea5e666b
Java
Astroware/FAMIS
/FireAlertMobileInspectionSystem/src/com/astroware/famis/LocationScreen.java
UTF-8
5,250
2.125
2
[]
no_license
package com.astroware.famis; import java.util.ArrayList; import controlClasses.DigitsToPixels; import controlClasses.LocationControl; import entityClasses.*; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; public class LocationScreen extends Activity { private ArrayList<Button> locationButtons; private EditText searchbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location_screen); searchbar = (EditText)findViewById(R.id.searchbar2); Button back = (Button)findViewById(R.id.locationback); Button search =(Button)findViewById(R.id.buttonsearch); Button home = (Button)findViewById(R.id.locationhome); //Receive the intent from the previous activity and retrieve the passed Client object Intent in =getIntent(); int clientIndex = in.getIntExtra("selectedClient", -1); if (clientIndex != -1) { LocationControl.getInstance().setClient(clientIndex); createButtons(); } //Creates a listener for when the back button is pressed back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // Graham finish(); overridePendingTransition(R.anim.slide_out_right, R.anim.slide_in_right); } }); //Creates a listener for when the search button is pressed search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub createButtons(); } }); //Creates a listener for when the home button is pressed home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LocationScreen.this, ClientScreen.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); //finish(); //startActivity(new Intent (LocationScreen.this, ClientScreen.class)); } }); } //Currently a placeholder for the xml parse for client locations public void locationParse(Client currentClient) { currentClient.m_serviceAddress = new ArrayList<ServiceAddress>(); currentClient.m_serviceAddress.add(new ServiceAddress("S1","123 Sesame Street","N6G 2P4", "", "London", "Ontario", "Canada","ID001","20131009 09:49PM", 1234)); } //Create a an array of buttons for each location under the current client. Each button will be the same and will have //the service address on it public void createButtons() { locationButtons = new ArrayList<Button>(); TableLayout tl = (TableLayout)findViewById(R.id.locationtable); LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,DigitsToPixels.dpToPixel(50, getBaseContext())); tl.removeAllViews(); locationButtons.removeAll(locationButtons); tl.invalidate(); for (int i=0; i<LocationControl.getInstance().getLocationListSize(); i++) { locationButtons.add(new Button(this)); if (LocationControl.getInstance().getLocation(i).getAddress().toLowerCase().startsWith(searchbar.getText().toString().toLowerCase().trim())){ locationButtons.get(i).setText(LocationControl.getInstance().getLocation(i).getAddress()); locationButtons.get(i).setBackgroundResource(R.drawable.client_button); locationButtons.get(i).setTextColor(Color.parseColor("white")); locationButtons.get(i).setTypeface(null, Typeface.BOLD_ITALIC); locationButtons.get(i).setTextSize(20); tl.addView(locationButtons.get(i), lp); //final int j was created because a final int is required inside of the onClick function final int j=i; locationButtons.get(i).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in= new Intent(LocationScreen.this, EquipmentScreen.class); in.putExtra("selectedLocation", j); startActivity(in); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left); } }); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.login_screen, menu); return true; } //Overrides when the back button is pressed @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition(R.anim.slide_out_right, R.anim.slide_in_right); } public boolean onTouchEvent(MotionEvent event) { InputMethodManager IMM = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); IMM.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); return true; } }
true
e6a31ba58b30ca8e905600bf434aabea8f3e8d91
Java
DucMystery/api-book
/src/main/java/com/example/managerbookapi/model/Book.java
UTF-8
410
2.125
2
[]
no_license
package com.example.managerbookapi.model; import lombok.Getter; import lombok.Setter; import javax.persistence.*; @Entity @Setter @Getter public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private String author; @ManyToOne private Category category; }
true
971a80b83ab5f1b9fa07eff8839a3e0000474fc3
Java
fluorumlabs/disconnect-project
/disconnect-spring-integration/src/main/java/com/github/fluorumlabs/disconnect/spring/server/DynamicStream.java
UTF-8
41,341
2.859375
3
[ "Apache-2.0" ]
permissive
package com.github.fluorumlabs.disconnect.spring.server; import java.util.Comparator; import java.util.Iterator; import java.util.Optional; import java.util.Spliterator; import java.util.function.*; import java.util.stream.*; /** * Created by Artem Godin on 2/12/2020. */ public class DynamicStream<T> implements Stream<T> { private final DynamicSpliterator<T> spliterator = new DynamicSpliterator<>(); private final Stream<T> stream = StreamSupport.stream(spliterator, true); public DynamicStream(){} public void push(T value) { spliterator.push(value); } public void complete() { stream.close(); spliterator.complete(); } public void completeExceptionally(RuntimeException e) { stream.close(); spliterator.completeExceptionally(e); } /** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to each element to determine if it * should be included * * @return the new stream */ @Override public Stream<T> filter(Predicate<? super T> predicate) { return stream.filter(predicate); } /** * Returns a stream consisting of the results of applying the given * function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * * @return the new stream */ @Override public <R> Stream<R> map(Function<? super T, ? extends R> mapper) { return stream.map(mapper); } /** * Returns an {@code IntStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps"> * intermediate operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * * @return the new stream */ @Override public IntStream mapToInt(ToIntFunction<? super T> mapper) { return stream.mapToInt(mapper); } /** * Returns a {@code LongStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * * @return the new stream */ @Override public LongStream mapToLong(ToLongFunction<? super T> mapper) { return stream.mapToLong(mapper); } /** * Returns a {@code DoubleStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * * @return the new stream */ @Override public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) { return stream.mapToDouble(mapper); } /** * Returns a stream consisting of the results of replacing each element of * this stream with the contents of a mapped stream produced by applying * the provided mapping function to each element. Each mapped stream is * {@link BaseStream#close() closed} after its contents * have been placed into this stream. (If a mapped stream is {@code null} * an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces a stream * of new values * * @return the new stream * * The {@code flatMap()} operation has the effect of applying a one-to-many * transformation to the elements of the stream, and then flattening the * resulting elements into a new stream. * * <p><b>Examples.</b> * * <p>If {@code orders} is a stream of purchase orders, and each purchase * order contains a collection of line items, then the following produces a * stream containing all the line items in all the orders: * <pre>{@code * orders.flatMap(order -> order.getLineItems().stream())... * }</pre> * * <p>If {@code path} is the path to a file, then the following produces a * stream of the {@code words} contained in that file: * <pre>{@code * Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8); * Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +"))); * }</pre> * The {@code mapper} function passed to {@code flatMap} splits a line, * using a simple regular expression, into an array of words, and then * creates a stream of words from that array. */ @Override public <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) { return stream.flatMap(mapper); } /** * Returns an {@code IntStream} consisting of the results of replacing each * element of this stream with the contents of a mapped stream produced by * applying the provided mapping function to each element. Each mapped * stream is {@link BaseStream#close() closed} after its * contents have been placed into this stream. (If a mapped stream is * {@code null} an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces a stream * of new values * * @return the new stream * * @see #flatMap(Function) */ @Override public IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper) { return stream.flatMapToInt(mapper); } /** * Returns an {@code LongStream} consisting of the results of replacing each * element of this stream with the contents of a mapped stream produced by * applying the provided mapping function to each element. Each mapped * stream is {@link BaseStream#close() closed} after its * contents have been placed into this stream. (If a mapped stream is * {@code null} an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces a stream * of new values * * @return the new stream * * @see #flatMap(Function) */ @Override public LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper) { return stream.flatMapToLong(mapper); } /** * Returns an {@code DoubleStream} consisting of the results of replacing * each element of this stream with the contents of a mapped stream produced * by applying the provided mapping function to each element. Each mapped * stream is {@link BaseStream#close() closed} after its * contents have placed been into this stream. (If a mapped stream is * {@code null} an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces a stream * of new values * * @return the new stream * * @see #flatMap(Function) */ @Override public DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) { return stream.flatMapToDouble(mapper); } /** * Returns a stream consisting of the distinct elements (according to * {@link Object#equals(Object)}) of this stream. * * <p>For ordered streams, the selection of distinct elements is stable * (for duplicated elements, the element appearing first in the encounter * order is preserved.) For unordered streams, no stability guarantees * are made. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the new stream * * Preserving stability for {@code distinct()} in parallel pipelines is * relatively expensive (requires that the operation act as a full barrier, * with substantial buffering overhead), and stability is often not needed. * Using an unordered stream source (such as {@link #generate(Supplier)}) * or removing the ordering constraint with {@link #unordered()} may result * in significantly more efficient execution for {@code distinct()} in parallel * pipelines, if the semantics of your situation permit. If consistency * with encounter order is required, and you are experiencing poor performance * or memory utilization with {@code distinct()} in parallel pipelines, * switching to sequential execution with {@link #sequential()} may improve * performance. */ @Override public Stream<T> distinct() { return stream.distinct(); } /** * Returns a stream consisting of the elements of this stream, sorted * according to natural order. If the elements of this stream are not * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown * when the terminal operation is executed. * * <p>For ordered streams, the sort is stable. For unordered streams, no * stability guarantees are made. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the new stream */ @Override public Stream<T> sorted() { return stream.sorted(); } /** * Returns a stream consisting of the elements of this stream, sorted * according to the provided {@code Comparator}. * * <p>For ordered streams, the sort is stable. For unordered streams, no * stability guarantees are made. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * {@code Comparator} to be used to compare stream elements * * @return the new stream */ @Override public Stream<T> sorted(Comparator<? super T> comparator) { return stream.sorted(comparator); } /** * Returns a stream consisting of the elements of this stream, additionally * performing the provided action on each element as elements are consumed * from the resulting stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * <p>For parallel stream pipelines, the action may be called at * whatever time and in whatever thread the element is made available by the * upstream operation. If the action modifies shared state, * it is responsible for providing the required synchronization. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements as * they are consumed from the stream * * @return the new stream * * This method exists mainly to support debugging, where you want * to see the elements as they flow past a certain point in a pipeline: * <pre>{@code * Stream.of("one", "two", "three", "four") * .filter(e -> e.length() > 3) * .peek(e -> System.out.println("Filtered value: " + e)) * .map(String::toUpperCase) * .peek(e -> System.out.println("Mapped value: " + e)) * .collect(Collectors.toList()); * }</pre> */ @Override public Stream<T> peek(Consumer<? super T> action) { return stream.peek(action); } /** * Returns a stream consisting of the elements of this stream, truncated * to be no longer than {@code maxSize} in length. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * stateful intermediate operation</a>. * * @param maxSize the number of elements the stream should be limited to * * @return the new stream * * @throws IllegalArgumentException if {@code maxSize} is negative * While {@code limit()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code maxSize}, since {@code limit(n)} * is constrained to return not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(Supplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code limit()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code limit()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. */ @Override public Stream<T> limit(long maxSize) { return stream.limit(maxSize); } /** * Returns a stream consisting of the remaining elements of this stream * after discarding the first {@code n} elements of the stream. * If this stream contains fewer than {@code n} elements then an * empty stream will be returned. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @param n the number of leading elements to skip * * @return the new stream * * @throws IllegalArgumentException if {@code n} is negative * While {@code skip()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code n}, since {@code skip(n)} * is constrained to skip not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(Supplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code skip()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code skip()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. */ @Override public Stream<T> skip(long n) { return stream.skip(n); } /** * Performs an action for each element of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * <p>The behavior of this operation is explicitly nondeterministic. * For parallel stream pipelines, this operation does <em>not</em> * guarantee to respect the encounter order of the stream, as doing so * would sacrifice the benefit of parallelism. For any given element, the * action may be performed at whatever time and in whatever thread the * library chooses. If the action accesses shared state, it is * responsible for providing the required synchronization. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements */ @Override public void forEach(Consumer<? super T> action) { stream.forEach(action); } /** * Performs an action for each element of this stream, in the encounter * order of the stream if the stream has a defined encounter order. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * <p>This operation processes the elements one at a time, in encounter * order if one exists. Performing the action for one element * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> * performing the action for subsequent elements, but for any given element, * the action may be performed in whatever thread the library chooses. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements * * @see #forEach(Consumer) */ @Override public void forEachOrdered(Consumer<? super T> action) { stream.forEachOrdered(action); } /** * Returns an array containing the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an array containing the elements of this stream */ @Override public Object[] toArray() { return stream.toArray(); } /** * Returns an array containing the elements of this stream, using the * provided {@code generator} function to allocate the returned array, as * well as any additional arrays that might be required for a partitioned * execution or for resizing. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param generator a function which produces a new array of the desired * type and the provided length * * @return an array containing the elements in this stream * * @throws ArrayStoreException if the runtime type of the array returned * from the array generator is not a supertype of the runtime type of every * element in this stream * The generator function takes an integer, which is the size of the * desired array, and produces an array of the desired size. This can be * concisely expressed with an array constructor reference: * <pre>{@code * Person[] men = people.stream() * .filter(p -> p.getGender() == MALE) * .toArray(Person[]::new); * }</pre> */ @Override public <A> A[] toArray(IntFunction<A[]> generator) { return stream.toArray(generator); } /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using the provided identity value and an * <a href="package-summary.html#Associativity">associative</a> * accumulation function, and returns the reduced value. This is equivalent * to: * <pre>{@code * T result = identity; * for (T element : this stream) * result = accumulator.apply(result, element) * return result; * }</pre> * <p> * but is not constrained to execute sequentially. * * <p>The {@code identity} value must be an identity for the accumulator * function. This means that for all {@code t}, * {@code accumulator.apply(identity, t)} is equal to {@code t}. * The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param identity the identity value for the accumulating function * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * * @return the result of the reduction * * Sum, min, max, average, and string concatenation are all special * cases of reduction. Summing a stream of numbers can be expressed as: * * <pre>{@code * Integer sum = integers.reduce(0, (a, b) -> a+b); * }</pre> * <p> * or: * * <pre>{@code * Integer sum = integers.reduce(0, Integer::sum); * }</pre> * * <p>While this may seem a more roundabout way to perform an aggregation * compared to simply mutating a running total in a loop, reduction * operations parallelize more gracefully, without needing additional * synchronization and with greatly reduced risk of data races. */ @Override public T reduce(T identity, BinaryOperator<T> accumulator) { return stream.reduce(identity, accumulator); } /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using an * <a href="package-summary.html#Associativity">associative</a> accumulation * function, and returns an {@code Optional} describing the reduced value, * if any. This is equivalent to: * <pre>{@code * boolean foundAny = false; * T result = null; * for (T element : this stream) { * if (!foundAny) { * foundAny = true; * result = element; * } * else * result = accumulator.apply(result, element); * } * return foundAny ? Optional.of(result) : Optional.empty(); * }</pre> * <p> * but is not constrained to execute sequentially. * * <p>The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * * @return an {@link Optional} describing the result of the reduction * * @throws NullPointerException if the result of the reduction is null * @see #reduce(Object, BinaryOperator) * @see #min(Comparator) * @see #max(Comparator) */ @Override public Optional<T> reduce(BinaryOperator<T> accumulator) { return stream.reduce(accumulator); } /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using the provided identity, accumulation and * combining functions. This is equivalent to: * <pre>{@code * U result = identity; * for (T element : this stream) * result = accumulator.apply(result, element) * return result; * }</pre> * <p> * but is not constrained to execute sequentially. * * <p>The {@code identity} value must be an identity for the combiner * function. This means that for all {@code u}, {@code combiner(identity, u)} * is equal to {@code u}. Additionally, the {@code combiner} function * must be compatible with the {@code accumulator} function; for all * {@code u} and {@code t}, the following must hold: * <pre>{@code * combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param identity the identity value for the combiner function * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for incorporating an additional element into a result * @param combiner an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values, which must be * compatible with the accumulator function * * @return the result of the reduction * * Many reductions using this form can be represented more simply * by an explicit combination of {@code map} and {@code reduce} operations. * The {@code accumulator} function acts as a fused mapper and accumulator, * which can sometimes be more efficient than separate mapping and reduction, * such as when knowing the previously reduced value allows you to avoid * some computation. * @see #reduce(BinaryOperator) * @see #reduce(Object, BinaryOperator) */ @Override public <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner) { return stream.reduce(identity, accumulator, combiner); } /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream. A mutable * reduction is one in which the reduced value is a mutable result container, * such as an {@code ArrayList}, and elements are incorporated by updating * the state of the result rather than by replacing the result. This * produces a result equivalent to: * <pre>{@code * R result = supplier.get(); * for (T element : this stream) * accumulator.accept(result, element); * return result; * }</pre> * * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations * can be parallelized without requiring additional synchronization. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for incorporating an additional element into a result * @param combiner an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values, which must be * compatible with the accumulator function * * @return the result of the reduction * * There are many existing classes in the JDK whose signatures are * well-suited for use with method references as arguments to {@code collect()}. * For example, the following will accumulate strings into an {@code ArrayList}: * <pre>{@code * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, * ArrayList::addAll); * }</pre> * * <p>The following will take a stream of strings and concatenates them into a * single string: * <pre>{@code * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, * StringBuilder::append) * .toString(); * }</pre> */ @Override public <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner) { return stream.collect(supplier, accumulator, combiner); } /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream using a * {@code Collector}. A {@code Collector} * encapsulates the functions used as arguments to * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of * collection strategies and composition of collect operations such as * multiple-level grouping or partitioning. * * <p>If the stream is parallel, and the {@code Collector} * is {@link Collector.Characteristics#CONCURRENT concurrent}, and * either the stream is unordered or the collector is * {@link Collector.Characteristics#UNORDERED unordered}, * then a concurrent reduction will be performed (see {@link Collector} for * details on concurrent reduction.) * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * <p>When executed in parallel, multiple intermediate results may be * instantiated, populated, and merged so as to maintain isolation of * mutable data structures. Therefore, even when executed in parallel * with non-thread-safe data structures (such as {@code ArrayList}), no * additional synchronization is needed for a parallel reduction. * * @param collector the {@code Collector} describing the reduction * * @return the result of the reduction * * The following will accumulate strings into an ArrayList: * <pre>{@code * List<String> asList = stringStream.collect(Collectors.toList()); * }</pre> * * <p>The following will classify {@code Person} objects by city: * <pre>{@code * Map<String, List<Person>> peopleByCity * = personStream.collect(Collectors.groupingBy(Person::getCity)); * }</pre> * * <p>The following will classify {@code Person} objects by state and city, * cascading two {@code Collector}s together: * <pre>{@code * Map<String, Map<String, List<Person>>> peopleByStateAndCity * = personStream.collect(Collectors.groupingBy(Person::getState, * Collectors.groupingBy(Person::getCity))); * }</pre> * @see #collect(Supplier, BiConsumer, BiConsumer) * @see Collectors */ @Override public <R, A> R collect(Collector<? super T, A, R> collector) { return stream.collect(collector); } /** * Returns the minimum element of this stream according to the provided * {@code Comparator}. This is a special case of a * <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * {@code Comparator} to compare elements of this stream * * @return an {@code Optional} describing the minimum element of this stream, * or an empty {@code Optional} if the stream is empty * * @throws NullPointerException if the minimum element is null */ @Override public Optional<T> min(Comparator<? super T> comparator) { return stream.min(comparator); } /** * Returns the maximum element of this stream according to the provided * {@code Comparator}. This is a special case of a * <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * {@code Comparator} to compare elements of this stream * * @return an {@code Optional} describing the maximum element of this stream, * or an empty {@code Optional} if the stream is empty * * @throws NullPointerException if the maximum element is null */ @Override public Optional<T> max(Comparator<? super T> comparator) { return stream.max(comparator); } /** * Returns the count of elements in this stream. This is a special case of * a <a href="package-summary.html#Reduction">reduction</a> and is * equivalent to: * <pre>{@code * return mapToLong(e -> 1L).sum(); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @return the count of elements in this stream */ @Override public long count() { return stream.count(); } /** * Returns whether any elements of this stream match the provided * predicate. May not evaluate the predicate on all elements if not * necessary for determining the result. If the stream is empty then * {@code false} is returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} * * This method evaluates the <em>existential quantification</em> of the * predicate over the elements of the stream (for some x P(x)). */ @Override public boolean anyMatch(Predicate<? super T> predicate) { return stream.anyMatch(predicate); } /** * Returns whether all elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} * * This method evaluates the <em>universal quantification</em> of the * predicate over the elements of the stream (for all x P(x)). If the * stream is empty, the quantification is said to be <em>vacuously * satisfied</em> and is always {@code true} (regardless of P(x)). */ @Override public boolean allMatch(Predicate<? super T> predicate) { return stream.allMatch(predicate); } /** * Returns whether no elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} * * This method evaluates the <em>universal quantification</em> of the * negated predicate over the elements of the stream (for all x ~P(x)). If * the stream is empty, the quantification is said to be vacuously satisfied * and is always {@code true}, regardless of P(x). */ @Override public boolean noneMatch(Predicate<? super T> predicate) { return stream.noneMatch(predicate); } /** * Returns an {@link Optional} describing the first element of this stream, * or an empty {@code Optional} if the stream is empty. If the stream has * no encounter order, then any element may be returned. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @return an {@code Optional} describing the first element of this stream, * or an empty {@code Optional} if the stream is empty * * @throws NullPointerException if the element selected is null */ @Override public Optional<T> findFirst() { return stream.findFirst(); } /** * Returns an {@link Optional} describing some element of the stream, or an * empty {@code Optional} if the stream is empty. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * <p>The behavior of this operation is explicitly nondeterministic; it is * free to select any element in the stream. This is to allow for maximal * performance in parallel operations; the cost is that multiple invocations * on the same source may not return the same result. (If a stable result * is desired, use {@link #findFirst()} instead.) * * @return an {@code Optional} describing some element of this stream, or an * empty {@code Optional} if the stream is empty * * @throws NullPointerException if the element selected is null * @see #findFirst() */ @Override public Optional<T> findAny() { return stream.findAny(); } /** * Returns an iterator for the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return the element iterator for this stream */ @Override public Iterator<T> iterator() { return stream.iterator(); } /** * Returns a spliterator for the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return the element spliterator for this stream */ @Override public Spliterator<T> spliterator() { return stream.spliterator(); } /** * Returns whether this stream, if a terminal operation were to be executed, * would execute in parallel. Calling this method after invoking an * terminal stream operation method may yield unpredictable results. * * @return {@code true} if this stream would execute in parallel if executed */ @Override public boolean isParallel() { return stream.isParallel(); } /** * Returns an equivalent stream that is sequential. May return * itself, either because the stream was already sequential, or because * the underlying stream state was modified to be sequential. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a sequential stream */ @Override public Stream<T> sequential() { return stream.sequential(); } /** * Returns an equivalent stream that is parallel. May return * itself, either because the stream was already parallel, or because * the underlying stream state was modified to be parallel. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a parallel stream */ @Override public Stream<T> parallel() { return stream.parallel(); } /** * Returns an equivalent stream that is * <a href="package-summary.html#Ordering">unordered</a>. May return * itself, either because the stream was already unordered, or because * the underlying stream state was modified to be unordered. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return an unordered stream */ @Override public Stream<T> unordered() { return stream.unordered(); } /** * Returns an equivalent stream with an additional close handler. Close * handlers are run when the {@link #close()} method * is called on the stream, and are executed in the order they were * added. All close handlers are run, even if earlier close handlers throw * exceptions. If any close handler throws an exception, the first * exception thrown will be relayed to the caller of {@code close()}, with * any remaining exceptions added to that exception as suppressed exceptions * (unless one of the remaining exceptions is the same exception as the * first exception, since an exception cannot suppress itself.) May * return itself. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param closeHandler A task to execute when the stream is closed * * @return a stream with a handler that is run if the stream is closed */ @Override public Stream<T> onClose(Runnable closeHandler) { return stream.onClose(closeHandler); } /** * Closes this stream, causing all close handlers for this stream pipeline * to be called. * * @see AutoCloseable#close() */ @Override public void close() { complete(); } }
true
1f8f0938913eb00ed956cdf126e795e846c6eca6
Java
Lyanel/Milker
/src/modele/carac/MilkCoin.java
UTF-8
2,137
2.734375
3
[ "MIT" ]
permissive
package modele.carac; import modele.ParseMilkFile; import modele.baseObject.MilkVar; import org.w3c.dom.Element; public class MilkCoin extends MilkVar { public static final String xmlCoin = "coin"; // Fields private Float coin; // Constructors public MilkCoin() { this((float) 0); } public MilkCoin(Float coin) { super(); this.setCoin(coin); } public MilkCoin(Element milkElement) { super(); this.setValueFromNode(milkElement); } public MilkCoin(MilkCoin original) { super(original); this.coin = new Float(original.getCoin()); } // Set value from Element methods @Override public void setValueFromNode(Element milkElement) { super.setValueFromNode(milkElement); this.setCoin(milkElement); } public void setCoin(Element milkElement) { Float temp=null; temp=ParseMilkFile.getXmlFloatAttribute(milkElement,xmlCoin); if (temp != null) this.coin=temp; } /* @Override public void setNullValueFromNode(Element milkElement) { super.setNullValueFromNode(milkElement); this.setNullCoin(milkElement); } public void setNullCoin(Element milkElement) { coin = ParseMilkFile.getXmlFloatAttribute(milkElement,xmlCoin); }*/ // field methods public Float getCoin() { return this.coin; } public String getStringCoin() { String temp = null; if (this.coin != null) temp = " "+xmlCoin+" : "+this.coin+". "; return temp; } public String getXmlCoin() { String temp = null; if (this.coin != null) temp = " "+xmlCoin+"=\""+coin+"\""; return temp; } public void setCoin(Float coin) { this.coin = coin; } // toString & toXml methods @Override public String toStringAttrib() { String temp = super.toStringAttrib(); temp+=this.getStringCoin(); return temp; } @Override public String toXmlAttrib() { String temp = super.toXmlAttrib(); temp+=this.getXmlCoin(); return temp; } // other object methods @Override public boolean allZero() { boolean temp = super.allZero(); if(this.coin!=null && this.coin!=0) temp= false; return temp; } }
true
bf91eaaf8b0eaae1b624d263377ab1288b7dcf53
Java
dzlongju/JavaLearningTest
/src/Mashu_Price/Control.java
UTF-8
3,621
2.3125
2
[]
no_license
package Mashu_Price; import java.util.List; public class Control { //类目表信息 String[] catelist = {"网店/网络服务/软件", "包装", "电动车/配件/交通工具", "居家布艺", "五金/工具", "家庭/个人清洁工具", "模玩/动漫/周边/cos/桌游", "自行车/骑行装备/零配件", "节庆用品/礼品", "彩妆/香水/美妆工具", "鲜花速递/花卉仿真/绿植园艺", "厨房/烹饪用具", "收纳整理", "宠物/宠物食品及用品", "家居饰品", "饰品/流行首饰/时尚饰品新", "零食/坚果/特产", "粮油米面/南北干货/调味品", "餐饮具", "玩具/童车/益智/积木/模型", "居家日用", "美发护发/假发", "美容护肤/美体/精油", "个性定制/设计服务/DIY", "尿片/洗护/喂哺/推车床", "洗护清洁剂/卫生巾/纸/香薰", "女士内衣/男士内衣/家居服", "手表", "电子/电工", "床上用品", "童装/婴儿装/亲子装", "女装/女士精品", "服饰配件/皮带/帽子/围巾", "ZIPPO/瑞士军刀/眼镜", "孕妇装/孕产妇用品/营养", "汽车/用品/配件/改装", "运动/瑜伽/健身/球迷用品", "童鞋/婴儿鞋/亲子鞋", "运动包/户外包/配件", "女鞋", "男装", "箱包皮具/热销女包/男包", "咖啡/麦片/冲饮", "运动服/休闲服装", "流行男鞋", "运动鞋new", "家装主材", "户外/登山/野营/旅行用品", "珠宝/钻石/翡翠/黄金" }; Double[] priceslist = {2.0, 2.8, 3.95, 5.049609959, 6.763636364, 7.080151515, 7.436, 8.593333333, 8.633448276, 11.27222222, 12.5, 13.45928571, 13.65580111, 13.83, 15.68090909, 15.78871279, 17.36125, 18.13333333, 19.1358209, 19.68488372, 20.22032609, 21.145, 23.93878788, 23.95, 34.49022727, 38.2613198, 41.34622567, 52.25736842, 58.33, 74.178, 76.46709267, 81.12874182, 81.54100433, 93.6393578, 96.35045117, 109.1118182, 109.2680038, 154.2501149, 185.0927556, 189.1726093, 199.2539982, 204.9510895, 226.3485356, 287.3677014, 353.2020548, 452.52478, 622.171261, 627.0589622, 899.0 }; public static void main(String[] args) { //获取类目平均价格表 Control cc = new Control(); String[] catelist = cc.catelist; Double[] priceslist = cc.priceslist; // 获取店铺类目下的价格表 GoodsList gl=new GoodsList(100); String[] shopcatelist = gl.catename; Double[] pl = gl.goodprice; Match m = new Match(); List matchs = m.matching(shopcatelist, pl, catelist, priceslist); //分箱的标准:分成四个区间,区间生成由类目平均价格和参数生成 //参数设置 Double[] parameter = {0.666667, 2.5, 5.0}; //分类目分箱,打印结果,并把结果放入列表 anaresult中 FengXiang fx = new FengXiang(); List anaresult = fx.feng(matchs, parameter); } }
true
3a0c65fa240be27096b51d42072ae094877ad9cc
Java
SmartToolFactory/Bluetooth-LE-Smart-Tutorials
/Bluetooth-LE-library/src/test/java/uk/co/alt236/bluetoothlelib/device/beacon/BeaconUtilsTest.java
UTF-8
896
2.140625
2
[]
no_license
package uk.co.alt236.bluetoothlelib.device.beacon; import junit.framework.TestCase; /** * */ public class BeaconUtilsTest extends TestCase { public void testGetBeaconTypeIBeacon() throws Exception { assertEquals(BeaconType.IBEACON, BeaconUtils.getBeaconType(new byte[]{ 0x4C, 0x00, 0x02, 0x15, 0x00, // <- Magic iBeacon header 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })); } public void testGetBeaconTypeInvalid() throws Exception { assertEquals(BeaconType.NOT_A_BEACON, BeaconUtils.getBeaconType((byte[]) null)); assertEquals(BeaconType.NOT_A_BEACON, BeaconUtils.getBeaconType(new byte[0])); assertEquals(BeaconType.NOT_A_BEACON, BeaconUtils.getBeaconType(new byte[25])); } }
true
d22fbcc753eeb86e5a4f6a0cb5b24606e4166c1e
Java
rogerio121/geracontrato
/src/main/java/br/com/geracontrato/model/Imovel.java
UTF-8
2,186
2.015625
2
[]
no_license
package br.com.geracontrato.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "imovel") public class Imovel { @Id @GeneratedValue @Column(name = "imov_id") int idImovel; @Column(name = "imov_numero") int numero; @Column(name = "imov_comodos") int comodos; @Column(name = "imov_valor_numero") double valorEmNumero; @Column(name = "imov_rua") String rua; @Column(name = "imov_bairro") String bairro; @Column(name = "imov_cidade") String cidade; @Column(name = "imov_uf") String uf; @Column(name = "imov_cep") String cep; @Column(name = "imov_valor_extenso") String valorExtenso; @Column(name = "usu_cpf") String cpfUsuario; public int getIdImovel() { return idImovel; } public void setIdImovel(int idImovel) { this.idImovel = idImovel; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public int getComodos() { return comodos; } public void setComodos(int comodos) { this.comodos = comodos; } public double getValorEmNumero() { return valorEmNumero; } public void setValorEmNumero(double valorEmNumero) { this.valorEmNumero = valorEmNumero; } public String getRua() { return rua; } public void setRua(String rua) { this.rua = rua; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } public String getUf() { return uf; } public void setUf(String uf) { this.uf = uf; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public String getValorExtenso() { return valorExtenso; } public void setValorExtenso(String valorExtenso) { this.valorExtenso = valorExtenso; } public String getCpfUsuario() { return cpfUsuario; } public void setCpfUsuario(String cpfUsuario) { this.cpfUsuario = cpfUsuario; } }
true
05da73a5c421b412548c06ddd288bcbc8ef09d01
Java
6uonp/androiddev2020
/USTHWeather/app/src/main/java/vn/edu/usth/usthweather/ForecastFragment.java
UTF-8
5,678
2.234375
2
[]
no_license
package vn.edu.usth.usthweather; import android.app.ActionBar; import android.graphics.Typeface; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import org.w3c.dom.Text; public class ForecastFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment LinearLayout forecast = new LinearLayout(getActivity()); forecast.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); forecast.setOrientation(LinearLayout.HORIZONTAL); forecast.setPadding(28,30,0,20); LinearLayout day = new LinearLayout(getActivity()); day.setLayoutParams(new LinearLayout.MarginLayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); day.setOrientation(LinearLayout.VERTICAL); day.setBackgroundColor(0xFF2D5D76); TextView mon = new TextView(getActivity()); mon.setText("Mon"); mon.setPadding(40,20,0,0); mon.setTextSize(24); TextView tue = new TextView(getActivity()); tue.setText("Tue"); tue.setPadding(40,100,0,0); tue.setTextSize(24); TextView wed = new TextView(getActivity()); wed.setText("Wed"); wed.setPadding(40,100,0,0); wed.setTextSize(24); TextView thu = new TextView(getActivity()); thu.setText("Thu"); thu.setPadding(40,100,0,0); thu.setTextSize(24); TextView fri = new TextView(getActivity()); fri.setText("Fri"); fri.setPadding(40,100,0,0); fri.setTextSize(24); TextView sat = new TextView(getActivity()); sat.setText("Sat"); sat.setPadding(40,100,0,0); sat.setTextSize(24); TextView sun = new TextView(getActivity()); sun.setText("Sun"); sun.setPadding(40,100,0,20); sun.setTextSize(24); day.addView(mon); day.addView(tue); day.addView(wed); day.addView(thu); day.addView(fri); day.addView(sat); day.addView(sun); LinearLayout weathericon = new LinearLayout(getActivity()); weathericon.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); weathericon.setOrientation(LinearLayout.VERTICAL); weathericon.setBackgroundColor(0xFF2D5D76); TextView snow = new TextView(getActivity()); snow.setCompoundDrawablesWithIntrinsicBounds(R.drawable.snow, 0, 0, 0); snow.setText("Snow day"); snow.setPadding(20,20,0,0); snow.setCompoundDrawablePadding(50); snow.setTextSize(24); TextView sunny = new TextView(getActivity()); sunny.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sunny, 0, 0, 0); sunny.setText("It hot outside"); sunny.setPadding(20,100,0,0); sunny.setCompoundDrawablePadding(50); sunny.setTextSize(24); TextView windy = new TextView(getActivity()); windy.setCompoundDrawablesWithIntrinsicBounds(R.drawable.windy,0,0,0); windy.setText("Strong wind caution"); windy.setPadding(20,100,0,0); windy.setCompoundDrawablePadding(50); windy.setTextSize(24); TextView rain__heavy = new TextView(getActivity()); rain__heavy.setCompoundDrawablesWithIntrinsicBounds(R.drawable.heavy_rain,0,0,0); rain__heavy.setText("Don't forget your raincoat"); rain__heavy.setPadding(20,100,0,0); rain__heavy.setCompoundDrawablePadding(50); rain__heavy.setTextSize(24); TextView rain = new TextView(getActivity()); rain.setCompoundDrawablesWithIntrinsicBounds(R.drawable.moderate_rain,0,0,0); rain.setText("Bring your umbrella"); rain.setPadding(20,100,0,0); rain.setCompoundDrawablePadding(50); rain.setTextSize(24); TextView overcast = new TextView(getActivity()); overcast.setCompoundDrawablesWithIntrinsicBounds(R.drawable.overcast,0,0,0); overcast.setText("The weather seem sad"); overcast.setPadding(20,100,0,0); overcast.setCompoundDrawablePadding(50); overcast.setTextSize(24); TextView thunder = new TextView(getActivity()); thunder.setCompoundDrawablesWithIntrinsicBounds(R.drawable.thunder, 0, 0, 0); thunder.setText("Stay inside"); thunder.setPadding(20,100,0,20); thunder.setCompoundDrawablePadding(50); thunder.setTextSize(24); weathericon.addView(snow); weathericon.addView(sunny); weathericon.addView(windy); weathericon.addView(rain); weathericon.addView(overcast); weathericon.addView(rain__heavy); weathericon.addView(thunder); forecast.addView(day); forecast.addView(weathericon); return forecast; } }
true
24ef8484747777b0c679895171de27696d8e3dad
Java
GodLikeEcho/HVZ-GO
/HvZUI/app/src/main/java/redacted/hvzui/A_chat_room.java
UTF-8
1,114
2.203125
2
[]
no_license
package redacted.hvzui; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.webkit.WebSettings; import android.webkit.WebView; /** * Main class to create a webView */ public class A_chat_room extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // pulls the all chat layout from the layouts folder setContentView(R.layout.activity_a_chat_room); // declaires a webView variable named myWebView and sets it to the id from // the webview window created in the layout WebView myWebView = (WebView) findViewById(R.id.webView3); // cleares any residual data from the last use. myWebView.clearCache(true); // pulls default behavior settings for the webview WebSettings webSettings = myWebView.getSettings(); // enables java script to run in the web page webSettings.setJavaScriptEnabled(true); // loads the desired web page myWebView.loadUrl("http://www.achat.hvz-go.com/"); } }
true
d5cd1560c4dc8877827626d46e952e76fad5e0da
Java
joana-team/WALA
/com.ibm.wala.util/src/com/ibm/wala/util/intset/EmptyIntSet.java
UTF-8
1,894
2.46875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2011 - IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.util.intset; import java.util.NoSuchElementException; public class EmptyIntSet implements IntSet { private static final long serialVersionUID = 5116475799916663164L; public static final EmptyIntSet instance = new EmptyIntSet(); @Override public boolean contains(int i) { return false; } @Override public boolean containsAny(IntSet set) { return false; } @Override public IntSet intersection(IntSet that) { return this; } @Override public IntSet union(IntSet that) { return that; } @Override public boolean isEmpty() { return true; } @Override public int size() { return 0; } private static final IntIterator emptyIter = new IntIterator() { @Override public boolean hasNext() { return false; } @Override public int next() { throw new NoSuchElementException(); } }; @Override public IntIterator intIterator() { return emptyIter; } @Override public IntIterator intIteratorSorted() { return emptyIter; } @Override public void foreach(IntSetAction action) { } @Override public void foreachExcluding(IntSet X, IntSetAction action) { } @Override public int max() { throw new NoSuchElementException(); } @Override public boolean sameValue(IntSet that) { return that.isEmpty(); } @Override public boolean isSubset(IntSet that) { return true; } }
true
8ed226da25424af8b1a28774d69358bceab4aac0
Java
rootmelo92118/analysis
/sources/com/p051vm/p062vo/login/LoginResp.java
UTF-8
835
2.125
2
[]
no_license
package com.p051vm.p062vo.login; import java.io.Serializable; /* renamed from: com.vm.vo.login.LoginResp */ public class LoginResp implements Serializable { private String authKey; private Long memberId; private String token; public Long getMemberId() { return this.memberId; } public void setMemberId(Long l) { this.memberId = l; } public String getToken() { return this.token; } public void setToken(String str) { this.token = str; } public String getAuthKey() { return this.authKey; } public void setAuthKey(String str) { this.authKey = str; } public String toString() { return "LoginResp{memberId=" + this.memberId + ", token='" + this.token + '\'' + ", authKey='" + this.authKey + '\'' + '}'; } }
true
3725fd6d3543820edc58162f4be5a52bad1cd604
Java
scrocchia/kata-tennis
/kata-tennis/src/kata/tennis/play/Scores.java
UTF-8
4,961
2.984375
3
[]
no_license
package kata.tennis.play; import kata.tennis.entity.Player; import java.util.Random; public class Scores { private Player firstPlayer; private Player secondPlayer; public static final String ADVANTAGE = "ADVANTAGE"; public static final String DEUCE = "DEUCE"; public static String END_MATCH = "THE GAME IS OVER"; public static String GAME_SCORE = "Game score :\n%s : %s\n%s : %s"; public static String FULL_GAME_SCORE = "Set score :\n%s : %s\n%s : %s\n%s"; public Scores(Player firstPlayer, Player secondPlayer){ this.firstPlayer = firstPlayer; this.secondPlayer = secondPlayer; } public void setRandomPoints() { int random = new Random().nextInt(2) + 1; switch (random){ case 1 : firstPlayer.winsPoint(); break; case 2 : secondPlayer.winsPoint(); break; default: break; } } public String getSetPoints() { String gamePoint; if (firstPlayer.getSetPoints() == 6 && secondPlayer.getSetPoints() == 6) { gamePoint = checkTieBreak(); } else { gamePoint = checkGamePoints(); } Player playerWinningSet = Player.getPlayerWinningSet(firstPlayer,secondPlayer); if (playerWinningSet.getSetPoints() >= 6) { if (Math.abs(firstPlayer.getSetPoints() - secondPlayer.getSetPoints()) >= 2) { return displayMatchScore(playerWinningSet, firstPlayer, secondPlayer, gamePoint, true); } } return displayMatchScore(playerWinningSet, firstPlayer, secondPlayer, gamePoint, false); } public String checkTieBreak() { Player playerWinningMatch = Player.getPlayerWinningMatch(firstPlayer,secondPlayer); if (playerWinningMatch.checkGamePoints() >= 7 && Math.abs(firstPlayer.checkGamePoints() - secondPlayer.checkGamePoints()) >= 2) { int incrementSetScore = playerWinningMatch.getSetPoints(); playerWinningMatch.setSetScore(incrementSetScore++); Player.resetGamePoints(firstPlayer,secondPlayer); return String.format(GAME_SCORE + "\n%s %s", firstPlayer.getName(), firstPlayer.checkGamePoints(), secondPlayer.getName(), secondPlayer.checkGamePoints(), playerWinningMatch.getName(), END_MATCH); } return String.format(GAME_SCORE, firstPlayer.getName(), firstPlayer.checkGamePoints(), secondPlayer.getName(), secondPlayer.checkGamePoints()); } public String checkGamePoints() { Player playerWinningMatch; if (firstPlayer.checkGamePoints() >= 3 && secondPlayer.checkGamePoints() >= 3) { if (Math.abs(firstPlayer.checkGamePoints() - secondPlayer.checkGamePoints()) > 1) { playerWinningMatch = Player.getPlayerWinningMatch(firstPlayer,secondPlayer); int incrementSetScore = playerWinningMatch.getSetPoints(); incrementSetScore++; playerWinningMatch.setSetScore(incrementSetScore); Player.resetGamePoints(firstPlayer,secondPlayer); return String.format(GAME_SCORE, firstPlayer.getName(), firstPlayer.displayPoints(), secondPlayer.getName(), secondPlayer.displayPoints()); } else { if (firstPlayer.checkGamePoints() == secondPlayer.checkGamePoints()){ return DEUCE; } else { playerWinningMatch = Player.getPlayerWinningMatch(firstPlayer,secondPlayer); return String.format("%s %s", ADVANTAGE,playerWinningMatch.getName()); } } } else { playerWinningMatch = Player.getPlayerWinningMatch(firstPlayer,secondPlayer); if (playerWinningMatch.checkGamePoints() >= 4) { playerWinningMatch = Player.getPlayerWinningMatch(firstPlayer,secondPlayer); int incrementSetScore = playerWinningMatch.getSetPoints(); incrementSetScore++; playerWinningMatch.setSetScore(incrementSetScore); Player.resetGamePoints(firstPlayer,secondPlayer); } return String.format(GAME_SCORE, firstPlayer.getName(), firstPlayer.displayPoints(), secondPlayer.getName(), secondPlayer.displayPoints()); } } private String displayMatchScore(Player playerWinningMatch, Player firstPlayer, Player secondPlayer, String gamePoint, boolean setEnded){ String setEndMessage = setEnded ? String.format("\n%s %s", playerWinningMatch.getName(), END_MATCH) : ""; return String.format(FULL_GAME_SCORE, firstPlayer.getName(), firstPlayer.getSetPoints(), secondPlayer.getName(), secondPlayer.getSetPoints(), gamePoint) + setEndMessage; } }
true
e2bf394bbe647b8233ccb4b698ee96d21d2c2bfb
Java
zhixiandev/trans1
/bdi-dx/src/main/java/com/bdi/sp/vo/Naver.java
UTF-8
776
2.0625
2
[]
no_license
package com.bdi.sp.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; public class Naver { private Message message; public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } @JsonIgnoreProperties(ignoreUnknown=true) public class Message{ private Result result; public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } @JsonIgnoreProperties(ignoreUnknown=true) public class Result{ private String translatedText; public String getTranslatedText() { return translatedText; } public void setTranslatedText(String translatedText) { this.translatedText = translatedText; } } } }
true
6404e4d34b1e35a4f568e60dd49b3bcaae0f189a
Java
arielcarlos757/AMSS
/amdocs-api-common-web-services/amdocs-api-common-abp-ws/src/main/java/com/practia/abp/exception/AACWSException.java
UTF-8
635
2.25
2
[]
no_license
package com.practia.abp.exception; import javax.xml.ws.WebFault; import com.practia.abp.exception.fault.MessageFault; @WebFault(name="AACWSException") public class AACWSException extends Exception { public static final long serialVersionUID = 1L; public MessageFault messageFault; public AACWSException(String message, Throwable aNestedException) { super(message,aNestedException); this.messageFault = MessageFault.MessageFactory(aNestedException); } public MessageFault getMessageFault() { return messageFault; } public void setMessageFault(MessageFault messageFault) { this.messageFault = messageFault; } }
true
f056b170851fbdbcfba56641de9b57da3bd21e59
Java
cga2351/code
/DecompiledViberSrc/app/src/main/java/com/google/android/gms/internal/ads/zzu.java
UTF-8
429
1.859375
2
[]
no_license
package com.google.android.gms.internal.ads; public enum zzu { static { zzu[] arrayOfzzu = new zzu[4]; arrayOfzzu[0] = zzav; arrayOfzzu[1] = zzaw; arrayOfzzu[2] = zzax; arrayOfzzu[3] = zzay; } } /* Location: E:\Study\Tools\apktool2_2\dex2jar-0.0.9.15\classes_viber_2_dex2jar.jar * Qualified Name: com.google.android.gms.internal.ads.zzu * JD-Core Version: 0.6.2 */
true
8b28958458812d5148ece4b3df96eaddb32fc3ba
Java
jburgosortega/EmpresaCable
/src/capaGui/MenuPackCanales.java
UTF-8
22,354
2.046875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package capaGui; import capaDatos.DatosCliente; import capaDatos.DatosProductos; import capaDatos.DatosServicios; import capaNegocio.NegocioProductos; import capaNegocio.NegocioServicios; import java.util.ArrayList; import java.util.Calendar; import javax.swing.JOptionPane; /** * * @author Johnny y karo */ public class MenuPackCanales extends javax.swing.JDialog { /** * Creates new form MenuCanales */ public MenuPackCanales(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setLocationRelativeTo(null); llenarNombre(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); lblTitulo = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); btnAgregar = new javax.swing.JButton(); cmbPackElegir = new javax.swing.JComboBox(); btnMostrat = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); txtNombre = new javax.swing.JTextField(); lblTipo = new javax.swing.JLabel(); txtTipo = new javax.swing.JTextField(); lblPrecio = new javax.swing.JLabel(); txtPrecio = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); cmbCanales = new javax.swing.JComboBox(); jPanel5 = new javax.swing.JPanel(); btnSalir = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel2.setBackground(new java.awt.Color(204, 0, 0)); jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); lblTitulo.setFont(new java.awt.Font("Comic Sans MS", 1, 36)); // NOI18N lblTitulo.setForeground(new java.awt.Color(255, 255, 255)); lblTitulo.setText("Elige tus Canales"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(102, 102, 102) .addComponent(lblTitulo) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(42, Short.MAX_VALUE) .addComponent(lblTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) ); jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); btnAgregar.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N btnAgregar.setText("Agregar"); btnAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAgregarActionPerformed(evt); } }); cmbPackElegir.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N cmbPackElegir.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione..." })); btnMostrat.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnMostrat.setText("Mostrar"); btnMostrat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnMostratActionPerformed(evt); } }); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 255))); txtNombre.setEditable(false); txtNombre.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblTipo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N lblTipo.setText("Tipo"); txtTipo.setEditable(false); txtTipo.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N lblPrecio.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N lblPrecio.setText("Precio"); txtPrecio.setEditable(false); txtPrecio.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setText("$"); cmbCanales.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N cmbCanales.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Canales en Pack" })); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtNombre) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblTipo) .addGap(18, 18, 18) .addComponent(txtTipo, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblPrecio) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(cmbCanales, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(cmbCanales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblTipo) .addComponent(txtTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(7, 7, 7) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPrecio) .addComponent(jLabel1) .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(205, 205, 205) .addComponent(btnAgregar)) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(cmbPackElegir, javax.swing.GroupLayout.PREFERRED_SIZE, 378, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btnMostrat))) .addGap(0, 34, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmbPackElegir, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnMostrat)) .addGap(18, 18, 18) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnAgregar) .addContainerGap()) ); jPanel5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); btnSalir.setFont(new java.awt.Font("Comic Sans MS", 1, 12)); // NOI18N btnSalir.setText("Salir"); btnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalirActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(btnSalir) .addContainerGap(30, Short.MAX_VALUE)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnSalir) .addContainerGap()) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(205, 205, 205) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 14, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed int a = (int) Math.round((Math.random() * 10000)); NegocioServicios neg = new NegocioServicios(); if (this.cmbPackElegir.getSelectedIndex() == DatosServicios.getComparar2()) { JOptionPane.showMessageDialog(this, "Ud. Ya tiene este Pack en sus Servicios", "Error de Ingreso", JOptionPane.ERROR_MESSAGE); this.btnMostrat.requestFocus(); return; } Calendar cal1 = Calendar.getInstance(); DatosServicios asd = new DatosServicios(); DatosProductos dsa = new DatosProductos(); if (a != DatosServicios.getComparar2()) { dsa.setIdPackCanales(this.cmbPackElegir.getSelectedIndex()); asd.setIdContratado((a)); asd.setRutCliente(DatosCliente.Comparar2); asd.setFechaContratacion((+cal1.get(Calendar.YEAR) + "-" + (cal1.get(Calendar.MONTH)+1) + "-" + cal1.get(Calendar.DATE))); neg.ingresarDatos(asd); neg.ingresarContratoCanales(asd , dsa); } else { JOptionPane.showMessageDialog(this, "Ud. Esta seguro de Contratar este Pack?", "Error de Ingreso", JOptionPane.ERROR_MESSAGE); this.btnAgregar.requestFocus(); return; } JOptionPane.showMessageDialog(this, "Ingreso Exito", "Bienvenido!", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_btnAgregarActionPerformed private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed this.dispose(); }//GEN-LAST:event_btnSalirActionPerformed private void btnMostratActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostratActionPerformed MostraridContratados(); System.out.println(DatosServicios.getComparar2()); this.cmbCanales.removeAllItems(); if (this.cmbPackElegir.getSelectedIndex() != 0) { NegocioProductos neg = new NegocioProductos(); DatosProductos acad = neg.buscarDatosPackCanales((this.cmbPackElegir.getSelectedIndex())); this.txtNombre.setText(acad.getNombrePackCanales()); this.txtTipo.setText(acad.getTipoPackCanales()); this.txtPrecio.setText("" + acad.getPrecioPackCanales()); //////////////////////////////////////////////////////////////////////// llenarCanal(); //////////////////////////////////////////////////////////////////////// } else { JOptionPane.showMessageDialog(this, "Seleccione Pack de Canales", "Error de Ingreso", JOptionPane.ERROR_MESSAGE); this.cmbPackElegir.requestFocus(); } }//GEN-LAST:event_btnMostratActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MenuPackCanales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuPackCanales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuPackCanales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuPackCanales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { MenuPackCanales dialog = new MenuPackCanales(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAgregar; private javax.swing.JButton btnMostrat; private javax.swing.JButton btnSalir; private javax.swing.JComboBox cmbCanales; private javax.swing.JComboBox cmbPackElegir; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JLabel lblPrecio; private javax.swing.JLabel lblTipo; private javax.swing.JLabel lblTitulo; private javax.swing.JTextField txtNombre; private javax.swing.JTextField txtPrecio; private javax.swing.JTextField txtTipo; // End of variables declaration//GEN-END:variables private void llenarNombre() { NegocioProductos neg2 = new NegocioProductos(); ArrayList<DatosProductos> lista2 = neg2.getDatos(); for (int i = 0; i < lista2.size(); i++) { DatosProductos sv = lista2.get(i); this.cmbPackElegir.addItem(sv.getNombre()); } } private void llenarCanal() { NegocioProductos neg = new NegocioProductos(); ArrayList<DatosProductos> listaCanal = neg.getDatosCanal(); for (int i = 0; i < listaCanal.size(); i++) { DatosProductos sv = listaCanal.get(i); if (this.cmbPackElegir.getSelectedIndex() == sv.getIdCanal()) { this.cmbCanales.addItem(sv.getNombreCanal()); } } } private void MostraridContratados() { NegocioServicios neg = new NegocioServicios(); ArrayList<DatosServicios> listaidDatosServicioses = neg.getDatosServicios(); for (int i = 0; i < listaidDatosServicioses.size(); i++) { DatosServicios sv = listaidDatosServicioses.get(i); DatosServicios.setComparar2(sv.getIdContratado()); } } }
true
0be74d3ba61d2e2c83dd03cbdc7a27b3ff57f285
Java
raminDutt/CoreJava
/src/main/java/coreJava/Line.java
UTF-8
743
3.359375
3
[]
no_license
package coreJava; import annotations.Serializable; @Serializable public class Line { Point from; Point to; Point center; public Line() { this(null,null); } public Line(Point from, Point to) { this.from=from; this.to=to; } //@Override public Point getCenter() { double cx = (to.getX()+from.getX())/2; double cy = (from.getY()+from.getY())/2; center = new Point(cx, cy); return center; } @Override public Line clone() throws CloneNotSupportedException { Line line = (Line)super.clone(); line.from = this.from.clone(); line.to=this.to.clone(); return line; } public String toString() { String result = "[from=" + to + " " + "to=" + to + " " + "center=" + center +"]"; return result; } }
true
d9577b270d537b59e8bad32c1d19d2ea0e47934a
Java
LennartSannen/java_boxing-administration
/src/main/java/com/defence/administration/model/Member.java
UTF-8
3,941
2.0625
2
[]
no_license
package com.defence.administration.model; import java.time.LocalDate; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.SequenceGenerator; @Entity public class Member { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "member_id_generator") @SequenceGenerator(name="member_id_generator", sequenceName = "member_id_seq", allocationSize=1) private Long id; private String firstName; private String middleName; private String lastName; private LocalDate paidUntil; private String IBAN; private String streetWithNr; private String zipCode; private String residence; private LocalDate dateOfBirth; private Long phoneHome; private Long phoneMobile; private String email; private Boolean isTrainer = false; private Boolean isSender = false; @Lob private byte[] image; @ManyToMany(mappedBy = "members") private Set <Training> trainings = new HashSet<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public LocalDate getPaidUntil() { return paidUntil; } public void setPaidUntil(LocalDate paidUntil) { this.paidUntil = paidUntil; } public String getIBAN() { return IBAN; } public void setIBAN(String IBAN) { this.IBAN = IBAN; } public String getStreetWithNr() { return streetWithNr; } public void setStreetWithNr(String streetWithNr) { this.streetWithNr = streetWithNr; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getResidence() { return residence; } public void setResidence(String residence) { this.residence = residence; } public LocalDate getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(LocalDate dateOfBirth) { this.dateOfBirth = dateOfBirth; } public Long getPhoneHome() { return phoneHome; } public void setPhoneHome(Long phoneHome) { this.phoneHome = phoneHome; } public Long getPhoneMobile() { return phoneMobile; } public void setPhoneMobile(Long phoneMobile) { this.phoneMobile = phoneMobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Boolean getIsTrainer() { return isTrainer; } public void setIsTrainer(Boolean isTrainer) { this.isTrainer = isTrainer; } public Boolean getIsSender() { return isSender; } public void setIsSender(Boolean isSender) { this.isSender = isSender; } public void setTrainings(Set<Training> trainings) { this.trainings = trainings; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } }
true
b967efa2b48bb3591de3a8ff9a967ad14c8e5ffe
Java
hzhh123/beetn
/src/main/java/com/hd/controller/bpmn/ProcessDefinitionController.java
UTF-8
4,120
2.359375
2
[]
no_license
package com.hd.controller.bpmn; import com.hd.controller.base.BaseController; import com.hd.entity.ProcessDefinitionEntity; import com.hd.util.PageInfo; import org.activiti.engine.HistoryService; import org.activiti.engine.RepositoryService; import org.activiti.engine.history.HistoricTaskInstance; import org.activiti.engine.repository.ProcessDefinition; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * 流程定义管理Controller * @author user * */ @Controller @RequestMapping("/processDefinition") public class ProcessDefinitionController extends BaseController{ @Resource private RepositoryService repositoryService; @Resource private HistoryService historyService; /** * 流程定义查询列表 * @param page * @param limit * @param name * @return */ @ResponseBody @RequestMapping("dataGrid") public Object dataGrid(Integer page,Integer limit,String name){ if(name==null){ name=""; } PageInfo info=new PageInfo(page,limit); List<ProcessDefinition>processDefinitions=repositoryService.createProcessDefinitionQuery() .orderByProcessDefinitionId().desc()//根据流程定义id降序查询 .processDefinitionNameLike(""+name+"%")// 根据流程定义名称模糊查询 .listPage(page,limit);//返回带分页的查询结果结合 long total=repositoryService.createProcessDefinitionQuery().processDefinitionNameLike("%"+name+"%").count(); // 获取总记录数 List<ProcessDefinitionEntity>processDefinitionEntities=new ArrayList<ProcessDefinitionEntity>(); for (ProcessDefinition processDefinition:processDefinitions){ ProcessDefinitionEntity processDefinitionEntity=new ProcessDefinitionEntity(); processDefinitionEntity.setId(processDefinition.getId()); processDefinitionEntity.setName(processDefinition.getName()); processDefinitionEntity.setDiagramResourceName(processDefinition.getDiagramResourceName()); processDefinitionEntity.setRevision(processDefinition.getVersion()); } info.setData(processDefinitions); info.setCount(total); return info; } /** * 查看流程图 * @param deploymentId * @param diagramResourceName * @param response * @return * @throws Exception */ @RequestMapping("/showView") public String showView(String deploymentId,String diagramResourceName,HttpServletResponse response)throws Exception{ InputStream inputStream=repositoryService.getResourceAsStream(deploymentId, diagramResourceName); OutputStream out=response.getOutputStream(); for(int b=-1;(b=inputStream.read())!=-1;){ out.write(b); } out.close(); inputStream.close(); return null; } /** * 查看流程图 * @param * @param response * @return * @throws Exception */ @RequestMapping("/showViewByTaskId") public String showViewByTaskId(String taskId,HttpServletResponse response)throws Exception{ HistoricTaskInstance hti=historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult(); String processDefinitionId=hti.getProcessDefinitionId(); // 获取流程定义id ProcessDefinition pd=repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult(); InputStream inputStream=repositoryService.getResourceAsStream(pd.getDeploymentId(), pd.getDiagramResourceName()); OutputStream out=response.getOutputStream(); for(int b=-1;(b=inputStream.read())!=-1;){ out.write(b); } out.close(); inputStream.close(); return null; } }
true
dcc1c6a950cda350b6b4772d6750deaaddb82933
Java
nzrscc/MMSpring
/src/main/java/it/mastermind/mmspring/services/CombinationService.java
UTF-8
230
1.765625
2
[]
no_license
package it.mastermind.mmspring.services; public interface CombinationService { int[] check(int[] valori_inseriti, int[] soluzione); int save(String username); String getSoluzioneByUsername(String username); }
true
7d4b1868fb9a5e1861bd8b31c1c606b264bfa0e6
Java
ribeiro2008/calypte
/src/test/java/calypte/TXCacheHelper.java
UTF-8
1,518
2.4375
2
[]
no_license
/* * Calypte http://calypte.uoutec.com.br/ * Copyright (C) 2018 UoUTec. (calypte@uoutec.com.br) * * 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 calypte; import calypte.tx.TXCache; /** * * @author Ribeiro * */ public class TXCacheHelper { public static abstract class ConcurrentTask extends Thread{ private Throwable error; private TXCache cache; private Object value; private String key; private Object value2; public ConcurrentTask(TXCache cache, String key, Object value, Object value2) { this.cache = cache; this.value = value; this.key = key; this.value2 = value2; } public void run(){ try{ this.execute(cache, key, value, value2); } catch(Throwable e){ this.error = e; } } protected abstract void execute(TXCache cache, String key, Object value, Object value2) throws Throwable; public Throwable getError() { return error; } } }
true