id
int64
22
34.9k
original_code
stringlengths
31
107k
code_wo_comment
stringlengths
29
77.3k
cleancode
stringlengths
25
62.1k
repo
stringlengths
6
65
label
sequencelengths
4
4
30,838
@Override public String getAdditionalProposalInfo() { try { ASTNode coveringNode = mContext.getCoveringNode(); int start = coveringNode.getStartPosition(); int length = coveringNode.getLength(); IBuffer buffer = mContext.getCompilationUnit().getBuffer(); StringBuilder sb = new StringBuilder(); String string = buffer.getText(start, length); string = ExtractStringRefactoring.unquoteAttrValue(string); String token = ExtractStringInputPage.guessId(string); // Look up the beginning and the end of the line (outside of the extracted string) // such that we can show a preview of the diff, e.g. if you have // foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello); // so we need to extract "foo.setTitle(" and ");". // Look backwards to the beginning of the line (and strip whitespace) int i = start - 1; while (i > 0) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i--; } String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim(); // Look forwards to the end of the line (and strip whitespace) i = start + length; while (i < buffer.getLength()) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i++; } String lineSuffix = buffer.getText(start + length, i - (start + length)); // Should we show the replacement as just R.string.foo or // context.getString(R.string.foo) ? boolean useContext = false; ASTNode parent = coveringNode.getParent(); if (parent != null) { int type = parent.getNodeType(); if (type == ASTNode.ASSIGNMENT || type == ASTNode.VARIABLE_DECLARATION_STATEMENT || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT || type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) { useContext = true; } } // Display .java change: sb.append("...<br>"); //$NON-NLS-1$ sb.append(linePrefix); sb.append("<b>"); //$NON-NLS-1$ if (useContext) { sb.append("context.getString("); //$NON-NLS-1$ } sb.append("R.string."); //$NON-NLS-1$ sb.append(token); if (useContext) { sb.append(")"); //$NON-NLS-1$ } sb.append("</b>"); //$NON-NLS-1$ sb.append(lineSuffix); sb.append("<br>...<br>"); //$NON-NLS-1$ // Display strings.xml change: sb.append("<br>"); //$NON-NLS-1$ sb.append("&lt;resources&gt;<br>"); //$NON-NLS-1$ sb.append(" <b>&lt;string name=\""); //$NON-NLS-1$ sb.append(token); sb.append("\"&gt;"); //$NON-NLS-1$ sb.append(string); sb.append("&lt;/string&gt;</b><br>"); //$NON-NLS-1$ sb.append("&lt;/resources&gt;"); //$NON-NLS-1$ return sb.toString(); } catch (JavaModelException e) { AdtPlugin.log(e, null); } return "Initiates the Extract String refactoring operation"; }
@Override public String getAdditionalProposalInfo() { try { ASTNode coveringNode = mContext.getCoveringNode(); int start = coveringNode.getStartPosition(); int length = coveringNode.getLength(); IBuffer buffer = mContext.getCompilationUnit().getBuffer(); StringBuilder sb = new StringBuilder(); String string = buffer.getText(start, length); string = ExtractStringRefactoring.unquoteAttrValue(string); String token = ExtractStringInputPage.guessId(string); int i = start - 1; while (i > 0) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i--; } String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim(); i = start + length; while (i < buffer.getLength()) { char c = buffer.getChar(i); if (c == '\r' || (c == '\n')) { break; } i++; } String lineSuffix = buffer.getText(start + length, i - (start + length)); boolean useContext = false; ASTNode parent = coveringNode.getParent(); if (parent != null) { int type = parent.getNodeType(); if (type == ASTNode.ASSIGNMENT || type == ASTNode.VARIABLE_DECLARATION_STATEMENT || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT || type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) { useContext = true; } } sb.append("...<br>"); sb.append(linePrefix); sb.append("<b>"); if (useContext) { sb.append("context.getString("); } sb.append("R.string."); sb.append(token); if (useContext) { sb.append(")"); } sb.append("</b>"); sb.append(lineSuffix); sb.append("<br>...<br>"); sb.append("<br>"); sb.append("&lt;resources&gt;<br>"); sb.append(" <b>&lt;string name=\""); sb.append(token); sb.append("\"&gt;"); sb.append(string); sb.append("&lt;/string&gt;</b><br>"); sb.append("&lt;/resources&gt;"); return sb.toString(); } catch (JavaModelException e) { AdtPlugin.log(e, null); } return "Initiates the Extract String refactoring operation"; }
@override public string getadditionalproposalinfo() { try { astnode coveringnode = mcontext.getcoveringnode(); int start = coveringnode.getstartposition(); int length = coveringnode.getlength(); ibuffer buffer = mcontext.getcompilationunit().getbuffer(); stringbuilder sb = new stringbuilder(); string string = buffer.gettext(start, length); string = extractstringrefactoring.unquoteattrvalue(string); string token = extractstringinputpage.guessid(string); int i = start - 1; while (i > 0) { char c = buffer.getchar(i); if (c == '\r' || (c == '\n')) { break; } i--; } string lineprefix = buffer.gettext(i + 1, start - (i + 1)).trim(); i = start + length; while (i < buffer.getlength()) { char c = buffer.getchar(i); if (c == '\r' || (c == '\n')) { break; } i++; } string linesuffix = buffer.gettext(start + length, i - (start + length)); boolean usecontext = false; astnode parent = coveringnode.getparent(); if (parent != null) { int type = parent.getnodetype(); if (type == astnode.assignment || type == astnode.variable_declaration_statement || type == astnode.variable_declaration_fragment || type == astnode.variable_declaration_expression) { usecontext = true; } } sb.append("...<br>"); sb.append(lineprefix); sb.append("<b>"); if (usecontext) { sb.append("context.getstring("); } sb.append("r.string."); sb.append(token); if (usecontext) { sb.append(")"); } sb.append("</b>"); sb.append(linesuffix); sb.append("<br>...<br>"); sb.append("<br>"); sb.append("&lt;resources&gt;<br>"); sb.append(" <b>&lt;string name=\""); sb.append(token); sb.append("\"&gt;"); sb.append(string); sb.append("&lt;/string&gt;</b><br>"); sb.append("&lt;/resources&gt;"); return sb.tostring(); } catch (javamodelexception e) { adtplugin.log(e, null); } return "initiates the extract string refactoring operation"; }
jiangshide/sdk
[ 1, 0, 0, 0 ]
22,747
public void waitFor(String name,Cmd command,Context context,String input, long timeout, TimeUnit unit){ //TODO use scheduled task to implement timeout Waiter waiter = new Waiter(command,context,input); waitFor(name,waiter); }
public void waitFor(String name,Cmd command,Context context,String input, long timeout, TimeUnit unit){ Waiter waiter = new Waiter(command,context,input); waitFor(name,waiter); }
public void waitfor(string name,cmd command,context context,string input, long timeout, timeunit unit){ waiter waiter = new waiter(command,context,input); waitfor(name,waiter); }
johnaohara/qDup
[ 0, 1, 0, 0 ]
30,944
@Override protected FilterResults performFiltering(CharSequence constraint) { List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>(); List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>(); //----------- search = false, filter = false ---------------- if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) { filteredList.addAll(searchAllCosts); //----------- search = false, filter = true ---------------- } else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) { if (categoriesForFilter != null && tagsForFilter == null) { for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { for (String category : categoriesForFilter) { if (category.equals(item.getCostEntry().getCategory())) { filteredList.add(item); } } } } else if (categoriesForFilter == null && tagsForFilter != null) { //todo bug for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { for (String tag : tagsForFilter) { if (item.getTagNames().contains(tag)) { if (!filteredList.contains(item)) { filteredList.add(item); } } } } } else if (categoriesForFilter != null && tagsForFilter != null) { for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { for (String category : categoriesForFilter) { if (category.equals(item.getCostEntry().getCategory())) { filteredListHelper.add(item); } } } for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) { for (String tag : tagsForFilter) { if (item.getTagNames().contains(tag)) { if (!filteredList.contains(item)) { filteredList.add(item); } } } } } //----------- search = true, filter = false ---------------- } else if (constraint.length() != 0) { String filterPattern = constraint.toString().toLowerCase().trim(); for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) { filteredList.add(item); } } } // TODO: simultaneously search what is filtered and filter what is searched FilterResults results = new FilterResults(); results.values = filteredList; Log.d("kraj metode", "testt"); return results; }
@Override protected FilterResults performFiltering(CharSequence constraint) { List<DailyExpenseTagsWithPicsPojo> filteredListHelper = new ArrayList<>(); List<DailyExpenseTagsWithPicsPojo> filteredList = new ArrayList<>(); if ((constraint == null || constraint.length() == 0) && (categoriesForFilter == null || categoriesForFilter.size() == 0) && (tagsForFilter == null || tagsForFilter.size() == 0)) { filteredList.addAll(searchAllCosts); } else if ((constraint == null || constraint.length() == 0) && (categoriesForFilter != null || tagsForFilter != null)) { if (categoriesForFilter != null && tagsForFilter == null) { for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { for (String category : categoriesForFilter) { if (category.equals(item.getCostEntry().getCategory())) { filteredList.add(item); } } } } else if (categoriesForFilter == null && tagsForFilter != null) { for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { for (String tag : tagsForFilter) { if (item.getTagNames().contains(tag)) { if (!filteredList.contains(item)) { filteredList.add(item); } } } } } else if (categoriesForFilter != null && tagsForFilter != null) { for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { for (String category : categoriesForFilter) { if (category.equals(item.getCostEntry().getCategory())) { filteredListHelper.add(item); } } } for (DailyExpenseTagsWithPicsPojo item : filteredListHelper) { for (String tag : tagsForFilter) { if (item.getTagNames().contains(tag)) { if (!filteredList.contains(item)) { filteredList.add(item); } } } } } } else if (constraint.length() != 0) { String filterPattern = constraint.toString().toLowerCase().trim(); for (DailyExpenseTagsWithPicsPojo item : searchAllCosts) { if (item.getCostEntry().getName().toLowerCase().contains(filterPattern)) { filteredList.add(item); } } } FilterResults results = new FilterResults(); results.values = filteredList; Log.d("kraj metode", "testt"); return results; }
@override protected filterresults performfiltering(charsequence constraint) { list<dailyexpensetagswithpicspojo> filteredlisthelper = new arraylist<>(); list<dailyexpensetagswithpicspojo> filteredlist = new arraylist<>(); if ((constraint == null || constraint.length() == 0) && (categoriesforfilter == null || categoriesforfilter.size() == 0) && (tagsforfilter == null || tagsforfilter.size() == 0)) { filteredlist.addall(searchallcosts); } else if ((constraint == null || constraint.length() == 0) && (categoriesforfilter != null || tagsforfilter != null)) { if (categoriesforfilter != null && tagsforfilter == null) { for (dailyexpensetagswithpicspojo item : searchallcosts) { for (string category : categoriesforfilter) { if (category.equals(item.getcostentry().getcategory())) { filteredlist.add(item); } } } } else if (categoriesforfilter == null && tagsforfilter != null) { for (dailyexpensetagswithpicspojo item : searchallcosts) { for (string tag : tagsforfilter) { if (item.gettagnames().contains(tag)) { if (!filteredlist.contains(item)) { filteredlist.add(item); } } } } } else if (categoriesforfilter != null && tagsforfilter != null) { for (dailyexpensetagswithpicspojo item : searchallcosts) { for (string category : categoriesforfilter) { if (category.equals(item.getcostentry().getcategory())) { filteredlisthelper.add(item); } } } for (dailyexpensetagswithpicspojo item : filteredlisthelper) { for (string tag : tagsforfilter) { if (item.gettagnames().contains(tag)) { if (!filteredlist.contains(item)) { filteredlist.add(item); } } } } } } else if (constraint.length() != 0) { string filterpattern = constraint.tostring().tolowercase().trim(); for (dailyexpensetagswithpicspojo item : searchallcosts) { if (item.getcostentry().getname().tolowercase().contains(filterpattern)) { filteredlist.add(item); } } } filterresults results = new filterresults(); results.values = filteredlist; log.d("kraj metode", "testt"); return results; }
jkandcoding/QuantiTanti_1
[ 0, 1, 1, 0 ]
22,765
private Object convert(final Field field, final Val val) { if (field != null && field.getFormat() != null && field.getFormat().getType() != null) { final Type type = field.getFormat().getType(); if (Type.NUMBER.equals(type) || Type.DATE_TIME.equals(type)) { return val.toDouble(); } } return val.toString(); }
private Object convert(final Field field, final Val val) { if (field != null && field.getFormat() != null && field.getFormat().getType() != null) { final Type type = field.getFormat().getType(); if (Type.NUMBER.equals(type) || Type.DATE_TIME.equals(type)) { return val.toDouble(); } } return val.toString(); }
private object convert(final field field, final val val) { if (field != null && field.getformat() != null && field.getformat().gettype() != null) { final type type = field.getformat().gettype(); if (type.number.equals(type) || type.date_time.equals(type)) { return val.todouble(); } } return val.tostring(); }
gcdev373/stroom-query
[ 1, 0, 0, 0 ]
14,676
@Override public Set<OperatorSet> detectPropertyOnline( SearchState relevantState, SearchTree tree) { Set<OperatorSet> result = new HashSet<OperatorSet>(); //TODO: shouldn't this be in-fact an offline detector? relevantState = tree.getSentState(relevantState.iparentID); if(relevantState == null) return result; //TODO: optimize for(SearchState s1 : relevantState.successors){ for(SearchState s2 : relevantState.successors){ if(s1.stateID != s2.stateID){ OperatorSet opSet = new OperatorSet(EnumPrivacyProperty.PRIVATELY_NONDETERMINISTIC,true); opSet.addAll(s1.responsibleOperators); opSet.retainAll(s2.responsibleOperators); if(!opSet.isEmpty()){ result.add(opSet); } } } } return result; }
@Override public Set<OperatorSet> detectPropertyOnline( SearchState relevantState, SearchTree tree) { Set<OperatorSet> result = new HashSet<OperatorSet>(); relevantState = tree.getSentState(relevantState.iparentID); if(relevantState == null) return result; for(SearchState s1 : relevantState.successors){ for(SearchState s2 : relevantState.successors){ if(s1.stateID != s2.stateID){ OperatorSet opSet = new OperatorSet(EnumPrivacyProperty.PRIVATELY_NONDETERMINISTIC,true); opSet.addAll(s1.responsibleOperators); opSet.retainAll(s2.responsibleOperators); if(!opSet.isEmpty()){ result.add(opSet); } } } } return result; }
@override public set<operatorset> detectpropertyonline( searchstate relevantstate, searchtree tree) { set<operatorset> result = new hashset<operatorset>(); relevantstate = tree.getsentstate(relevantstate.iparentid); if(relevantstate == null) return result; for(searchstate s1 : relevantstate.successors){ for(searchstate s2 : relevantstate.successors){ if(s1.stateid != s2.stateid){ operatorset opset = new operatorset(enumprivacyproperty.privately_nondeterministic,true); opset.addall(s1.responsibleoperators); opset.retainall(s2.responsibleoperators); if(!opset.isempty()){ result.add(opset); } } } } return result; }
gree7/privacy-analysis
[ 1, 0, 0, 0 ]
14,772
@Override public BundleDetails extract(final InputStream inputStream) throws IOException { try (final JarInputStream jarInputStream = new JarInputStream(inputStream)) { final Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { throw new IllegalArgumentException("NAR bundles must contain a valid MANIFEST"); } final Attributes attributes = manifest.getMainAttributes(); final String groupId = attributes.getValue(NarManifestEntry.NAR_GROUP.getManifestName()); final String artifactId = attributes.getValue(NarManifestEntry.NAR_ID.getManifestName()); final String version = attributes.getValue(NarManifestEntry.NAR_VERSION.getManifestName()); final BundleCoordinate bundleCoordinate = new BundleCoordinate(groupId, artifactId, version); final String dependencyGroupId = attributes.getValue(NarManifestEntry.NAR_DEPENDENCY_GROUP.getManifestName()); final String dependencyArtifactId = attributes.getValue(NarManifestEntry.NAR_DEPENDENCY_ID.getManifestName()); final String dependencyVersion = attributes.getValue(NarManifestEntry.NAR_DEPENDENCY_VERSION.getManifestName()); final BundleCoordinate dependencyCoordinate; if (dependencyArtifactId != null) { dependencyCoordinate = new BundleCoordinate(dependencyGroupId, dependencyArtifactId, dependencyVersion); } else { dependencyCoordinate = null; } // TODO figure out what to do with build info final String buildBranch = attributes.getValue(NarManifestEntry.BUILD_BRANCH.getManifestName()); final String buildTag = attributes.getValue(NarManifestEntry.BUILD_TAG.getManifestName()); final String buildRevision = attributes.getValue(NarManifestEntry.BUILD_REVISION.getManifestName()); final String buildTimestamp = attributes.getValue(NarManifestEntry.BUILD_TIMESTAMP.getManifestName()); final String buildJdk = attributes.getValue(NarManifestEntry.BUILD_JDK.getManifestName()); final String builtBy = attributes.getValue(NarManifestEntry.BUILT_BY.getManifestName()); final BundleDetails.Builder builder = new BundleDetails.Builder() .coordinate(bundleCoordinate) .dependencyCoordinate(dependencyCoordinate); return builder.build(); } }
@Override public BundleDetails extract(final InputStream inputStream) throws IOException { try (final JarInputStream jarInputStream = new JarInputStream(inputStream)) { final Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { throw new IllegalArgumentException("NAR bundles must contain a valid MANIFEST"); } final Attributes attributes = manifest.getMainAttributes(); final String groupId = attributes.getValue(NarManifestEntry.NAR_GROUP.getManifestName()); final String artifactId = attributes.getValue(NarManifestEntry.NAR_ID.getManifestName()); final String version = attributes.getValue(NarManifestEntry.NAR_VERSION.getManifestName()); final BundleCoordinate bundleCoordinate = new BundleCoordinate(groupId, artifactId, version); final String dependencyGroupId = attributes.getValue(NarManifestEntry.NAR_DEPENDENCY_GROUP.getManifestName()); final String dependencyArtifactId = attributes.getValue(NarManifestEntry.NAR_DEPENDENCY_ID.getManifestName()); final String dependencyVersion = attributes.getValue(NarManifestEntry.NAR_DEPENDENCY_VERSION.getManifestName()); final BundleCoordinate dependencyCoordinate; if (dependencyArtifactId != null) { dependencyCoordinate = new BundleCoordinate(dependencyGroupId, dependencyArtifactId, dependencyVersion); } else { dependencyCoordinate = null; } final String buildBranch = attributes.getValue(NarManifestEntry.BUILD_BRANCH.getManifestName()); final String buildTag = attributes.getValue(NarManifestEntry.BUILD_TAG.getManifestName()); final String buildRevision = attributes.getValue(NarManifestEntry.BUILD_REVISION.getManifestName()); final String buildTimestamp = attributes.getValue(NarManifestEntry.BUILD_TIMESTAMP.getManifestName()); final String buildJdk = attributes.getValue(NarManifestEntry.BUILD_JDK.getManifestName()); final String builtBy = attributes.getValue(NarManifestEntry.BUILT_BY.getManifestName()); final BundleDetails.Builder builder = new BundleDetails.Builder() .coordinate(bundleCoordinate) .dependencyCoordinate(dependencyCoordinate); return builder.build(); } }
@override public bundledetails extract(final inputstream inputstream) throws ioexception { try (final jarinputstream jarinputstream = new jarinputstream(inputstream)) { final manifest manifest = jarinputstream.getmanifest(); if (manifest == null) { throw new illegalargumentexception("nar bundles must contain a valid manifest"); } final attributes attributes = manifest.getmainattributes(); final string groupid = attributes.getvalue(narmanifestentry.nar_group.getmanifestname()); final string artifactid = attributes.getvalue(narmanifestentry.nar_id.getmanifestname()); final string version = attributes.getvalue(narmanifestentry.nar_version.getmanifestname()); final bundlecoordinate bundlecoordinate = new bundlecoordinate(groupid, artifactid, version); final string dependencygroupid = attributes.getvalue(narmanifestentry.nar_dependency_group.getmanifestname()); final string dependencyartifactid = attributes.getvalue(narmanifestentry.nar_dependency_id.getmanifestname()); final string dependencyversion = attributes.getvalue(narmanifestentry.nar_dependency_version.getmanifestname()); final bundlecoordinate dependencycoordinate; if (dependencyartifactid != null) { dependencycoordinate = new bundlecoordinate(dependencygroupid, dependencyartifactid, dependencyversion); } else { dependencycoordinate = null; } final string buildbranch = attributes.getvalue(narmanifestentry.build_branch.getmanifestname()); final string buildtag = attributes.getvalue(narmanifestentry.build_tag.getmanifestname()); final string buildrevision = attributes.getvalue(narmanifestentry.build_revision.getmanifestname()); final string buildtimestamp = attributes.getvalue(narmanifestentry.build_timestamp.getmanifestname()); final string buildjdk = attributes.getvalue(narmanifestentry.build_jdk.getmanifestname()); final string builtby = attributes.getvalue(narmanifestentry.built_by.getmanifestname()); final bundledetails.builder builder = new bundledetails.builder() .coordinate(bundlecoordinate) .dependencycoordinate(dependencycoordinate); return builder.build(); } }
joaocc/nifi-registry
[ 1, 0, 0, 0 ]
22,990
private void addEvent(Event e, int globalId, int localId) { EventData data = eventMap.getOrCreate(e); data.setId(globalId); data.setLocalId(localId); eventList.add(data); data.setWasExecuted(true); if (data.isMemoryEvent()) { // ===== Memory Events ===== BigInteger address = ((MemEvent) e).getAddress().getIntValue(e, model, context); data.setAccessedAddress(address); if (!addressReadsMap.containsKey(address)) { addressReadsMap.put(address, new HashSet<>()); addressWritesMap.put(address, new HashSet<>()); } if (data.isRead()) { data.setValue(new BigInteger(model.evaluate(((RegWriter)e).getResultRegisterExpr()).toString())); addressReadsMap.get(address).add(data); } else if (data.isWrite()) { data.setValue(((MemEvent)e).getMemValue().getIntValue(e, model, context)); addressWritesMap.get(address).add(data); writeReadsMap.put(data, new HashSet<>()); if (data.isInit()) { addressInitMap.put(address, data); } } else { throw new RuntimeException("Unexpected memory event"); } } else if (data.isFence()) { // ===== Fences ===== String name = ((Fence)data.getEvent()).getName(); fenceMap.computeIfAbsent(name, key -> new HashSet<>()).add(data); } else if (data.isJump()) { // ===== Jumps ===== // We override the meaning of execution here. A jump is executed IFF its condition was true. data.setWasExecuted(((CondJump)e).didJump(model, context)); } else { //TODO: Maybe add some other events (e.g. assertions) // But for now all non-visible events are simply registered without // having any data extracted } }
private void addEvent(Event e, int globalId, int localId) { EventData data = eventMap.getOrCreate(e); data.setId(globalId); data.setLocalId(localId); eventList.add(data); data.setWasExecuted(true); if (data.isMemoryEvent()) { BigInteger address = ((MemEvent) e).getAddress().getIntValue(e, model, context); data.setAccessedAddress(address); if (!addressReadsMap.containsKey(address)) { addressReadsMap.put(address, new HashSet<>()); addressWritesMap.put(address, new HashSet<>()); } if (data.isRead()) { data.setValue(new BigInteger(model.evaluate(((RegWriter)e).getResultRegisterExpr()).toString())); addressReadsMap.get(address).add(data); } else if (data.isWrite()) { data.setValue(((MemEvent)e).getMemValue().getIntValue(e, model, context)); addressWritesMap.get(address).add(data); writeReadsMap.put(data, new HashSet<>()); if (data.isInit()) { addressInitMap.put(address, data); } } else { throw new RuntimeException("Unexpected memory event"); } } else if (data.isFence()) { String name = ((Fence)data.getEvent()).getName(); fenceMap.computeIfAbsent(name, key -> new HashSet<>()).add(data); } else if (data.isJump()) { data.setWasExecuted(((CondJump)e).didJump(model, context)); } else { } }
private void addevent(event e, int globalid, int localid) { eventdata data = eventmap.getorcreate(e); data.setid(globalid); data.setlocalid(localid); eventlist.add(data); data.setwasexecuted(true); if (data.ismemoryevent()) { biginteger address = ((memevent) e).getaddress().getintvalue(e, model, context); data.setaccessedaddress(address); if (!addressreadsmap.containskey(address)) { addressreadsmap.put(address, new hashset<>()); addresswritesmap.put(address, new hashset<>()); } if (data.isread()) { data.setvalue(new biginteger(model.evaluate(((regwriter)e).getresultregisterexpr()).tostring())); addressreadsmap.get(address).add(data); } else if (data.iswrite()) { data.setvalue(((memevent)e).getmemvalue().getintvalue(e, model, context)); addresswritesmap.get(address).add(data); writereadsmap.put(data, new hashset<>()); if (data.isinit()) { addressinitmap.put(address, data); } } else { throw new runtimeexception("unexpected memory event"); } } else if (data.isfence()) { string name = ((fence)data.getevent()).getname(); fencemap.computeifabsent(name, key -> new hashset<>()).add(data); } else if (data.isjump()) { data.setwasexecuted(((condjump)e).didjump(model, context)); } else { } }
hernanponcedeleon/Dat3M
[ 0, 1, 0, 0 ]
23,254
@Override protected int writeParametersWireFormat ( byte[] dst, int dstIndex ) { int start = dstIndex; SMBUtil.writeInt2(mapInformationLevel(this.informationLevel), dst, dstIndex); dstIndex += 2; /* * windows98 has what appears to be another 4 0's followed by the share * name as a zero terminated ascii string "\TMP" + '\0' * * As is this works, but it deviates from the spec section 4.1.6.6 but * maybe I should put it in. Wonder what NT does? */ return dstIndex - start; }
@Override protected int writeParametersWireFormat ( byte[] dst, int dstIndex ) { int start = dstIndex; SMBUtil.writeInt2(mapInformationLevel(this.informationLevel), dst, dstIndex); dstIndex += 2; return dstIndex - start; }
@override protected int writeparameterswireformat ( byte[] dst, int dstindex ) { int start = dstindex; smbutil.writeint2(mapinformationlevel(this.informationlevel), dst, dstindex); dstindex += 2; return dstindex - start; }
goyourfly/NovaCustom
[ 1, 0, 0, 0 ]
15,149
private void configureComponents() { //Associate the data with the formLayout columns and load the data. try { //1 - Set properties of the form this.tabs.addClassName("fichier-tab"); this.tabs.setOrientation(Tabs.Orientation.HORIZONTAL); this.tabs.setFlexGrowForEnclosedTabs(1); //Tabs covering the full width of the tab bar this.tabs.addThemeVariants(TabsVariant.LUMO_SMALL); this.tabs.setWidthFull(); this.tabInfoGenerale.setLabel("Informations Générales"); this.tabDefinition.setLabel("Définitions"); this.tabAjustement.setLabel("Ajustement"); this.tabCompteurBaseMontant.setLabel("Stockage des Compteurs Base et Montant"); this.tabCompteurInterne.setLabel("Stockage des Compteurs Internes"); this.tabCompteurExterne.setLabel("Stockage des Compteurs Externes"); this.pages.setSizeFull(); //sets the form size to fill the screen. this.tabInfoGeneraleFormLayout.addClassName("fichier-form"); this.tabInfoGeneraleFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabInfoGeneraleFormLayout.setVisible(true); //At startup, set the first page visible, while the remaining are not this.tabDefinitionFormLayout.addClassName("fichier-form"); this.tabDefinitionFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabDefinitionFormLayout.setVisible(true); //At startup, set the first page visible, while the remaining are not this.tabAjustementFormLayout.addClassName("fichier-form"); this.tabAjustementFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabAjustementFormLayout.setVisible(true); //At startup, set the first page visible, while the remaining are not this.tabCompteurBaseMontantFormLayout.addClassName("fichier-form"); this.tabCompteurBaseMontantFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabCompteurBaseMontantFormLayout.setVisible(false); //At startup, set the first page visible, while the remaining are not this.tabCompteurInterneFormLayout.addClassName("fichier-form"); this.tabCompteurInterneFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabCompteurInterneFormLayout.setVisible(false); //At startup, set the first page visible, while the remaining are not this.tabCompteurExterneFormLayout.addClassName("fichier-form"); this.tabCompteurExterneFormLayout.setSizeFull(); //sets the form size to fill the screen. this.tabCompteurExterneFormLayout.setVisible(false); //At startup, set the first page visible, while the remaining are not //2 - Define the Fields instances to use - We don't use .setLabel since we will use addFormItem instead of add to add items to the form - addFormItem allows us to set SuperTextField with on a FormaLayout when add doesn't //Contrôles de tabInfoGenerale this.txtNoRubrique.setWidth(100, Unit.PIXELS); this.txtNoRubrique.setRequired(true); this.txtNoRubrique.setRequiredIndicatorVisible(true); this.txtNoRubrique.addClassName(TEXTFIELD_LEFT_LABEL); this.txtLibelleRubrique.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtLibelleRubrique.addClassName(TEXTFIELD_LEFT_LABEL); this.txtLibelleCourtRubrique.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.txtLibelleCourtRubrique.addClassName(TEXTFIELD_LEFT_LABEL); this.chkInactif.setAutofocus(false); //Sepecific for isInactif this.chkEditionFacture.setAutofocus(true); this.chkEditionSynthetique.setAutofocus(true); //Contrôles de tabDefinition this.cboCodeModeValorisationRubrique.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeValorisationRubrique.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from ModeValorisationRubrique is the presentation value this.cboCodeModeValorisationRubrique.setItemLabelGenerator(SystemeModeValorisationCommission::getLibelleModeValorisation); this.cboCodeModeValorisationRubrique.setRequired(true); this.cboCodeModeValorisationRubrique.setRequiredIndicatorVisible(true); //???this.cboCodeModeValorisationRubrique.setLabel("ModeValorisationRubrique"); //???this.cboCodeModeValorisationRubrique.setId("this.cboCodeModeValorisationRubrique.getValue()"); this.cboCodeModeValorisationRubrique.setClearButtonVisible(true); //Add Filtering this.cboCodeModeValorisationRubrique.setAllowCustomValue(false); this.cboCodeModeValorisationRubrique.setPreventInvalidInput(true); this.cboCodeModeValorisationRubrique.addValueChangeListener(event -> { this.myControlsManageAccordingToModeValorisation(); }); this.txtMontantFixe.setWidth(100, Unit.PIXELS); this.txtMontantFixe.setRequiredIndicatorVisible(true); //Tmp - this.txtMontantFixe.addClassName(TEXTFIELD_LEFT_LABEL); this.txtMontantFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtMontantFixe.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtMontantFixe.withNullValueAllowed(false); this.cboCodeModeValorisationBase.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeValorisationBase.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from ModeValorisationBase is the presentation value this.cboCodeModeValorisationBase.setItemLabelGenerator(SystemeModeValorisationBaseCommission::getLibelleModeValorisation); this.cboCodeModeValorisationBase.setRequired(true); this.cboCodeModeValorisationBase.setRequiredIndicatorVisible(true); //???this.cboCodeModeValorisationBase.setLabel("ModeValorisationBase"); //???this.cboCodeModeValorisationBase.setId("this.cboCodeModeValorisationBase.getValue()"); this.cboCodeModeValorisationBase.setClearButtonVisible(true); //Add Filtering this.cboCodeModeValorisationBase.setAllowCustomValue(false); this.cboCodeModeValorisationBase.setPreventInvalidInput(true); this.cboCodeModeValorisationBase.addValueChangeListener(event -> { this.myControlsManageAccordingToModeValorisation(); }); this.txtBaseFixe.setWidth(100, Unit.PIXELS); this.txtBaseFixe.setRequiredIndicatorVisible(true); //Tmp - this.txtBaseFixe.addClassName(TEXTFIELD_LEFT_LABEL); this.txtBaseFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtBaseFixe.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtBaseFixe.withNullValueAllowed(false); this.cboCodeModeValorisationTaux.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeValorisationTaux.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from ModeValorisationTaux is the presentation value this.cboCodeModeValorisationTaux.setItemLabelGenerator(SystemeModeValorisationTauxCommission::getLibelleModeValorisation); this.cboCodeModeValorisationTaux.setRequired(true); this.cboCodeModeValorisationTaux.setRequiredIndicatorVisible(true); //???this.cboCodeModeValorisationTaux.setLabel("ModeValorisationTaux"); //???this.cboCodeModeValorisationTaux.setId("this.cboCodeModeValorisationTaux.getValue()"); this.cboCodeModeValorisationTaux.setClearButtonVisible(true); //Add Filtering this.cboCodeModeValorisationTaux.setAllowCustomValue(false); this.cboCodeModeValorisationTaux.setPreventInvalidInput(true); this.cboCodeModeValorisationTaux.addValueChangeListener(event -> { this.myControlsManageAccordingToModeValorisation(); }); this.txtTauxFixe.setWidth(100, Unit.PIXELS); this.txtTauxFixe.setRequiredIndicatorVisible(true); //Tmp - this.txtTauxFixe.addClassName(TEXTFIELD_LEFT_LABEL); this.txtTauxFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtTauxFixe.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtTauxFixe.withNullValueAllowed(false); this.txtCoefficientMultiplicateur.setWidth(100, Unit.PIXELS); this.txtCoefficientMultiplicateur.setRequiredIndicatorVisible(true); //Tmp - this.txtCoefficientMultiplicateur.addClassName(TEXTFIELD_LEFT_LABEL); this.txtCoefficientMultiplicateur.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtCoefficientMultiplicateur.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtCoefficientMultiplicateur.withNullValueAllowed(false); this.cboCodeTranche.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeTranche.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from TrancheValeur is the presentation value this.cboCodeTranche.setItemLabelGenerator(TrancheValeur::getLibelleTranche); this.cboCodeTranche.setRequired(true); this.cboCodeTranche.setRequiredIndicatorVisible(true); //???this.cboCodeTranche.setLabel("TrancheValeur"); //???this.cboCodeTranche.setId("person"); this.cboCodeTranche.setClearButtonVisible(true); //Add Filtering this.cboCodeTranche.setAllowCustomValue(true); this.cboCodeTranche.setPreventInvalidInput(true); this.cboCodeTranche.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeTranche (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Tranche de Valeur choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeTranche.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeTranche.addCustomValueSetListener(event -> { this.cboCodeTranche_NotInList(event.getDetail(), 50); }); this.cboCodeVariableRubrique.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeVariableRubrique.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from VariableService is the presentation value this.cboCodeVariableRubrique.setItemLabelGenerator(VariableService::getLibelleVariable); this.cboCodeVariableRubrique.setRequired(true); this.cboCodeVariableRubrique.setRequiredIndicatorVisible(true); //???this.cboCodeVariableRubrique.setLabel("VariableService"); //???this.cboCodeVariableRubrique.setId("person"); this.cboCodeVariableRubrique.setClearButtonVisible(true); //Add Filtering this.cboCodeVariableRubrique.setAllowCustomValue(true); this.cboCodeVariableRubrique.setPreventInvalidInput(true); this.cboCodeVariableRubrique.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeVariableRubrique (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Variable choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeVariableRubrique.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeVariableRubrique.addCustomValueSetListener(event -> { this.cboCodeVariableRubrique_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteRubrique.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeConstanteRubrique.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from EmploiFonds is the presentation value this.cboCodeConstanteRubrique.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteRubrique.setRequired(true); this.cboCodeConstanteRubrique.setRequiredIndicatorVisible(true); //???this.cboCodeConstanteRubrique.setLabel("EmploiFonds"); //???this.cboCodeConstanteRubrique.setId("person"); this.cboCodeConstanteRubrique.setClearButtonVisible(true); //Add Filtering this.cboCodeConstanteRubrique.setAllowCustomValue(true); this.cboCodeConstanteRubrique.setPreventInvalidInput(true); this.cboCodeConstanteRubrique.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeConstanteRubrique (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeConstanteRubrique.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeConstanteRubrique.addCustomValueSetListener(event -> { this.cboCodeConstanteRubrique_NotInList(event.getDetail(), 50); }); this.cboCodeVariableBase.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeVariableBase.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from VariableService is the presentation value this.cboCodeVariableBase.setItemLabelGenerator(VariableService::getLibelleVariable); this.cboCodeVariableBase.setRequired(true); this.cboCodeVariableBase.setRequiredIndicatorVisible(true); //???this.cboCodeVariableBase.setLabel("VariableService"); //???this.cboCodeVariableBase.setId("person"); this.cboCodeVariableBase.setClearButtonVisible(true); //Add Filtering this.cboCodeVariableBase.setAllowCustomValue(true); this.cboCodeVariableBase.setPreventInvalidInput(true); this.cboCodeVariableBase.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeVariableBase (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Variable choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeVariableBase.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeVariableBase.addCustomValueSetListener(event -> { this.cboCodeVariableBase_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteBase.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeConstanteBase.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from EmploiFonds is the presentation value this.cboCodeConstanteBase.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteBase.setRequired(true); this.cboCodeConstanteBase.setRequiredIndicatorVisible(true); //???this.cboCodeConstanteBase.setLabel("EmploiFonds"); //???this.cboCodeConstanteBase.setId("person"); this.cboCodeConstanteBase.setClearButtonVisible(true); //Add Filtering this.cboCodeConstanteBase.setAllowCustomValue(true); this.cboCodeConstanteBase.setPreventInvalidInput(true); this.cboCodeConstanteBase.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeConstanteBase (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeConstanteBase.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeConstanteBase.addCustomValueSetListener(event -> { this.cboCodeConstanteBase_NotInList(event.getDetail(), 50); }); this.cboCodeVariableTaux.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeVariableTaux.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from VariableService is the presentation value this.cboCodeVariableTaux.setItemLabelGenerator(VariableService::getLibelleVariable); this.cboCodeVariableTaux.setRequired(true); this.cboCodeVariableTaux.setRequiredIndicatorVisible(true); //???this.cboCodeVariableTaux.setLabel("VariableService"); //???this.cboCodeVariableTaux.setId("person"); this.cboCodeVariableTaux.setClearButtonVisible(true); //Add Filtering this.cboCodeVariableTaux.setAllowCustomValue(true); this.cboCodeVariableTaux.setPreventInvalidInput(true); this.cboCodeVariableTaux.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeVariableTaux (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Variable choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeVariableTaux.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeVariableTaux.addCustomValueSetListener(event -> { this.cboCodeVariableTaux_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteTaux.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeConstanteTaux.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from EmploiFonds is the presentation value this.cboCodeConstanteTaux.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteTaux.setRequired(true); this.cboCodeConstanteTaux.setRequiredIndicatorVisible(true); //???this.cboCodeConstanteTaux.setLabel("EmploiFonds"); //???this.cboCodeConstanteTaux.setId("person"); this.cboCodeConstanteTaux.setClearButtonVisible(true); //Add Filtering this.cboCodeConstanteTaux.setAllowCustomValue(true); this.cboCodeConstanteTaux.setPreventInvalidInput(true); this.cboCodeConstanteTaux.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeConstanteTaux (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeConstanteTaux.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeConstanteTaux.addCustomValueSetListener(event -> { this.cboCodeConstanteTaux_NotInList(event.getDetail(), 50); }); //Contrôles de tabAjustement this.cboCodeValeurMinimum.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeValeurMinimum.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeValeurMinMax is the presentation value this.cboCodeValeurMinimum.setItemLabelGenerator(SystemeValeurMinMax::getLibelleValeur); this.cboCodeValeurMinimum.setRequired(true); this.cboCodeValeurMinimum.setRequiredIndicatorVisible(true); //???this.cboCodeValeurMinimum.setLabel("SystemeValeurMinMax"); //???this.cboCodeValeurMinimum.setId("person"); this.cboCodeValeurMinimum.setClearButtonVisible(true); //Add Filtering this.cboCodeValeurMinimum.setAllowCustomValue(false); this.cboCodeValeurMinimum.setPreventInvalidInput(true); this.txtValeurMinimumFixe.setWidth(100, Unit.PIXELS); this.txtValeurMinimumFixe.setRequiredIndicatorVisible(true); //Tmp - this.txtValeurMinimumFixe.addClassName(TEXTFIELD_LEFT_LABEL); this.txtValeurMinimumFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtValeurMinimumFixe.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtValeurMinimumFixe.withNullValueAllowed(false); this.cboCodeValeurMaximum.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeValeurMaximum.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeValeurMinMax is the presentation value this.cboCodeValeurMaximum.setItemLabelGenerator(SystemeValeurMinMax::getLibelleValeur); this.cboCodeValeurMaximum.setRequired(true); this.cboCodeValeurMaximum.setRequiredIndicatorVisible(true); //???this.cboCodeValeurMaximum.setLabel("SystemeValeurMinMax"); //???this.cboCodeValeurMaximum.setId("person"); this.cboCodeValeurMaximum.setClearButtonVisible(true); //Add Filtering this.cboCodeValeurMaximum.setAllowCustomValue(false); this.cboCodeValeurMaximum.setPreventInvalidInput(true); this.txtValeurMaximumFixe.setWidth(100, Unit.PIXELS); this.txtValeurMaximumFixe.setRequiredIndicatorVisible(true); //Tmp - this.txtValeurMaximumFixe.addClassName(TEXTFIELD_LEFT_LABEL); this.txtValeurMaximumFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtValeurMaximumFixe.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtValeurMaximumFixe.withNullValueAllowed(false); this.cboCodeConstanteValeurMinimum.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeConstanteValeurMinimum.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from EmploiFonds is the presentation value this.cboCodeConstanteValeurMinimum.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteValeurMinimum.setRequired(true); this.cboCodeConstanteValeurMinimum.setRequiredIndicatorVisible(true); //???this.cboCodeConstanteValeurMinimum.setLabel("EmploiFonds"); //???this.cboCodeConstanteValeurMinimum.setId("person"); this.cboCodeConstanteValeurMinimum.setClearButtonVisible(true); //Add Filtering this.cboCodeConstanteValeurMinimum.setAllowCustomValue(true); this.cboCodeConstanteValeurMinimum.setPreventInvalidInput(true); this.cboCodeConstanteValeurMinimum.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeConstanteValeurMinimum (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeConstanteValeurMinimum.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeConstanteValeurMinimum.addCustomValueSetListener(event -> { this.cboCodeConstanteValeurMinimum_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteValeurMaximum.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeConstanteValeurMaximum.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from EmploiFonds is the presentation value this.cboCodeConstanteValeurMaximum.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteValeurMaximum.setRequired(true); this.cboCodeConstanteValeurMaximum.setRequiredIndicatorVisible(true); //???this.cboCodeConstanteValeurMaximum.setLabel("EmploiFonds"); //???this.cboCodeConstanteValeurMaximum.setId("person"); this.cboCodeConstanteValeurMaximum.setClearButtonVisible(true); //Add Filtering this.cboCodeConstanteValeurMaximum.setAllowCustomValue(true); this.cboCodeConstanteValeurMaximum.setPreventInvalidInput(true); this.cboCodeConstanteValeurMaximum.addValueChangeListener(event -> { if (event.getValue() != null) { //BeforeUpdate CodeConstanteValeurMaximum (CIF): Contrôle de Inactif if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); //Cancel this.cboCodeConstanteValeurMaximum.setValue(event.getOldValue()); } //if (event.getValue() != null) { } }); /** * Allow users to enter a value which doesn't exist in the data set, and * set it as the value of the ComboBox. */ this.cboCodeConstanteValeurMaximum.addCustomValueSetListener(event -> { this.cboCodeConstanteValeurMaximum_NotInList(event.getDetail(), 50); }); this.cboCodeModeAbattement.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeAbattement.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeAbattement is the presentation value this.cboCodeModeAbattement.setItemLabelGenerator(SystemeModeAbattement::getLibelleModeAbattement); this.cboCodeModeAbattement.setRequired(true); this.cboCodeModeAbattement.setRequiredIndicatorVisible(true); //???this.cboCodeModeAbattement.setLabel("SystemeModeAbattement"); //???this.cboCodeModeAbattement.setId("person"); this.cboCodeModeAbattement.setClearButtonVisible(true); //Add Filtering this.cboCodeModeAbattement.setAllowCustomValue(false); this.cboCodeModeAbattement.setPreventInvalidInput(true); this.txtAbattementFixe.setWidth(100, Unit.PIXELS); this.txtAbattementFixe.setRequiredIndicatorVisible(true); //Tmp - this.txtAbattementFixe.addClassName(TEXTFIELD_LEFT_LABEL); this.txtAbattementFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtAbattementFixe.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtAbattementFixe.withNullValueAllowed(false); this.cboCodeModeArrondissement.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeArrondissement.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeArrondissement is the presentation value this.cboCodeModeArrondissement.setItemLabelGenerator(SystemeModeArrondissement::getLibelleModeArrondissement); this.cboCodeModeArrondissement.setRequired(true); this.cboCodeModeArrondissement.setRequiredIndicatorVisible(true); //???this.cboCodeModeArrondissement.setLabel("SystemeModeArrondissement"); //???this.cboCodeModeArrondissement.setId("person"); this.cboCodeModeArrondissement.setClearButtonVisible(true); //Add Filtering this.cboCodeModeArrondissement.setAllowCustomValue(false); this.cboCodeModeArrondissement.setPreventInvalidInput(true); this.txtNombreChiffreArrondissement.setWidth(100, Unit.PIXELS); this.txtNombreChiffreArrondissement.setRequiredIndicatorVisible(true); //Tmp - this.txtNombreChiffreArrondissement.addClassName(TEXTFIELD_LEFT_LABEL); this.txtNombreChiffreArrondissement.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); //Align Center for numeric value this.txtNombreChiffreArrondissement.setLocale(Locale.FRENCH); //Configuration options for HasLocale this.txtNombreChiffreArrondissement.withNullValueAllowed(false); //Contrôles de tabCompteurBaseMontant this.cboCodeModeStockageCompteurBase01.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurBase01.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurBase01.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase01.setRequired(true); this.cboCodeModeStockageCompteurBase01.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurBase01.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurBase01.setId("person"); this.cboCodeModeStockageCompteurBase01.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurBase01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurBase02.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurBase02.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurBase02.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase02.setRequired(true); this.cboCodeModeStockageCompteurBase02.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurBase02.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurBase02.setId("person"); this.cboCodeModeStockageCompteurBase02.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurBase02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurBase03.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurBase03.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurBase03.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase03.setRequired(true); this.cboCodeModeStockageCompteurBase03.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurBase03.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurBase03.setId("person"); this.cboCodeModeStockageCompteurBase03.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurBase03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurBase04.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurBase04.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurBase04.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase04.setRequired(true); this.cboCodeModeStockageCompteurBase04.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurBase04.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurBase04.setId("person"); this.cboCodeModeStockageCompteurBase04.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurBase04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant01.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant01.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurMontant01.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant01.setRequired(true); this.cboCodeModeStockageCompteurMontant01.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurMontant01.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurMontant01.setId("person"); this.cboCodeModeStockageCompteurMontant01.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurMontant01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant02.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant02.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurMontant02.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant02.setRequired(true); this.cboCodeModeStockageCompteurMontant02.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurMontant02.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurMontant02.setId("person"); this.cboCodeModeStockageCompteurMontant02.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurMontant02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant03.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant03.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurMontant03.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant03.setRequired(true); this.cboCodeModeStockageCompteurMontant03.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurMontant03.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurMontant03.setId("person"); this.cboCodeModeStockageCompteurMontant03.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurMontant03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant04.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant04.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageBaseMontant is the presentation value this.cboCodeModeStockageCompteurMontant04.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant04.setRequired(true); this.cboCodeModeStockageCompteurMontant04.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurMontant04.setLabel("SystemeModeStockageBaseMontant"); //???this.cboCodeModeStockageCompteurMontant04.setId("person"); this.cboCodeModeStockageCompteurMontant04.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurMontant04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant04.setPreventInvalidInput(true); //Contrôles de tabCompteurInterne this.cboCodeModeStockageCompteurInterne01.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne01.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne01.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne01.setRequired(true); this.cboCodeModeStockageCompteurInterne01.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne01.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne01.setId("person"); this.cboCodeModeStockageCompteurInterne01.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne02.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne02.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne02.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne02.setRequired(true); this.cboCodeModeStockageCompteurInterne02.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne02.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne02.setId("person"); this.cboCodeModeStockageCompteurInterne02.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne03.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne03.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne03.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne03.setRequired(true); this.cboCodeModeStockageCompteurInterne03.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne03.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne03.setId("person"); this.cboCodeModeStockageCompteurInterne03.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne04.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne04.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne04.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne04.setRequired(true); this.cboCodeModeStockageCompteurInterne04.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne04.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne04.setId("person"); this.cboCodeModeStockageCompteurInterne04.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne05.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne05.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne05.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne05.setRequired(true); this.cboCodeModeStockageCompteurInterne05.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne05.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne05.setId("person"); this.cboCodeModeStockageCompteurInterne05.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne05.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne05.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne06.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne06.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne06.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne06.setRequired(true); this.cboCodeModeStockageCompteurInterne06.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne06.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne06.setId("person"); this.cboCodeModeStockageCompteurInterne06.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne06.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne06.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne07.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne07.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne07.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne07.setRequired(true); this.cboCodeModeStockageCompteurInterne07.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne07.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne07.setId("person"); this.cboCodeModeStockageCompteurInterne07.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne07.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne07.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne08.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne08.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne08.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne08.setRequired(true); this.cboCodeModeStockageCompteurInterne08.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne08.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne08.setId("person"); this.cboCodeModeStockageCompteurInterne08.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne08.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne08.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne09.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne09.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne09.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne09.setRequired(true); this.cboCodeModeStockageCompteurInterne09.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne09.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne09.setId("person"); this.cboCodeModeStockageCompteurInterne09.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne09.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne09.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne10.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne10.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurInterne10.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne10.setRequired(true); this.cboCodeModeStockageCompteurInterne10.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurInterne10.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurInterne10.setId("person"); this.cboCodeModeStockageCompteurInterne10.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurInterne10.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne10.setPreventInvalidInput(true); //Contrôles de tabCompteurExterne this.cboCodeModeStockageCompteurExterne01.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne01.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne01.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne01.setRequired(true); this.cboCodeModeStockageCompteurExterne01.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne01.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne01.setId("person"); this.cboCodeModeStockageCompteurExterne01.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne02.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne02.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne02.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne02.setRequired(true); this.cboCodeModeStockageCompteurExterne02.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne02.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne02.setId("person"); this.cboCodeModeStockageCompteurExterne02.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne03.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne03.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne03.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne03.setRequired(true); this.cboCodeModeStockageCompteurExterne03.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne03.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne03.setId("person"); this.cboCodeModeStockageCompteurExterne03.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne04.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne04.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne04.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne04.setRequired(true); this.cboCodeModeStockageCompteurExterne04.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne04.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne04.setId("person"); this.cboCodeModeStockageCompteurExterne04.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne05.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne05.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne05.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne05.setRequired(true); this.cboCodeModeStockageCompteurExterne05.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne05.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne05.setId("person"); this.cboCodeModeStockageCompteurExterne05.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne05.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne05.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne06.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne06.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne06.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne06.setRequired(true); this.cboCodeModeStockageCompteurExterne06.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne06.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne06.setId("person"); this.cboCodeModeStockageCompteurExterne06.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne06.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne06.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne07.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne07.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne07.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne07.setRequired(true); this.cboCodeModeStockageCompteurExterne07.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne07.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne07.setId("person"); this.cboCodeModeStockageCompteurExterne07.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne07.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne07.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne08.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne08.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne08.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne08.setRequired(true); this.cboCodeModeStockageCompteurExterne08.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne08.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne08.setId("person"); this.cboCodeModeStockageCompteurExterne08.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne08.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne08.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne09.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne09.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne09.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne09.setRequired(true); this.cboCodeModeStockageCompteurExterne09.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne09.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne09.setId("person"); this.cboCodeModeStockageCompteurExterne09.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne09.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne09.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne10.setWidth(350, Unit.PIXELS); //setWidth(400, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne10.addClassName(COMBOBOX_LEFT_LABEL); // Choose which property from SystemeModeStockageInterneExterne is the presentation value this.cboCodeModeStockageCompteurExterne10.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne10.setRequired(true); this.cboCodeModeStockageCompteurExterne10.setRequiredIndicatorVisible(true); //???this.cboCodeModeStockageCompteurExterne10.setLabel("SystemeModeStockageInterneExterne"); //???this.cboCodeModeStockageCompteurExterne10.setId("person"); this.cboCodeModeStockageCompteurExterne10.setClearButtonVisible(true); //Add Filtering this.cboCodeModeStockageCompteurExterne10.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne10.setPreventInvalidInput(true); //3 - Bind Fields instances to use (Manual Data Binding) // Easily bind forms to beans and manage validation and buffering //To bind a component to read-only data, use a null value for the setter. Label lblNoRubriqueValidationStatus = new Label(); this.binder.forField(this.txtNoRubrique) .asRequired("La Saisie du N° Rubrique est Obligatoire. Veuillez saisir le N° Rubrique.") .withValidator(text -> text != null && text.length() <= 10, "N° Rubrique ne peut contenir au plus 10 caractères") .withValidationStatusHandler(status -> {lblNoRubriqueValidationStatus.setText(status.getMessage().orElse("")); lblNoRubriqueValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getNoRubrique, Rubrique::setNoRubrique); Label lblLibelleRubriqueValidationStatus = new Label(); this.binder.forField(this.txtLibelleRubrique) .asRequired("La Saisie du Libellé de la Rubrique est Obligatoire. Veuillez saisir le Libellé de la Rubrique.") .withValidator(text -> text.length() <= 50, "Libellé Rubrique ne peut contenir au plus 50 caractères.") .withValidationStatusHandler(status -> {lblLibelleRubriqueValidationStatus.setText(status.getMessage().orElse("")); lblLibelleRubriqueValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getLibelleRubrique, Rubrique::setLibelleRubrique); Label lblLibelleCourtRubriqueValidationStatus = new Label(); this.binder.forField(this.txtLibelleCourtRubrique) .asRequired("La Saisie du Libellé Abrégé de la Rubrique est Obligatoire. Veuillez saisir le Libellé de la Rubrique.") .withValidator(text -> text.length() <= 30, "Libellé Abrégé Rubrique ne peut contenir au plus 30 caractères.") .withValidationStatusHandler(status -> {lblLibelleCourtRubriqueValidationStatus.setText(status.getMessage().orElse("")); lblLibelleCourtRubriqueValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getLibelleCourtRubrique, Rubrique::setLibelleCourtRubrique); this.binder.forField(this.chkInactif) .bind(Rubrique::isInactif, Rubrique::setInactif); this.binder.forField(this.chkEditionFacture) .bind(Rubrique::isEditionFacture, Rubrique::setEditionFacture); this.binder.forField(this.chkEditionSynthetique) .bind(Rubrique::isEditionSynthetique, Rubrique::setEditionSynthetique); Label lblModeValorisationRubriqueValidationStatus = new Label(); this.binder.forField(this.cboCodeModeValorisationRubrique) .asRequired("La Saisie du Mode de Valorisation de la Rubrique est requise. Veuillez sélectionner un Mode de Valorisation de la Rubrique") .bind(Rubrique::getModeValorisationRubrique, Rubrique::setModeValorisationRubrique); Label lblMontantFixeValidationStatus = new Label(); this.binder.forField(this.txtMontantFixe) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie du Montant Fixe est Obligatoire. Veuillez saisir le Montant Fixe.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblMontantFixeValidationStatus.setText(status.getMessage().orElse("")); lblMontantFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getMontantFixe, Rubrique::setMontantFixe); Label lblModeValorisationBaseValidationStatus = new Label(); this.binder.forField(this.cboCodeModeValorisationBase) //.asRequired("La Saisie du Mode de Détermination de la Base est requise. Veuillez sélectionner un Mode de Détermination de la Base") .bind(Rubrique::getModeValorisationBase, Rubrique::setModeValorisationBase); Label lblBaseFixeValidationStatus = new Label(); this.binder.forField(this.txtBaseFixe) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie de la Base Fixe est Obligatoire. Veuillez saisir la Base.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblBaseFixeValidationStatus.setText(status.getMessage().orElse("")); lblBaseFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getBaseFixe, Rubrique::setBaseFixe); Label lblModeValorisationTauxValidationStatus = new Label(); this.binder.forField(this.cboCodeModeValorisationTaux) //.asRequired("La Saisie du Mode de Détermination du Taux est requise. Veuillez sélectionner un Mode de Détermination du Taux") .bind(Rubrique::getModeValorisationTaux, Rubrique::setModeValorisationTaux); Label lblTauxFixeValidationStatus = new Label(); this.binder.forField(this.txtTauxFixe) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie du Taux Fixe est Obligatoire. Veuillez saisir le Taux.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblTauxFixeValidationStatus.setText(status.getMessage().orElse("")); lblTauxFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getTauxFixe, Rubrique::setTauxFixe); Label lblCoefficientMultiplicateurValidationStatus = new Label(); this.binder.forField(this.txtCoefficientMultiplicateur) .asRequired("La Saisie du Coefficient Multiplicateur est Obligatoire. Veuillez saisir le Coefficient Multiplicateur.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblCoefficientMultiplicateurValidationStatus.setText(status.getMessage().orElse("")); lblCoefficientMultiplicateurValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getCoefficientMultiplicateur, Rubrique::setCoefficientMultiplicateur); Label lblTrancheValeurValidationStatus = new Label(); this.binder.forField(this.cboCodeTranche) //.asRequired("La Saisie de la Tranche est requise. Veuillez sélectionner une Tranche") .bind(Rubrique::getTranche, Rubrique::setTranche); Label lblVariableRubriqueValidationStatus = new Label(); this.binder.forField(this.cboCodeVariableRubrique) //.asRequired("La Saisie de la Variable Rubrique est requise. Veuillez sélectionner une Variable") .bind(Rubrique::getVariableRubrique, Rubrique::setVariableRubrique); Label lblConstanteRubriqueValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteRubrique) //.asRequired("La Saisie EmploiFonds Rubrique est requise. Veuillez sélectionner une EmploiFonds") .bind(Rubrique::getConstanteRubrique, Rubrique::setConstanteRubrique); Label lblVariableBaseValidationStatus = new Label(); this.binder.forField(this.cboCodeVariableBase) //.asRequired("La Saisie de la Variable Base est requise. Veuillez sélectionner une Variable") .bind(Rubrique::getVariableBase, Rubrique::setVariableBase); Label lblConstanteBaseValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteBase) //.asRequired("La Saisie EmploiFonds Base est requise. Veuillez sélectionner une EmploiFonds") .bind(Rubrique::getConstanteBase, Rubrique::setConstanteBase); Label lblVariableTauxValidationStatus = new Label(); this.binder.forField(this.cboCodeVariableTaux) //.asRequired("La Saisie de la Variable Taux est requise. Veuillez sélectionner une Variable") .bind(Rubrique::getVariableTaux, Rubrique::setVariableTaux); Label lblConstanteTauxValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteTaux) //.asRequired("La Saisie EmploiFonds Taux est requise. Veuillez sélectionner une EmploiFonds") .bind(Rubrique::getConstanteTaux, Rubrique::setConstanteTaux); Label lblValeurMinimumValidationStatus = new Label(); this.binder.forField(this.cboCodeValeurMinimum) //.asRequired("La Saisie de la Valeur Minimum est requise. Veuillez saisir la Valeur Minimum") .bind(Rubrique::getValeurMinimum, Rubrique::setValeurMinimum); Label lblValeurMinimumFixeValidationStatus = new Label(); this.binder.forField(this.txtValeurMinimumFixe) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie de la Valeur Minimum Fixe est Obligatoire. Veuillez saisir la Valeur Minimum Fixe.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblValeurMinimumFixeValidationStatus.setText(status.getMessage().orElse("")); lblValeurMinimumFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getValeurMinimumFixe, Rubrique::setValeurMinimumFixe); Label lblValeurMaximumValidationStatus = new Label(); this.binder.forField(this.cboCodeValeurMaximum) //.asRequired("La Saisie de la Valeur Maximum est requise. Veuillez saisir la Valeur Maximum") .bind(Rubrique::getValeurMaximum, Rubrique::setValeurMaximum); Label lblValeurMaximumFixeValidationStatus = new Label(); this.binder.forField(this.txtValeurMaximumFixe) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie de la Valeur Maximum Fixe est Obligatoire. Veuillez saisir la Valeur Maximum Fixe.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblValeurMaximumFixeValidationStatus.setText(status.getMessage().orElse("")); lblValeurMaximumFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getValeurMaximumFixe, Rubrique::setValeurMaximumFixe); Label lblConstanteValeurMinimumValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteValeurMinimum) //.asRequired("La Saisie de la EmploiFonds Valeur Minimum est requise. Veuillez saisir la EmploiFonds Valeur Minimum") .bind(Rubrique::getConstanteValeurMinimum, Rubrique::setConstanteValeurMinimum); Label lblConstanteValeurMaximumValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteValeurMaximum) //.asRequired("La Saisie de la EmploiFonds Valeur Maximum est requise. Veuillez saisir la EmploiFonds Valeur Maximum") .bind(Rubrique::getConstanteValeurMaximum, Rubrique::setConstanteValeurMaximum); Label lblModeAbattementValidationStatus = new Label(); this.binder.forField(this.cboCodeModeAbattement) //.asRequired("La Saisie du Mode Abattement est requise. Veuillez sélectionner un Mode Abattement") .bind(Rubrique::getModeAbattement, Rubrique::setModeAbattement); Label lblAbattementFixeValidationStatus = new Label(); this.binder.forField(this.txtAbattementFixe) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie de l'Abattement Fixe est Obligatoire. Veuillez saisir l'Abattement Fixe.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblAbattementFixeValidationStatus.setText(status.getMessage().orElse("")); lblAbattementFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getAbattementFixe, Rubrique::setAbattementFixe); Label lblModeArrondissementValidationStatus = new Label(); this.binder.forField(this.cboCodeModeArrondissement) //.asRequired("La Saisie du Mode Arrondissement est requise. Veuillez sélectionner un Mode Arrondissement") .bind(Rubrique::getModeArrondissement, Rubrique::setModeArrondissement); Label lblNombreChiffreArrondissementValidationStatus = new Label(); this.binder.forField(this.txtNombreChiffreArrondissement) //Généralement pas de asRequired pour les nombres afin de permettre la saisie de zéro - .asRequired("La Saisie du Nombre Chiffre Arrondissement est Obligatoire. Veuillez saisir le Nombre Chiffre Arrondissement.") //.withConverter(Integer::valueOf, String::valueOf, "Veuillez saisir un nombre") //.withValidator(new RegexpValidator("Seuls les chiffres 0-9 sont acceptés","\\d*")) .withValidationStatusHandler(status -> {lblNombreChiffreArrondissementValidationStatus.setText(status.getMessage().orElse("")); lblNombreChiffreArrondissementValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getNombreChiffreArrondissement, Rubrique::setNombreChiffreArrondissement); Label lblModeStockageCompteurBase01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase01) //.asRequired("La Saisie du Mode de Stockage Compteur de Base 01 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Base 01") .bind(Rubrique::getModeStockageCompteurBase01, Rubrique::setModeStockageCompteurBase01); Label lblModeStockageCompteurBase02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase02) //.asRequired("La Saisie du Mode de Stockage Compteur de Base 02 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Base 02") .bind(Rubrique::getModeStockageCompteurBase02, Rubrique::setModeStockageCompteurBase02); Label lblModeStockageCompteurBase03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase03) //.asRequired("La Saisie du Mode de Stockage Compteur de Base 03 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Base 03") .bind(Rubrique::getModeStockageCompteurBase03, Rubrique::setModeStockageCompteurBase03); Label lblModeStockageCompteurBase04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase04) //.asRequired("La Saisie du Mode de Stockage Compteur de Base 04 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Base 04") .bind(Rubrique::getModeStockageCompteurBase04, Rubrique::setModeStockageCompteurBase04); Label lblModeStockageCompteurMontant01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant01) //.asRequired("La Saisie du Mode de Stockage Compteur de Montant 01 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Montant 01") .bind(Rubrique::getModeStockageCompteurMontant01, Rubrique::setModeStockageCompteurMontant01); Label lblModeStockageCompteurMontant02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant02) //.asRequired("La Saisie du Mode de Stockage Compteur de Montant 02 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Montant 02") .bind(Rubrique::getModeStockageCompteurMontant02, Rubrique::setModeStockageCompteurMontant02); Label lblModeStockageCompteurMontant03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant03) //.asRequired("La Saisie du Mode de Stockage Compteur de Montant 03 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Montant 03") .bind(Rubrique::getModeStockageCompteurMontant03, Rubrique::setModeStockageCompteurMontant03); Label lblModeStockageCompteurMontant04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant04) //.asRequired("La Saisie du Mode de Stockage Compteur de Montant 04 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Montant 04") .bind(Rubrique::getModeStockageCompteurMontant04, Rubrique::setModeStockageCompteurMontant04); Label lblModeStockageCompteurInterne01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne01) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 01 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne01, Rubrique::setModeStockageCompteurInterne01); Label lblModeStockageCompteurInterne02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne02) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 02 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne02, Rubrique::setModeStockageCompteurInterne02); Label lblModeStockageCompteurInterne03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne03) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 03 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne03, Rubrique::setModeStockageCompteurInterne03); Label lblModeStockageCompteurInterne04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne04) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 04 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne04, Rubrique::setModeStockageCompteurInterne04); Label lblModeStockageCompteurInterne05ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne05) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 05 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne05, Rubrique::setModeStockageCompteurInterne05); Label lblModeStockageCompteurInterne06ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne06) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 06 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne06, Rubrique::setModeStockageCompteurInterne06); Label lblModeStockageCompteurInterne07ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne07) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 07 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne07, Rubrique::setModeStockageCompteurInterne07); Label lblModeStockageCompteurInterne08ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne08) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 08 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne08, Rubrique::setModeStockageCompteurInterne08); Label lblModeStockageCompteurInterne09ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne09) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 09 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne09, Rubrique::setModeStockageCompteurInterne09); Label lblModeStockageCompteurInterne10ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne10) //.asRequired("La Saisie du Mode de Stockage Compteur de Interne 10 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Interne") .bind(Rubrique::getModeStockageCompteurInterne10, Rubrique::setModeStockageCompteurInterne10); Label lblModeStockageCompteurExterne01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne01) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 01 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne01, Rubrique::setModeStockageCompteurExterne01); Label lblModeStockageCompteurExterne02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne02) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 02 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne02, Rubrique::setModeStockageCompteurExterne02); Label lblModeStockageCompteurExterne03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne03) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 03 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne03, Rubrique::setModeStockageCompteurExterne03); Label lblModeStockageCompteurExterne04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne04) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 04 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne04, Rubrique::setModeStockageCompteurExterne04); Label lblModeStockageCompteurExterne05ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne05) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 05 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne05, Rubrique::setModeStockageCompteurExterne05); Label lblModeStockageCompteurExterne06ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne06) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 06 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne06, Rubrique::setModeStockageCompteurExterne06); Label lblModeStockageCompteurExterne07ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne07) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 07 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne07, Rubrique::setModeStockageCompteurExterne07); Label lblModeStockageCompteurExterne08ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne08) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 08 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne08, Rubrique::setModeStockageCompteurExterne08); Label lblModeStockageCompteurExterne09ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne09) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 09 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne09, Rubrique::setModeStockageCompteurExterne09); Label lblModeStockageCompteurExterne10ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne10) //.asRequired("La Saisie du Mode de Stockage Compteur de Externe 10 est requise. Veuillez sélectionner un Mode de Stockage Compteur de Externe") .bind(Rubrique::getModeStockageCompteurExterne10, Rubrique::setModeStockageCompteurExterne10); /* 3 - Alternative : Bind Fields instances that need validators manually and then bind all remaining fields using the bindInstanceFields method this.binder.bindInstanceFields(this.formLayout); //Automatic Data Binding //bindInstanceFields matches fields in Rubrique and RubriqueView based on their names. */ //4 - Add input fields to formLayout - We don't use .setLabel since we will use addFormItem instead of add to add items to the form - addFormItem allows us to set SuperTextField with on a FormaLayout when add doesn't //this.formLayout.add(this.txtNoRubrique, this.txtLibelleRubrique, this.txtLibelleCourtRubrique, this.txtNomMandataire, this.txtNoTelephone, this.txtNoMobile, this.txtNoTelecopie, this.datDateNaissance, this.txtLieuNaissance, this.txtAdresse, this.txtVille, this.txtNombreHomme, this.txtNombreFemme, this.chkInactif, this.txtNoPieceIdentite, this.chkDeposant, this.chkEmprunteur, this.chkGarant, this.chkDirigeant, this.chkAdministrateur); //4 - Alternative this.tabInfoGeneraleFormLayout.addFormItem(this.txtNoRubrique, "N° Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtLibelleRubrique, "Libellé Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtLibelleCourtRubrique, "Libellé Abrégé Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkInactif, "Inactif :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkEditionFacture, "Edition Facture :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkEditionSynthetique, "Edition Synthétique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeModeValorisationRubrique, "Mode Valorisation Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtMontantFixe, "Montant Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeModeValorisationBase, "Mode Détermination Base :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtBaseFixe, "BaseFixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeModeValorisationTaux, "Mode Détermination Taux :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtTauxFixe, "Taux Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtCoefficientMultiplicateur, "Coefficient Multiplicateur :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeTranche, "Tranche :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeVariableRubrique, "Variable Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeConstanteRubrique, "EmploiFonds Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeVariableBase, "Variable Base :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeConstanteBase, "EmploiFonds Base :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeVariableTaux, "Variable Taux :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeConstanteTaux, "EmploiFonds Taux :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeValeurMinimum, "Valeur Minimum :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtValeurMinimumFixe, "Valeur Minimum Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeValeurMaximum, "Titre Civilité :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtValeurMaximumFixe, "Valeur Maximum Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeConstanteValeurMinimum, "EmploiFonds Valeur Minimum :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeConstanteValeurMaximum, "EmploiFonds Valeur Maximum :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeModeAbattement, "Mode Abattement :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtAbattementFixe, "Abattement Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeModeArrondissement, "Mode Arrondissement :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtNombreChiffreArrondissement, "Nombre Chiffre Arrondissement :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase01, "Compteur Base 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase02, "Compteur Base 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase03, "Compteur Base 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase04, "Compteur Base 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant01, "Compteur Montant 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant02, "Compteur Montant 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant03, "Compteur Montant 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant04, "Compteur Montant 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne01, "Compteur Interne 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne02, "Compteur Interne 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne03, "Compteur Interne 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne04, "Compteur Interne 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne05, "Compteur Interne 05 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne06, "Compteur Interne 06 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne07, "Compteur Interne 07 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne08, "Compteur Interne 08 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne09, "Compteur Interne 09 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne10, "Compteur Interne 10 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne01, "Compteur Externe 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne02, "Compteur Externe 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne03, "Compteur Externe 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne04, "Compteur Externe 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne05, "Compteur Externe 05 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne06, "Compteur Externe 06 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne07, "Compteur Externe 07 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne08, "Compteur Externe 08 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne09, "Compteur Externe 09 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne10, "Compteur Externe 10 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); //5 - Making the Layout Responsive : Custom responsive layouting //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top and there is only 1 column. The form will show 2 columns if width is >= 600px tabInfoGeneraleFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. tabInfoGeneraleFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top and there is only 1 column. The form will show 2 columns if width is >= 600px tabDefinitionFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. tabDefinitionFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top and there is only 1 column. The form will show 2 columns if width is >= 600px tabAjustementFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. tabAjustementFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ this.tabCompteurBaseMontantFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. this.tabCompteurBaseMontantFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ this.tabCompteurInterneFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. this.tabCompteurInterneFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ this.tabCompteurExterneFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); /* //breakpoint at 600px, with the label to the side. At resolutions lower than 600px, the label will be at the top. In both cases there is only 1 column. this.tabCompteurExterneFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 1, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); */ //6 - Configure Tabs this.tabsToPages.put(this.tabInfoGenerale, this.tabInfoGeneraleFormLayout); this.tabsToPages.put(this.tabDefinition, this.tabDefinitionFormLayout); this.tabsToPages.put(this.tabAjustement, this.tabAjustementFormLayout); this.tabsToPages.put(this.tabCompteurBaseMontant, this.tabCompteurBaseMontantFormLayout); this.tabsToPages.put(this.tabCompteurInterne, this.tabCompteurInterneFormLayout); this.tabsToPages.put(this.tabCompteurExterne, this.tabCompteurExterneFormLayout); this.tabs.add(this.tabInfoGenerale, this.tabDefinition, this.tabAjustement, this.tabCompteurBaseMontant, this.tabCompteurInterne, this.tabCompteurExterne); this.pages.add(this.tabInfoGeneraleFormLayout, this.tabDefinitionFormLayout, this.tabAjustementFormLayout, this.tabCompteurBaseMontantFormLayout, this.tabCompteurInterneFormLayout, this.tabCompteurExterneFormLayout); //Configure OnSelectedTabChange this.tabs.addSelectedChangeListener(event -> { VaadinSession.getCurrent().setAttribute(CACHED_SELECTED_TAB_INDEX, this.tabs.getSelectedIndex()); this.showSelectedTab(); }); //Cache Selected Tab if (VaadinSession.getCurrent().getAttribute(CACHED_SELECTED_TAB_INDEX) == null) { VaadinSession.getCurrent().setAttribute(CACHED_SELECTED_TAB_INDEX, 0); } //First Page to show programmatically this.tabs.setSelectedIndex((int)VaadinSession.getCurrent().getAttribute(CACHED_SELECTED_TAB_INDEX)); //Pre-select tabs this.showSelectedTab(); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerRubriqueDialog.configureComponents", e.toString()); e.printStackTrace(); } }
private void configureComponents() { try { this.tabs.addClassName("fichier-tab"); this.tabs.setOrientation(Tabs.Orientation.HORIZONTAL); this.tabs.setFlexGrowForEnclosedTabs(1); this.tabs.addThemeVariants(TabsVariant.LUMO_SMALL); this.tabs.setWidthFull(); this.tabInfoGenerale.setLabel("Informations Générales"); this.tabDefinition.setLabel("Définitions"); this.tabAjustement.setLabel("Ajustement"); this.tabCompteurBaseMontant.setLabel("Stockage des Compteurs Base et Montant"); this.tabCompteurInterne.setLabel("Stockage des Compteurs Internes"); this.tabCompteurExterne.setLabel("Stockage des Compteurs Externes"); this.pages.setSizeFull(); this.tabInfoGeneraleFormLayout.addClassName("fichier-form"); this.tabInfoGeneraleFormLayout.setSizeFull(); this.tabInfoGeneraleFormLayout.setVisible(true); this.tabDefinitionFormLayout.addClassName("fichier-form"); this.tabDefinitionFormLayout.setSizeFull(); this.tabDefinitionFormLayout.setVisible(true); this.tabAjustementFormLayout.addClassName("fichier-form"); this.tabAjustementFormLayout.setSizeFull(); this.tabAjustementFormLayout.setVisible(true); this.tabCompteurBaseMontantFormLayout.addClassName("fichier-form"); this.tabCompteurBaseMontantFormLayout.setSizeFull(); this.tabCompteurBaseMontantFormLayout.setVisible(false); this.tabCompteurInterneFormLayout.addClassName("fichier-form"); this.tabCompteurInterneFormLayout.setSizeFull(); this.tabCompteurInterneFormLayout.setVisible(false); this.tabCompteurExterneFormLayout.addClassName("fichier-form"); this.tabCompteurExterneFormLayout.setSizeFull(); this.tabCompteurExterneFormLayout.setVisible(false); this.txtNoRubrique.setWidth(100, Unit.PIXELS); this.txtNoRubrique.setRequired(true); this.txtNoRubrique.setRequiredIndicatorVisible(true); this.txtNoRubrique.addClassName(TEXTFIELD_LEFT_LABEL); this.txtLibelleRubrique.setWidth(350, Unit.PIXELS); this.txtLibelleRubrique.addClassName(TEXTFIELD_LEFT_LABEL); this.txtLibelleCourtRubrique.setWidth(350, Unit.PIXELS); this.txtLibelleCourtRubrique.addClassName(TEXTFIELD_LEFT_LABEL); this.chkInactif.setAutofocus(false); this.chkEditionFacture.setAutofocus(true); this.chkEditionSynthetique.setAutofocus(true); this.cboCodeModeValorisationRubrique.setWidth(350, Unit.PIXELS); this.cboCodeModeValorisationRubrique.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeValorisationRubrique.setItemLabelGenerator(SystemeModeValorisationCommission::getLibelleModeValorisation); this.cboCodeModeValorisationRubrique.setRequired(true); this.cboCodeModeValorisationRubrique.setRequiredIndicatorVisible(true); this.cboCodeModeValorisationRubrique.setClearButtonVisible(true); this.cboCodeModeValorisationRubrique.setAllowCustomValue(false); this.cboCodeModeValorisationRubrique.setPreventInvalidInput(true); this.cboCodeModeValorisationRubrique.addValueChangeListener(event -> { this.myControlsManageAccordingToModeValorisation(); }); this.txtMontantFixe.setWidth(100, Unit.PIXELS); this.txtMontantFixe.setRequiredIndicatorVisible(true); this.txtMontantFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtMontantFixe.setLocale(Locale.FRENCH); this.txtMontantFixe.withNullValueAllowed(false); this.cboCodeModeValorisationBase.setWidth(350, Unit.PIXELS); this.cboCodeModeValorisationBase.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeValorisationBase.setItemLabelGenerator(SystemeModeValorisationBaseCommission::getLibelleModeValorisation); this.cboCodeModeValorisationBase.setRequired(true); this.cboCodeModeValorisationBase.setRequiredIndicatorVisible(true); this.cboCodeModeValorisationBase.setClearButtonVisible(true); this.cboCodeModeValorisationBase.setAllowCustomValue(false); this.cboCodeModeValorisationBase.setPreventInvalidInput(true); this.cboCodeModeValorisationBase.addValueChangeListener(event -> { this.myControlsManageAccordingToModeValorisation(); }); this.txtBaseFixe.setWidth(100, Unit.PIXELS); this.txtBaseFixe.setRequiredIndicatorVisible(true); this.txtBaseFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtBaseFixe.setLocale(Locale.FRENCH); this.txtBaseFixe.withNullValueAllowed(false); this.cboCodeModeValorisationTaux.setWidth(350, Unit.PIXELS); this.cboCodeModeValorisationTaux.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeValorisationTaux.setItemLabelGenerator(SystemeModeValorisationTauxCommission::getLibelleModeValorisation); this.cboCodeModeValorisationTaux.setRequired(true); this.cboCodeModeValorisationTaux.setRequiredIndicatorVisible(true); this.cboCodeModeValorisationTaux.setClearButtonVisible(true); this.cboCodeModeValorisationTaux.setAllowCustomValue(false); this.cboCodeModeValorisationTaux.setPreventInvalidInput(true); this.cboCodeModeValorisationTaux.addValueChangeListener(event -> { this.myControlsManageAccordingToModeValorisation(); }); this.txtTauxFixe.setWidth(100, Unit.PIXELS); this.txtTauxFixe.setRequiredIndicatorVisible(true); this.txtTauxFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtTauxFixe.setLocale(Locale.FRENCH); this.txtTauxFixe.withNullValueAllowed(false); this.txtCoefficientMultiplicateur.setWidth(100, Unit.PIXELS); this.txtCoefficientMultiplicateur.setRequiredIndicatorVisible(true); this.txtCoefficientMultiplicateur.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtCoefficientMultiplicateur.setLocale(Locale.FRENCH); this.txtCoefficientMultiplicateur.withNullValueAllowed(false); this.cboCodeTranche.setWidth(350, Unit.PIXELS); this.cboCodeTranche.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeTranche.setItemLabelGenerator(TrancheValeur::getLibelleTranche); this.cboCodeTranche.setRequired(true); this.cboCodeTranche.setRequiredIndicatorVisible(true); this.cboCodeTranche.setClearButtonVisible(true); this.cboCodeTranche.setAllowCustomValue(true); this.cboCodeTranche.setPreventInvalidInput(true); this.cboCodeTranche.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Tranche de Valeur choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeTranche.setValue(event.getOldValue()); } } }); this.cboCodeTranche.addCustomValueSetListener(event -> { this.cboCodeTranche_NotInList(event.getDetail(), 50); }); this.cboCodeVariableRubrique.setWidth(350, Unit.PIXELS); this.cboCodeVariableRubrique.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeVariableRubrique.setItemLabelGenerator(VariableService::getLibelleVariable); this.cboCodeVariableRubrique.setRequired(true); this.cboCodeVariableRubrique.setRequiredIndicatorVisible(true); this.cboCodeVariableRubrique.setClearButtonVisible(true); this.cboCodeVariableRubrique.setAllowCustomValue(true); this.cboCodeVariableRubrique.setPreventInvalidInput(true); this.cboCodeVariableRubrique.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Variable choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeVariableRubrique.setValue(event.getOldValue()); } } }); this.cboCodeVariableRubrique.addCustomValueSetListener(event -> { this.cboCodeVariableRubrique_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteRubrique.setWidth(350, Unit.PIXELS); this.cboCodeConstanteRubrique.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeConstanteRubrique.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteRubrique.setRequired(true); this.cboCodeConstanteRubrique.setRequiredIndicatorVisible(true); this.cboCodeConstanteRubrique.setClearButtonVisible(true); this.cboCodeConstanteRubrique.setAllowCustomValue(true); this.cboCodeConstanteRubrique.setPreventInvalidInput(true); this.cboCodeConstanteRubrique.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeConstanteRubrique.setValue(event.getOldValue()); } } }); this.cboCodeConstanteRubrique.addCustomValueSetListener(event -> { this.cboCodeConstanteRubrique_NotInList(event.getDetail(), 50); }); this.cboCodeVariableBase.setWidth(350, Unit.PIXELS); this.cboCodeVariableBase.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeVariableBase.setItemLabelGenerator(VariableService::getLibelleVariable); this.cboCodeVariableBase.setRequired(true); this.cboCodeVariableBase.setRequiredIndicatorVisible(true); this.cboCodeVariableBase.setClearButtonVisible(true); this.cboCodeVariableBase.setAllowCustomValue(true); this.cboCodeVariableBase.setPreventInvalidInput(true); this.cboCodeVariableBase.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Variable choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeVariableBase.setValue(event.getOldValue()); } } }); this.cboCodeVariableBase.addCustomValueSetListener(event -> { this.cboCodeVariableBase_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteBase.setWidth(350, Unit.PIXELS); this.cboCodeConstanteBase.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeConstanteBase.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteBase.setRequired(true); this.cboCodeConstanteBase.setRequiredIndicatorVisible(true); this.cboCodeConstanteBase.setClearButtonVisible(true); this.cboCodeConstanteBase.setAllowCustomValue(true); this.cboCodeConstanteBase.setPreventInvalidInput(true); this.cboCodeConstanteBase.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeConstanteBase.setValue(event.getOldValue()); } } }); this.cboCodeConstanteBase.addCustomValueSetListener(event -> { this.cboCodeConstanteBase_NotInList(event.getDetail(), 50); }); this.cboCodeVariableTaux.setWidth(350, Unit.PIXELS); this.cboCodeVariableTaux.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeVariableTaux.setItemLabelGenerator(VariableService::getLibelleVariable); this.cboCodeVariableTaux.setRequired(true); this.cboCodeVariableTaux.setRequiredIndicatorVisible(true); this.cboCodeVariableTaux.setClearButtonVisible(true); this.cboCodeVariableTaux.setAllowCustomValue(true); this.cboCodeVariableTaux.setPreventInvalidInput(true); this.cboCodeVariableTaux.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La Variable choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeVariableTaux.setValue(event.getOldValue()); } } }); this.cboCodeVariableTaux.addCustomValueSetListener(event -> { this.cboCodeVariableTaux_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteTaux.setWidth(350, Unit.PIXELS); this.cboCodeConstanteTaux.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeConstanteTaux.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteTaux.setRequired(true); this.cboCodeConstanteTaux.setRequiredIndicatorVisible(true); this.cboCodeConstanteTaux.setClearButtonVisible(true); this.cboCodeConstanteTaux.setAllowCustomValue(true); this.cboCodeConstanteTaux.setPreventInvalidInput(true); this.cboCodeConstanteTaux.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeConstanteTaux.setValue(event.getOldValue()); } } }); this.cboCodeConstanteTaux.addCustomValueSetListener(event -> { this.cboCodeConstanteTaux_NotInList(event.getDetail(), 50); }); this.cboCodeValeurMinimum.setWidth(350, Unit.PIXELS); this.cboCodeValeurMinimum.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeValeurMinimum.setItemLabelGenerator(SystemeValeurMinMax::getLibelleValeur); this.cboCodeValeurMinimum.setRequired(true); this.cboCodeValeurMinimum.setRequiredIndicatorVisible(true); this.cboCodeValeurMinimum.setClearButtonVisible(true); this.cboCodeValeurMinimum.setAllowCustomValue(false); this.cboCodeValeurMinimum.setPreventInvalidInput(true); this.txtValeurMinimumFixe.setWidth(100, Unit.PIXELS); this.txtValeurMinimumFixe.setRequiredIndicatorVisible(true); this.txtValeurMinimumFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtValeurMinimumFixe.setLocale(Locale.FRENCH); this.txtValeurMinimumFixe.withNullValueAllowed(false); this.cboCodeValeurMaximum.setWidth(350, Unit.PIXELS); this.cboCodeValeurMaximum.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeValeurMaximum.setItemLabelGenerator(SystemeValeurMinMax::getLibelleValeur); this.cboCodeValeurMaximum.setRequired(true); this.cboCodeValeurMaximum.setRequiredIndicatorVisible(true); this.cboCodeValeurMaximum.setClearButtonVisible(true); this.cboCodeValeurMaximum.setAllowCustomValue(false); this.cboCodeValeurMaximum.setPreventInvalidInput(true); this.txtValeurMaximumFixe.setWidth(100, Unit.PIXELS); this.txtValeurMaximumFixe.setRequiredIndicatorVisible(true); this.txtValeurMaximumFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtValeurMaximumFixe.setLocale(Locale.FRENCH); this.txtValeurMaximumFixe.withNullValueAllowed(false); this.cboCodeConstanteValeurMinimum.setWidth(350, Unit.PIXELS); this.cboCodeConstanteValeurMinimum.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeConstanteValeurMinimum.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteValeurMinimum.setRequired(true); this.cboCodeConstanteValeurMinimum.setRequiredIndicatorVisible(true); this.cboCodeConstanteValeurMinimum.setClearButtonVisible(true); this.cboCodeConstanteValeurMinimum.setAllowCustomValue(true); this.cboCodeConstanteValeurMinimum.setPreventInvalidInput(true); this.cboCodeConstanteValeurMinimum.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeConstanteValeurMinimum.setValue(event.getOldValue()); } } }); this.cboCodeConstanteValeurMinimum.addCustomValueSetListener(event -> { this.cboCodeConstanteValeurMinimum_NotInList(event.getDetail(), 50); }); this.cboCodeConstanteValeurMaximum.setWidth(350, Unit.PIXELS); this.cboCodeConstanteValeurMaximum.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeConstanteValeurMaximum.setItemLabelGenerator(EmploiFonds::getLibelleConstante); this.cboCodeConstanteValeurMaximum.setRequired(true); this.cboCodeConstanteValeurMaximum.setRequiredIndicatorVisible(true); this.cboCodeConstanteValeurMaximum.setClearButtonVisible(true); this.cboCodeConstanteValeurMaximum.setAllowCustomValue(true); this.cboCodeConstanteValeurMaximum.setPreventInvalidInput(true); this.cboCodeConstanteValeurMaximum.addValueChangeListener(event -> { if (event.getValue() != null) { if (event.getValue().isInactif() == true) { MessageDialogHelper.showWarningDialog("Erreur de Saisie", "La EmploiFonds choisie est actuellement désactivée. Veuillez en saisir une autre."); this.cboCodeConstanteValeurMaximum.setValue(event.getOldValue()); } } }); this.cboCodeConstanteValeurMaximum.addCustomValueSetListener(event -> { this.cboCodeConstanteValeurMaximum_NotInList(event.getDetail(), 50); }); this.cboCodeModeAbattement.setWidth(350, Unit.PIXELS); this.cboCodeModeAbattement.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeAbattement.setItemLabelGenerator(SystemeModeAbattement::getLibelleModeAbattement); this.cboCodeModeAbattement.setRequired(true); this.cboCodeModeAbattement.setRequiredIndicatorVisible(true); this.cboCodeModeAbattement.setClearButtonVisible(true); this.cboCodeModeAbattement.setAllowCustomValue(false); this.cboCodeModeAbattement.setPreventInvalidInput(true); this.txtAbattementFixe.setWidth(100, Unit.PIXELS); this.txtAbattementFixe.setRequiredIndicatorVisible(true); this.txtAbattementFixe.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtAbattementFixe.setLocale(Locale.FRENCH); this.txtAbattementFixe.withNullValueAllowed(false); this.cboCodeModeArrondissement.setWidth(350, Unit.PIXELS); this.cboCodeModeArrondissement.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeArrondissement.setItemLabelGenerator(SystemeModeArrondissement::getLibelleModeArrondissement); this.cboCodeModeArrondissement.setRequired(true); this.cboCodeModeArrondissement.setRequiredIndicatorVisible(true); this.cboCodeModeArrondissement.setClearButtonVisible(true); this.cboCodeModeArrondissement.setAllowCustomValue(false); this.cboCodeModeArrondissement.setPreventInvalidInput(true); this.txtNombreChiffreArrondissement.setWidth(100, Unit.PIXELS); this.txtNombreChiffreArrondissement.setRequiredIndicatorVisible(true); this.txtNombreChiffreArrondissement.addThemeVariants(TextFieldVariant.LUMO_ALIGN_CENTER); this.txtNombreChiffreArrondissement.setLocale(Locale.FRENCH); this.txtNombreChiffreArrondissement.withNullValueAllowed(false); this.cboCodeModeStockageCompteurBase01.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurBase01.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurBase01.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase01.setRequired(true); this.cboCodeModeStockageCompteurBase01.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurBase01.setClearButtonVisible(true); this.cboCodeModeStockageCompteurBase01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurBase02.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurBase02.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurBase02.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase02.setRequired(true); this.cboCodeModeStockageCompteurBase02.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurBase02.setClearButtonVisible(true); this.cboCodeModeStockageCompteurBase02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurBase03.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurBase03.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurBase03.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase03.setRequired(true); this.cboCodeModeStockageCompteurBase03.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurBase03.setClearButtonVisible(true); this.cboCodeModeStockageCompteurBase03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurBase04.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurBase04.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurBase04.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurBase04.setRequired(true); this.cboCodeModeStockageCompteurBase04.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurBase04.setClearButtonVisible(true); this.cboCodeModeStockageCompteurBase04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurBase04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant01.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant01.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurMontant01.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant01.setRequired(true); this.cboCodeModeStockageCompteurMontant01.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurMontant01.setClearButtonVisible(true); this.cboCodeModeStockageCompteurMontant01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant02.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant02.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurMontant02.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant02.setRequired(true); this.cboCodeModeStockageCompteurMontant02.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurMontant02.setClearButtonVisible(true); this.cboCodeModeStockageCompteurMontant02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant03.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant03.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurMontant03.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant03.setRequired(true); this.cboCodeModeStockageCompteurMontant03.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurMontant03.setClearButtonVisible(true); this.cboCodeModeStockageCompteurMontant03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurMontant04.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurMontant04.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurMontant04.setItemLabelGenerator(SystemeModeStockageBaseMontant::getLibelleModeStockage); this.cboCodeModeStockageCompteurMontant04.setRequired(true); this.cboCodeModeStockageCompteurMontant04.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurMontant04.setClearButtonVisible(true); this.cboCodeModeStockageCompteurMontant04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurMontant04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne01.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne01.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne01.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne01.setRequired(true); this.cboCodeModeStockageCompteurInterne01.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne01.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne02.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne02.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne02.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne02.setRequired(true); this.cboCodeModeStockageCompteurInterne02.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne02.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne03.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne03.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne03.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne03.setRequired(true); this.cboCodeModeStockageCompteurInterne03.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne03.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne04.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne04.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne04.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne04.setRequired(true); this.cboCodeModeStockageCompteurInterne04.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne04.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne05.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne05.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne05.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne05.setRequired(true); this.cboCodeModeStockageCompteurInterne05.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne05.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne05.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne05.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne06.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne06.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne06.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne06.setRequired(true); this.cboCodeModeStockageCompteurInterne06.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne06.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne06.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne06.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne07.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne07.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne07.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne07.setRequired(true); this.cboCodeModeStockageCompteurInterne07.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne07.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne07.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne07.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne08.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne08.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne08.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne08.setRequired(true); this.cboCodeModeStockageCompteurInterne08.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne08.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne08.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne08.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne09.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne09.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne09.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne09.setRequired(true); this.cboCodeModeStockageCompteurInterne09.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne09.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne09.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne09.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurInterne10.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurInterne10.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurInterne10.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurInterne10.setRequired(true); this.cboCodeModeStockageCompteurInterne10.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurInterne10.setClearButtonVisible(true); this.cboCodeModeStockageCompteurInterne10.setAllowCustomValue(false); this.cboCodeModeStockageCompteurInterne10.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne01.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne01.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne01.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne01.setRequired(true); this.cboCodeModeStockageCompteurExterne01.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne01.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne01.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne01.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne02.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne02.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne02.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne02.setRequired(true); this.cboCodeModeStockageCompteurExterne02.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne02.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne02.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne02.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne03.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne03.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne03.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne03.setRequired(true); this.cboCodeModeStockageCompteurExterne03.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne03.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne03.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne03.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne04.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne04.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne04.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne04.setRequired(true); this.cboCodeModeStockageCompteurExterne04.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne04.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne04.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne04.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne05.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne05.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne05.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne05.setRequired(true); this.cboCodeModeStockageCompteurExterne05.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne05.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne05.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne05.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne06.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne06.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne06.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne06.setRequired(true); this.cboCodeModeStockageCompteurExterne06.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne06.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne06.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne06.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne07.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne07.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne07.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne07.setRequired(true); this.cboCodeModeStockageCompteurExterne07.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne07.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne07.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne07.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne08.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne08.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne08.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne08.setRequired(true); this.cboCodeModeStockageCompteurExterne08.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne08.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne08.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne08.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne09.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne09.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne09.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne09.setRequired(true); this.cboCodeModeStockageCompteurExterne09.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne09.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne09.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne09.setPreventInvalidInput(true); this.cboCodeModeStockageCompteurExterne10.setWidth(350, Unit.PIXELS); this.cboCodeModeStockageCompteurExterne10.addClassName(COMBOBOX_LEFT_LABEL); this.cboCodeModeStockageCompteurExterne10.setItemLabelGenerator(SystemeModeStockageInterneExterne::getLibelleModeStockage); this.cboCodeModeStockageCompteurExterne10.setRequired(true); this.cboCodeModeStockageCompteurExterne10.setRequiredIndicatorVisible(true); this.cboCodeModeStockageCompteurExterne10.setClearButtonVisible(true); this.cboCodeModeStockageCompteurExterne10.setAllowCustomValue(false); this.cboCodeModeStockageCompteurExterne10.setPreventInvalidInput(true); Label lblNoRubriqueValidationStatus = new Label(); this.binder.forField(this.txtNoRubrique) .asRequired("La Saisie du N° Rubrique est Obligatoire. Veuillez saisir le N° Rubrique.") .withValidator(text -> text != null && text.length() <= 10, "N° Rubrique ne peut contenir au plus 10 caractères") .withValidationStatusHandler(status -> {lblNoRubriqueValidationStatus.setText(status.getMessage().orElse("")); lblNoRubriqueValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getNoRubrique, Rubrique::setNoRubrique); Label lblLibelleRubriqueValidationStatus = new Label(); this.binder.forField(this.txtLibelleRubrique) .asRequired("La Saisie du Libellé de la Rubrique est Obligatoire. Veuillez saisir le Libellé de la Rubrique.") .withValidator(text -> text.length() <= 50, "Libellé Rubrique ne peut contenir au plus 50 caractères.") .withValidationStatusHandler(status -> {lblLibelleRubriqueValidationStatus.setText(status.getMessage().orElse("")); lblLibelleRubriqueValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getLibelleRubrique, Rubrique::setLibelleRubrique); Label lblLibelleCourtRubriqueValidationStatus = new Label(); this.binder.forField(this.txtLibelleCourtRubrique) .asRequired("La Saisie du Libellé Abrégé de la Rubrique est Obligatoire. Veuillez saisir le Libellé de la Rubrique.") .withValidator(text -> text.length() <= 30, "Libellé Abrégé Rubrique ne peut contenir au plus 30 caractères.") .withValidationStatusHandler(status -> {lblLibelleCourtRubriqueValidationStatus.setText(status.getMessage().orElse("")); lblLibelleCourtRubriqueValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getLibelleCourtRubrique, Rubrique::setLibelleCourtRubrique); this.binder.forField(this.chkInactif) .bind(Rubrique::isInactif, Rubrique::setInactif); this.binder.forField(this.chkEditionFacture) .bind(Rubrique::isEditionFacture, Rubrique::setEditionFacture); this.binder.forField(this.chkEditionSynthetique) .bind(Rubrique::isEditionSynthetique, Rubrique::setEditionSynthetique); Label lblModeValorisationRubriqueValidationStatus = new Label(); this.binder.forField(this.cboCodeModeValorisationRubrique) .asRequired("La Saisie du Mode de Valorisation de la Rubrique est requise. Veuillez sélectionner un Mode de Valorisation de la Rubrique") .bind(Rubrique::getModeValorisationRubrique, Rubrique::setModeValorisationRubrique); Label lblMontantFixeValidationStatus = new Label(); this.binder.forField(this.txtMontantFixe) .withValidationStatusHandler(status -> {lblMontantFixeValidationStatus.setText(status.getMessage().orElse("")); lblMontantFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getMontantFixe, Rubrique::setMontantFixe); Label lblModeValorisationBaseValidationStatus = new Label(); this.binder.forField(this.cboCodeModeValorisationBase) .bind(Rubrique::getModeValorisationBase, Rubrique::setModeValorisationBase); Label lblBaseFixeValidationStatus = new Label(); this.binder.forField(this.txtBaseFixe) .withValidationStatusHandler(status -> {lblBaseFixeValidationStatus.setText(status.getMessage().orElse("")); lblBaseFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getBaseFixe, Rubrique::setBaseFixe); Label lblModeValorisationTauxValidationStatus = new Label(); this.binder.forField(this.cboCodeModeValorisationTaux) .bind(Rubrique::getModeValorisationTaux, Rubrique::setModeValorisationTaux); Label lblTauxFixeValidationStatus = new Label(); this.binder.forField(this.txtTauxFixe) .withValidationStatusHandler(status -> {lblTauxFixeValidationStatus.setText(status.getMessage().orElse("")); lblTauxFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getTauxFixe, Rubrique::setTauxFixe); Label lblCoefficientMultiplicateurValidationStatus = new Label(); this.binder.forField(this.txtCoefficientMultiplicateur) .asRequired("La Saisie du Coefficient Multiplicateur est Obligatoire. Veuillez saisir le Coefficient Multiplicateur.") .withValidationStatusHandler(status -> {lblCoefficientMultiplicateurValidationStatus.setText(status.getMessage().orElse("")); lblCoefficientMultiplicateurValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getCoefficientMultiplicateur, Rubrique::setCoefficientMultiplicateur); Label lblTrancheValeurValidationStatus = new Label(); this.binder.forField(this.cboCodeTranche) .bind(Rubrique::getTranche, Rubrique::setTranche); Label lblVariableRubriqueValidationStatus = new Label(); this.binder.forField(this.cboCodeVariableRubrique) .bind(Rubrique::getVariableRubrique, Rubrique::setVariableRubrique); Label lblConstanteRubriqueValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteRubrique) .bind(Rubrique::getConstanteRubrique, Rubrique::setConstanteRubrique); Label lblVariableBaseValidationStatus = new Label(); this.binder.forField(this.cboCodeVariableBase) .bind(Rubrique::getVariableBase, Rubrique::setVariableBase); Label lblConstanteBaseValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteBase) .bind(Rubrique::getConstanteBase, Rubrique::setConstanteBase); Label lblVariableTauxValidationStatus = new Label(); this.binder.forField(this.cboCodeVariableTaux) .bind(Rubrique::getVariableTaux, Rubrique::setVariableTaux); Label lblConstanteTauxValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteTaux) .bind(Rubrique::getConstanteTaux, Rubrique::setConstanteTaux); Label lblValeurMinimumValidationStatus = new Label(); this.binder.forField(this.cboCodeValeurMinimum) .bind(Rubrique::getValeurMinimum, Rubrique::setValeurMinimum); Label lblValeurMinimumFixeValidationStatus = new Label(); this.binder.forField(this.txtValeurMinimumFixe) .withValidationStatusHandler(status -> {lblValeurMinimumFixeValidationStatus.setText(status.getMessage().orElse("")); lblValeurMinimumFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getValeurMinimumFixe, Rubrique::setValeurMinimumFixe); Label lblValeurMaximumValidationStatus = new Label(); this.binder.forField(this.cboCodeValeurMaximum) .bind(Rubrique::getValeurMaximum, Rubrique::setValeurMaximum); Label lblValeurMaximumFixeValidationStatus = new Label(); this.binder.forField(this.txtValeurMaximumFixe) .withValidationStatusHandler(status -> {lblValeurMaximumFixeValidationStatus.setText(status.getMessage().orElse("")); lblValeurMaximumFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getValeurMaximumFixe, Rubrique::setValeurMaximumFixe); Label lblConstanteValeurMinimumValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteValeurMinimum) .bind(Rubrique::getConstanteValeurMinimum, Rubrique::setConstanteValeurMinimum); Label lblConstanteValeurMaximumValidationStatus = new Label(); this.binder.forField(this.cboCodeConstanteValeurMaximum) .bind(Rubrique::getConstanteValeurMaximum, Rubrique::setConstanteValeurMaximum); Label lblModeAbattementValidationStatus = new Label(); this.binder.forField(this.cboCodeModeAbattement) .bind(Rubrique::getModeAbattement, Rubrique::setModeAbattement); Label lblAbattementFixeValidationStatus = new Label(); this.binder.forField(this.txtAbattementFixe) .withValidationStatusHandler(status -> {lblAbattementFixeValidationStatus.setText(status.getMessage().orElse("")); lblAbattementFixeValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getAbattementFixe, Rubrique::setAbattementFixe); Label lblModeArrondissementValidationStatus = new Label(); this.binder.forField(this.cboCodeModeArrondissement) .bind(Rubrique::getModeArrondissement, Rubrique::setModeArrondissement); Label lblNombreChiffreArrondissementValidationStatus = new Label(); this.binder.forField(this.txtNombreChiffreArrondissement) .withValidationStatusHandler(status -> {lblNombreChiffreArrondissementValidationStatus.setText(status.getMessage().orElse("")); lblNombreChiffreArrondissementValidationStatus.setVisible(status.isError());}) .bind(Rubrique::getNombreChiffreArrondissement, Rubrique::setNombreChiffreArrondissement); Label lblModeStockageCompteurBase01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase01) .bind(Rubrique::getModeStockageCompteurBase01, Rubrique::setModeStockageCompteurBase01); Label lblModeStockageCompteurBase02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase02) .bind(Rubrique::getModeStockageCompteurBase02, Rubrique::setModeStockageCompteurBase02); Label lblModeStockageCompteurBase03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase03) .bind(Rubrique::getModeStockageCompteurBase03, Rubrique::setModeStockageCompteurBase03); Label lblModeStockageCompteurBase04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurBase04) .bind(Rubrique::getModeStockageCompteurBase04, Rubrique::setModeStockageCompteurBase04); Label lblModeStockageCompteurMontant01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant01) .bind(Rubrique::getModeStockageCompteurMontant01, Rubrique::setModeStockageCompteurMontant01); Label lblModeStockageCompteurMontant02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant02) .bind(Rubrique::getModeStockageCompteurMontant02, Rubrique::setModeStockageCompteurMontant02); Label lblModeStockageCompteurMontant03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant03) .bind(Rubrique::getModeStockageCompteurMontant03, Rubrique::setModeStockageCompteurMontant03); Label lblModeStockageCompteurMontant04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurMontant04) .bind(Rubrique::getModeStockageCompteurMontant04, Rubrique::setModeStockageCompteurMontant04); Label lblModeStockageCompteurInterne01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne01) .bind(Rubrique::getModeStockageCompteurInterne01, Rubrique::setModeStockageCompteurInterne01); Label lblModeStockageCompteurInterne02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne02) .bind(Rubrique::getModeStockageCompteurInterne02, Rubrique::setModeStockageCompteurInterne02); Label lblModeStockageCompteurInterne03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne03) .bind(Rubrique::getModeStockageCompteurInterne03, Rubrique::setModeStockageCompteurInterne03); Label lblModeStockageCompteurInterne04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne04) .bind(Rubrique::getModeStockageCompteurInterne04, Rubrique::setModeStockageCompteurInterne04); Label lblModeStockageCompteurInterne05ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne05) .bind(Rubrique::getModeStockageCompteurInterne05, Rubrique::setModeStockageCompteurInterne05); Label lblModeStockageCompteurInterne06ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne06) .bind(Rubrique::getModeStockageCompteurInterne06, Rubrique::setModeStockageCompteurInterne06); Label lblModeStockageCompteurInterne07ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne07) .bind(Rubrique::getModeStockageCompteurInterne07, Rubrique::setModeStockageCompteurInterne07); Label lblModeStockageCompteurInterne08ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne08) .bind(Rubrique::getModeStockageCompteurInterne08, Rubrique::setModeStockageCompteurInterne08); Label lblModeStockageCompteurInterne09ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne09) .bind(Rubrique::getModeStockageCompteurInterne09, Rubrique::setModeStockageCompteurInterne09); Label lblModeStockageCompteurInterne10ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurInterne10) .bind(Rubrique::getModeStockageCompteurInterne10, Rubrique::setModeStockageCompteurInterne10); Label lblModeStockageCompteurExterne01ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne01) .bind(Rubrique::getModeStockageCompteurExterne01, Rubrique::setModeStockageCompteurExterne01); Label lblModeStockageCompteurExterne02ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne02) .bind(Rubrique::getModeStockageCompteurExterne02, Rubrique::setModeStockageCompteurExterne02); Label lblModeStockageCompteurExterne03ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne03) .bind(Rubrique::getModeStockageCompteurExterne03, Rubrique::setModeStockageCompteurExterne03); Label lblModeStockageCompteurExterne04ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne04) .bind(Rubrique::getModeStockageCompteurExterne04, Rubrique::setModeStockageCompteurExterne04); Label lblModeStockageCompteurExterne05ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne05) .bind(Rubrique::getModeStockageCompteurExterne05, Rubrique::setModeStockageCompteurExterne05); Label lblModeStockageCompteurExterne06ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne06) .bind(Rubrique::getModeStockageCompteurExterne06, Rubrique::setModeStockageCompteurExterne06); Label lblModeStockageCompteurExterne07ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne07) .bind(Rubrique::getModeStockageCompteurExterne07, Rubrique::setModeStockageCompteurExterne07); Label lblModeStockageCompteurExterne08ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne08) .bind(Rubrique::getModeStockageCompteurExterne08, Rubrique::setModeStockageCompteurExterne08); Label lblModeStockageCompteurExterne09ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne09) .bind(Rubrique::getModeStockageCompteurExterne09, Rubrique::setModeStockageCompteurExterne09); Label lblModeStockageCompteurExterne10ValidationStatus = new Label(); this.binder.forField(this.cboCodeModeStockageCompteurExterne10) .bind(Rubrique::getModeStockageCompteurExterne10, Rubrique::setModeStockageCompteurExterne10); this.tabInfoGeneraleFormLayout.addFormItem(this.txtNoRubrique, "N° Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtLibelleRubrique, "Libellé Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.txtLibelleCourtRubrique, "Libellé Abrégé Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkInactif, "Inactif :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkEditionFacture, "Edition Facture :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabInfoGeneraleFormLayout.addFormItem(this.chkEditionSynthetique, "Edition Synthétique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeModeValorisationRubrique, "Mode Valorisation Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtMontantFixe, "Montant Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeModeValorisationBase, "Mode Détermination Base :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtBaseFixe, "BaseFixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeModeValorisationTaux, "Mode Détermination Taux :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtTauxFixe, "Taux Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.txtCoefficientMultiplicateur, "Coefficient Multiplicateur :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeTranche, "Tranche :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeVariableRubrique, "Variable Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeConstanteRubrique, "EmploiFonds Rubrique :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeVariableBase, "Variable Base :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeConstanteBase, "EmploiFonds Base :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeVariableTaux, "Variable Taux :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabDefinitionFormLayout.addFormItem(this.cboCodeConstanteTaux, "EmploiFonds Taux :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeValeurMinimum, "Valeur Minimum :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtValeurMinimumFixe, "Valeur Minimum Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeValeurMaximum, "Titre Civilité :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtValeurMaximumFixe, "Valeur Maximum Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeConstanteValeurMinimum, "EmploiFonds Valeur Minimum :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeConstanteValeurMaximum, "EmploiFonds Valeur Maximum :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeModeAbattement, "Mode Abattement :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtAbattementFixe, "Abattement Fixe :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.cboCodeModeArrondissement, "Mode Arrondissement :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabAjustementFormLayout.addFormItem(this.txtNombreChiffreArrondissement, "Nombre Chiffre Arrondissement :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase01, "Compteur Base 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase02, "Compteur Base 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase03, "Compteur Base 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurBase04, "Compteur Base 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant01, "Compteur Montant 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant02, "Compteur Montant 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant03, "Compteur Montant 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurBaseMontantFormLayout.addFormItem(this.cboCodeModeStockageCompteurMontant04, "Compteur Montant 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne01, "Compteur Interne 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne02, "Compteur Interne 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne03, "Compteur Interne 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne04, "Compteur Interne 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne05, "Compteur Interne 05 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne06, "Compteur Interne 06 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne07, "Compteur Interne 07 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne08, "Compteur Interne 08 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne09, "Compteur Interne 09 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurInterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurInterne10, "Compteur Interne 10 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne01, "Compteur Externe 01 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne02, "Compteur Externe 02 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne03, "Compteur Externe 03 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne04, "Compteur Externe 04 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne05, "Compteur Externe 05 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne06, "Compteur Externe 06 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne07, "Compteur Externe 07 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne08, "Compteur Externe 08 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne09, "Compteur Externe 09 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); this.tabCompteurExterneFormLayout.addFormItem(this.cboCodeModeStockageCompteurExterne10, "Compteur Externe 10 :").getStyle().set("--vaadin-form-item-label-width", FORM_ITEM_LABEL_WIDTH200); tabInfoGeneraleFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); tabDefinitionFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); tabAjustementFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); this.tabCompteurBaseMontantFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); this.tabCompteurInterneFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); this.tabCompteurExterneFormLayout.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1, FormLayout.ResponsiveStep.LabelsPosition.TOP), new FormLayout.ResponsiveStep(PANEL_FLEX_BASIS, 2, FormLayout.ResponsiveStep.LabelsPosition.ASIDE)); this.tabsToPages.put(this.tabInfoGenerale, this.tabInfoGeneraleFormLayout); this.tabsToPages.put(this.tabDefinition, this.tabDefinitionFormLayout); this.tabsToPages.put(this.tabAjustement, this.tabAjustementFormLayout); this.tabsToPages.put(this.tabCompteurBaseMontant, this.tabCompteurBaseMontantFormLayout); this.tabsToPages.put(this.tabCompteurInterne, this.tabCompteurInterneFormLayout); this.tabsToPages.put(this.tabCompteurExterne, this.tabCompteurExterneFormLayout); this.tabs.add(this.tabInfoGenerale, this.tabDefinition, this.tabAjustement, this.tabCompteurBaseMontant, this.tabCompteurInterne, this.tabCompteurExterne); this.pages.add(this.tabInfoGeneraleFormLayout, this.tabDefinitionFormLayout, this.tabAjustementFormLayout, this.tabCompteurBaseMontantFormLayout, this.tabCompteurInterneFormLayout, this.tabCompteurExterneFormLayout); this.tabs.addSelectedChangeListener(event -> { VaadinSession.getCurrent().setAttribute(CACHED_SELECTED_TAB_INDEX, this.tabs.getSelectedIndex()); this.showSelectedTab(); }); if (VaadinSession.getCurrent().getAttribute(CACHED_SELECTED_TAB_INDEX) == null) { VaadinSession.getCurrent().setAttribute(CACHED_SELECTED_TAB_INDEX, 0); } this.tabs.setSelectedIndex((int)VaadinSession.getCurrent().getAttribute(CACHED_SELECTED_TAB_INDEX)); this.showSelectedTab(); } catch (Exception e) { MessageDialogHelper.showAlertDialog("EditerRubriqueDialog.configureComponents", e.toString()); e.printStackTrace(); } }
private void configurecomponents() { try { this.tabs.addclassname("fichier-tab"); this.tabs.setorientation(tabs.orientation.horizontal); this.tabs.setflexgrowforenclosedtabs(1); this.tabs.addthemevariants(tabsvariant.lumo_small); this.tabs.setwidthfull(); this.tabinfogenerale.setlabel("informations générales"); this.tabdefinition.setlabel("définitions"); this.tabajustement.setlabel("ajustement"); this.tabcompteurbasemontant.setlabel("stockage des compteurs base et montant"); this.tabcompteurinterne.setlabel("stockage des compteurs internes"); this.tabcompteurexterne.setlabel("stockage des compteurs externes"); this.pages.setsizefull(); this.tabinfogeneraleformlayout.addclassname("fichier-form"); this.tabinfogeneraleformlayout.setsizefull(); this.tabinfogeneraleformlayout.setvisible(true); this.tabdefinitionformlayout.addclassname("fichier-form"); this.tabdefinitionformlayout.setsizefull(); this.tabdefinitionformlayout.setvisible(true); this.tabajustementformlayout.addclassname("fichier-form"); this.tabajustementformlayout.setsizefull(); this.tabajustementformlayout.setvisible(true); this.tabcompteurbasemontantformlayout.addclassname("fichier-form"); this.tabcompteurbasemontantformlayout.setsizefull(); this.tabcompteurbasemontantformlayout.setvisible(false); this.tabcompteurinterneformlayout.addclassname("fichier-form"); this.tabcompteurinterneformlayout.setsizefull(); this.tabcompteurinterneformlayout.setvisible(false); this.tabcompteurexterneformlayout.addclassname("fichier-form"); this.tabcompteurexterneformlayout.setsizefull(); this.tabcompteurexterneformlayout.setvisible(false); this.txtnorubrique.setwidth(100, unit.pixels); this.txtnorubrique.setrequired(true); this.txtnorubrique.setrequiredindicatorvisible(true); this.txtnorubrique.addclassname(textfield_left_label); this.txtlibellerubrique.setwidth(350, unit.pixels); this.txtlibellerubrique.addclassname(textfield_left_label); this.txtlibellecourtrubrique.setwidth(350, unit.pixels); this.txtlibellecourtrubrique.addclassname(textfield_left_label); this.chkinactif.setautofocus(false); this.chkeditionfacture.setautofocus(true); this.chkeditionsynthetique.setautofocus(true); this.cbocodemodevalorisationrubrique.setwidth(350, unit.pixels); this.cbocodemodevalorisationrubrique.addclassname(combobox_left_label); this.cbocodemodevalorisationrubrique.setitemlabelgenerator(systememodevalorisationcommission::getlibellemodevalorisation); this.cbocodemodevalorisationrubrique.setrequired(true); this.cbocodemodevalorisationrubrique.setrequiredindicatorvisible(true); this.cbocodemodevalorisationrubrique.setclearbuttonvisible(true); this.cbocodemodevalorisationrubrique.setallowcustomvalue(false); this.cbocodemodevalorisationrubrique.setpreventinvalidinput(true); this.cbocodemodevalorisationrubrique.addvaluechangelistener(event -> { this.mycontrolsmanageaccordingtomodevalorisation(); }); this.txtmontantfixe.setwidth(100, unit.pixels); this.txtmontantfixe.setrequiredindicatorvisible(true); this.txtmontantfixe.addthemevariants(textfieldvariant.lumo_align_center); this.txtmontantfixe.setlocale(locale.french); this.txtmontantfixe.withnullvalueallowed(false); this.cbocodemodevalorisationbase.setwidth(350, unit.pixels); this.cbocodemodevalorisationbase.addclassname(combobox_left_label); this.cbocodemodevalorisationbase.setitemlabelgenerator(systememodevalorisationbasecommission::getlibellemodevalorisation); this.cbocodemodevalorisationbase.setrequired(true); this.cbocodemodevalorisationbase.setrequiredindicatorvisible(true); this.cbocodemodevalorisationbase.setclearbuttonvisible(true); this.cbocodemodevalorisationbase.setallowcustomvalue(false); this.cbocodemodevalorisationbase.setpreventinvalidinput(true); this.cbocodemodevalorisationbase.addvaluechangelistener(event -> { this.mycontrolsmanageaccordingtomodevalorisation(); }); this.txtbasefixe.setwidth(100, unit.pixels); this.txtbasefixe.setrequiredindicatorvisible(true); this.txtbasefixe.addthemevariants(textfieldvariant.lumo_align_center); this.txtbasefixe.setlocale(locale.french); this.txtbasefixe.withnullvalueallowed(false); this.cbocodemodevalorisationtaux.setwidth(350, unit.pixels); this.cbocodemodevalorisationtaux.addclassname(combobox_left_label); this.cbocodemodevalorisationtaux.setitemlabelgenerator(systememodevalorisationtauxcommission::getlibellemodevalorisation); this.cbocodemodevalorisationtaux.setrequired(true); this.cbocodemodevalorisationtaux.setrequiredindicatorvisible(true); this.cbocodemodevalorisationtaux.setclearbuttonvisible(true); this.cbocodemodevalorisationtaux.setallowcustomvalue(false); this.cbocodemodevalorisationtaux.setpreventinvalidinput(true); this.cbocodemodevalorisationtaux.addvaluechangelistener(event -> { this.mycontrolsmanageaccordingtomodevalorisation(); }); this.txttauxfixe.setwidth(100, unit.pixels); this.txttauxfixe.setrequiredindicatorvisible(true); this.txttauxfixe.addthemevariants(textfieldvariant.lumo_align_center); this.txttauxfixe.setlocale(locale.french); this.txttauxfixe.withnullvalueallowed(false); this.txtcoefficientmultiplicateur.setwidth(100, unit.pixels); this.txtcoefficientmultiplicateur.setrequiredindicatorvisible(true); this.txtcoefficientmultiplicateur.addthemevariants(textfieldvariant.lumo_align_center); this.txtcoefficientmultiplicateur.setlocale(locale.french); this.txtcoefficientmultiplicateur.withnullvalueallowed(false); this.cbocodetranche.setwidth(350, unit.pixels); this.cbocodetranche.addclassname(combobox_left_label); this.cbocodetranche.setitemlabelgenerator(tranchevaleur::getlibelletranche); this.cbocodetranche.setrequired(true); this.cbocodetranche.setrequiredindicatorvisible(true); this.cbocodetranche.setclearbuttonvisible(true); this.cbocodetranche.setallowcustomvalue(true); this.cbocodetranche.setpreventinvalidinput(true); this.cbocodetranche.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la tranche de valeur choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodetranche.setvalue(event.getoldvalue()); } } }); this.cbocodetranche.addcustomvaluesetlistener(event -> { this.cbocodetranche_notinlist(event.getdetail(), 50); }); this.cbocodevariablerubrique.setwidth(350, unit.pixels); this.cbocodevariablerubrique.addclassname(combobox_left_label); this.cbocodevariablerubrique.setitemlabelgenerator(variableservice::getlibellevariable); this.cbocodevariablerubrique.setrequired(true); this.cbocodevariablerubrique.setrequiredindicatorvisible(true); this.cbocodevariablerubrique.setclearbuttonvisible(true); this.cbocodevariablerubrique.setallowcustomvalue(true); this.cbocodevariablerubrique.setpreventinvalidinput(true); this.cbocodevariablerubrique.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la variable choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodevariablerubrique.setvalue(event.getoldvalue()); } } }); this.cbocodevariablerubrique.addcustomvaluesetlistener(event -> { this.cbocodevariablerubrique_notinlist(event.getdetail(), 50); }); this.cbocodeconstanterubrique.setwidth(350, unit.pixels); this.cbocodeconstanterubrique.addclassname(combobox_left_label); this.cbocodeconstanterubrique.setitemlabelgenerator(emploifonds::getlibelleconstante); this.cbocodeconstanterubrique.setrequired(true); this.cbocodeconstanterubrique.setrequiredindicatorvisible(true); this.cbocodeconstanterubrique.setclearbuttonvisible(true); this.cbocodeconstanterubrique.setallowcustomvalue(true); this.cbocodeconstanterubrique.setpreventinvalidinput(true); this.cbocodeconstanterubrique.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la emploifonds choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodeconstanterubrique.setvalue(event.getoldvalue()); } } }); this.cbocodeconstanterubrique.addcustomvaluesetlistener(event -> { this.cbocodeconstanterubrique_notinlist(event.getdetail(), 50); }); this.cbocodevariablebase.setwidth(350, unit.pixels); this.cbocodevariablebase.addclassname(combobox_left_label); this.cbocodevariablebase.setitemlabelgenerator(variableservice::getlibellevariable); this.cbocodevariablebase.setrequired(true); this.cbocodevariablebase.setrequiredindicatorvisible(true); this.cbocodevariablebase.setclearbuttonvisible(true); this.cbocodevariablebase.setallowcustomvalue(true); this.cbocodevariablebase.setpreventinvalidinput(true); this.cbocodevariablebase.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la variable choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodevariablebase.setvalue(event.getoldvalue()); } } }); this.cbocodevariablebase.addcustomvaluesetlistener(event -> { this.cbocodevariablebase_notinlist(event.getdetail(), 50); }); this.cbocodeconstantebase.setwidth(350, unit.pixels); this.cbocodeconstantebase.addclassname(combobox_left_label); this.cbocodeconstantebase.setitemlabelgenerator(emploifonds::getlibelleconstante); this.cbocodeconstantebase.setrequired(true); this.cbocodeconstantebase.setrequiredindicatorvisible(true); this.cbocodeconstantebase.setclearbuttonvisible(true); this.cbocodeconstantebase.setallowcustomvalue(true); this.cbocodeconstantebase.setpreventinvalidinput(true); this.cbocodeconstantebase.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la emploifonds choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodeconstantebase.setvalue(event.getoldvalue()); } } }); this.cbocodeconstantebase.addcustomvaluesetlistener(event -> { this.cbocodeconstantebase_notinlist(event.getdetail(), 50); }); this.cbocodevariabletaux.setwidth(350, unit.pixels); this.cbocodevariabletaux.addclassname(combobox_left_label); this.cbocodevariabletaux.setitemlabelgenerator(variableservice::getlibellevariable); this.cbocodevariabletaux.setrequired(true); this.cbocodevariabletaux.setrequiredindicatorvisible(true); this.cbocodevariabletaux.setclearbuttonvisible(true); this.cbocodevariabletaux.setallowcustomvalue(true); this.cbocodevariabletaux.setpreventinvalidinput(true); this.cbocodevariabletaux.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la variable choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodevariabletaux.setvalue(event.getoldvalue()); } } }); this.cbocodevariabletaux.addcustomvaluesetlistener(event -> { this.cbocodevariabletaux_notinlist(event.getdetail(), 50); }); this.cbocodeconstantetaux.setwidth(350, unit.pixels); this.cbocodeconstantetaux.addclassname(combobox_left_label); this.cbocodeconstantetaux.setitemlabelgenerator(emploifonds::getlibelleconstante); this.cbocodeconstantetaux.setrequired(true); this.cbocodeconstantetaux.setrequiredindicatorvisible(true); this.cbocodeconstantetaux.setclearbuttonvisible(true); this.cbocodeconstantetaux.setallowcustomvalue(true); this.cbocodeconstantetaux.setpreventinvalidinput(true); this.cbocodeconstantetaux.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la emploifonds choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodeconstantetaux.setvalue(event.getoldvalue()); } } }); this.cbocodeconstantetaux.addcustomvaluesetlistener(event -> { this.cbocodeconstantetaux_notinlist(event.getdetail(), 50); }); this.cbocodevaleurminimum.setwidth(350, unit.pixels); this.cbocodevaleurminimum.addclassname(combobox_left_label); this.cbocodevaleurminimum.setitemlabelgenerator(systemevaleurminmax::getlibellevaleur); this.cbocodevaleurminimum.setrequired(true); this.cbocodevaleurminimum.setrequiredindicatorvisible(true); this.cbocodevaleurminimum.setclearbuttonvisible(true); this.cbocodevaleurminimum.setallowcustomvalue(false); this.cbocodevaleurminimum.setpreventinvalidinput(true); this.txtvaleurminimumfixe.setwidth(100, unit.pixels); this.txtvaleurminimumfixe.setrequiredindicatorvisible(true); this.txtvaleurminimumfixe.addthemevariants(textfieldvariant.lumo_align_center); this.txtvaleurminimumfixe.setlocale(locale.french); this.txtvaleurminimumfixe.withnullvalueallowed(false); this.cbocodevaleurmaximum.setwidth(350, unit.pixels); this.cbocodevaleurmaximum.addclassname(combobox_left_label); this.cbocodevaleurmaximum.setitemlabelgenerator(systemevaleurminmax::getlibellevaleur); this.cbocodevaleurmaximum.setrequired(true); this.cbocodevaleurmaximum.setrequiredindicatorvisible(true); this.cbocodevaleurmaximum.setclearbuttonvisible(true); this.cbocodevaleurmaximum.setallowcustomvalue(false); this.cbocodevaleurmaximum.setpreventinvalidinput(true); this.txtvaleurmaximumfixe.setwidth(100, unit.pixels); this.txtvaleurmaximumfixe.setrequiredindicatorvisible(true); this.txtvaleurmaximumfixe.addthemevariants(textfieldvariant.lumo_align_center); this.txtvaleurmaximumfixe.setlocale(locale.french); this.txtvaleurmaximumfixe.withnullvalueallowed(false); this.cbocodeconstantevaleurminimum.setwidth(350, unit.pixels); this.cbocodeconstantevaleurminimum.addclassname(combobox_left_label); this.cbocodeconstantevaleurminimum.setitemlabelgenerator(emploifonds::getlibelleconstante); this.cbocodeconstantevaleurminimum.setrequired(true); this.cbocodeconstantevaleurminimum.setrequiredindicatorvisible(true); this.cbocodeconstantevaleurminimum.setclearbuttonvisible(true); this.cbocodeconstantevaleurminimum.setallowcustomvalue(true); this.cbocodeconstantevaleurminimum.setpreventinvalidinput(true); this.cbocodeconstantevaleurminimum.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la emploifonds choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodeconstantevaleurminimum.setvalue(event.getoldvalue()); } } }); this.cbocodeconstantevaleurminimum.addcustomvaluesetlistener(event -> { this.cbocodeconstantevaleurminimum_notinlist(event.getdetail(), 50); }); this.cbocodeconstantevaleurmaximum.setwidth(350, unit.pixels); this.cbocodeconstantevaleurmaximum.addclassname(combobox_left_label); this.cbocodeconstantevaleurmaximum.setitemlabelgenerator(emploifonds::getlibelleconstante); this.cbocodeconstantevaleurmaximum.setrequired(true); this.cbocodeconstantevaleurmaximum.setrequiredindicatorvisible(true); this.cbocodeconstantevaleurmaximum.setclearbuttonvisible(true); this.cbocodeconstantevaleurmaximum.setallowcustomvalue(true); this.cbocodeconstantevaleurmaximum.setpreventinvalidinput(true); this.cbocodeconstantevaleurmaximum.addvaluechangelistener(event -> { if (event.getvalue() != null) { if (event.getvalue().isinactif() == true) { messagedialoghelper.showwarningdialog("erreur de saisie", "la emploifonds choisie est actuellement désactivée. veuillez en saisir une autre."); this.cbocodeconstantevaleurmaximum.setvalue(event.getoldvalue()); } } }); this.cbocodeconstantevaleurmaximum.addcustomvaluesetlistener(event -> { this.cbocodeconstantevaleurmaximum_notinlist(event.getdetail(), 50); }); this.cbocodemodeabattement.setwidth(350, unit.pixels); this.cbocodemodeabattement.addclassname(combobox_left_label); this.cbocodemodeabattement.setitemlabelgenerator(systememodeabattement::getlibellemodeabattement); this.cbocodemodeabattement.setrequired(true); this.cbocodemodeabattement.setrequiredindicatorvisible(true); this.cbocodemodeabattement.setclearbuttonvisible(true); this.cbocodemodeabattement.setallowcustomvalue(false); this.cbocodemodeabattement.setpreventinvalidinput(true); this.txtabattementfixe.setwidth(100, unit.pixels); this.txtabattementfixe.setrequiredindicatorvisible(true); this.txtabattementfixe.addthemevariants(textfieldvariant.lumo_align_center); this.txtabattementfixe.setlocale(locale.french); this.txtabattementfixe.withnullvalueallowed(false); this.cbocodemodearrondissement.setwidth(350, unit.pixels); this.cbocodemodearrondissement.addclassname(combobox_left_label); this.cbocodemodearrondissement.setitemlabelgenerator(systememodearrondissement::getlibellemodearrondissement); this.cbocodemodearrondissement.setrequired(true); this.cbocodemodearrondissement.setrequiredindicatorvisible(true); this.cbocodemodearrondissement.setclearbuttonvisible(true); this.cbocodemodearrondissement.setallowcustomvalue(false); this.cbocodemodearrondissement.setpreventinvalidinput(true); this.txtnombrechiffrearrondissement.setwidth(100, unit.pixels); this.txtnombrechiffrearrondissement.setrequiredindicatorvisible(true); this.txtnombrechiffrearrondissement.addthemevariants(textfieldvariant.lumo_align_center); this.txtnombrechiffrearrondissement.setlocale(locale.french); this.txtnombrechiffrearrondissement.withnullvalueallowed(false); this.cbocodemodestockagecompteurbase01.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurbase01.addclassname(combobox_left_label); this.cbocodemodestockagecompteurbase01.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurbase01.setrequired(true); this.cbocodemodestockagecompteurbase01.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurbase01.setclearbuttonvisible(true); this.cbocodemodestockagecompteurbase01.setallowcustomvalue(false); this.cbocodemodestockagecompteurbase01.setpreventinvalidinput(true); this.cbocodemodestockagecompteurbase02.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurbase02.addclassname(combobox_left_label); this.cbocodemodestockagecompteurbase02.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurbase02.setrequired(true); this.cbocodemodestockagecompteurbase02.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurbase02.setclearbuttonvisible(true); this.cbocodemodestockagecompteurbase02.setallowcustomvalue(false); this.cbocodemodestockagecompteurbase02.setpreventinvalidinput(true); this.cbocodemodestockagecompteurbase03.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurbase03.addclassname(combobox_left_label); this.cbocodemodestockagecompteurbase03.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurbase03.setrequired(true); this.cbocodemodestockagecompteurbase03.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurbase03.setclearbuttonvisible(true); this.cbocodemodestockagecompteurbase03.setallowcustomvalue(false); this.cbocodemodestockagecompteurbase03.setpreventinvalidinput(true); this.cbocodemodestockagecompteurbase04.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurbase04.addclassname(combobox_left_label); this.cbocodemodestockagecompteurbase04.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurbase04.setrequired(true); this.cbocodemodestockagecompteurbase04.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurbase04.setclearbuttonvisible(true); this.cbocodemodestockagecompteurbase04.setallowcustomvalue(false); this.cbocodemodestockagecompteurbase04.setpreventinvalidinput(true); this.cbocodemodestockagecompteurmontant01.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurmontant01.addclassname(combobox_left_label); this.cbocodemodestockagecompteurmontant01.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurmontant01.setrequired(true); this.cbocodemodestockagecompteurmontant01.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurmontant01.setclearbuttonvisible(true); this.cbocodemodestockagecompteurmontant01.setallowcustomvalue(false); this.cbocodemodestockagecompteurmontant01.setpreventinvalidinput(true); this.cbocodemodestockagecompteurmontant02.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurmontant02.addclassname(combobox_left_label); this.cbocodemodestockagecompteurmontant02.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurmontant02.setrequired(true); this.cbocodemodestockagecompteurmontant02.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurmontant02.setclearbuttonvisible(true); this.cbocodemodestockagecompteurmontant02.setallowcustomvalue(false); this.cbocodemodestockagecompteurmontant02.setpreventinvalidinput(true); this.cbocodemodestockagecompteurmontant03.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurmontant03.addclassname(combobox_left_label); this.cbocodemodestockagecompteurmontant03.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurmontant03.setrequired(true); this.cbocodemodestockagecompteurmontant03.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurmontant03.setclearbuttonvisible(true); this.cbocodemodestockagecompteurmontant03.setallowcustomvalue(false); this.cbocodemodestockagecompteurmontant03.setpreventinvalidinput(true); this.cbocodemodestockagecompteurmontant04.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurmontant04.addclassname(combobox_left_label); this.cbocodemodestockagecompteurmontant04.setitemlabelgenerator(systememodestockagebasemontant::getlibellemodestockage); this.cbocodemodestockagecompteurmontant04.setrequired(true); this.cbocodemodestockagecompteurmontant04.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurmontant04.setclearbuttonvisible(true); this.cbocodemodestockagecompteurmontant04.setallowcustomvalue(false); this.cbocodemodestockagecompteurmontant04.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne01.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne01.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne01.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne01.setrequired(true); this.cbocodemodestockagecompteurinterne01.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne01.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne01.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne01.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne02.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne02.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne02.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne02.setrequired(true); this.cbocodemodestockagecompteurinterne02.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne02.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne02.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne02.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne03.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne03.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne03.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne03.setrequired(true); this.cbocodemodestockagecompteurinterne03.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne03.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne03.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne03.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne04.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne04.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne04.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne04.setrequired(true); this.cbocodemodestockagecompteurinterne04.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne04.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne04.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne04.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne05.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne05.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne05.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne05.setrequired(true); this.cbocodemodestockagecompteurinterne05.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne05.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne05.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne05.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne06.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne06.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne06.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne06.setrequired(true); this.cbocodemodestockagecompteurinterne06.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne06.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne06.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne06.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne07.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne07.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne07.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne07.setrequired(true); this.cbocodemodestockagecompteurinterne07.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne07.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne07.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne07.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne08.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne08.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne08.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne08.setrequired(true); this.cbocodemodestockagecompteurinterne08.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne08.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne08.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne08.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne09.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne09.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne09.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne09.setrequired(true); this.cbocodemodestockagecompteurinterne09.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne09.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne09.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne09.setpreventinvalidinput(true); this.cbocodemodestockagecompteurinterne10.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurinterne10.addclassname(combobox_left_label); this.cbocodemodestockagecompteurinterne10.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurinterne10.setrequired(true); this.cbocodemodestockagecompteurinterne10.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurinterne10.setclearbuttonvisible(true); this.cbocodemodestockagecompteurinterne10.setallowcustomvalue(false); this.cbocodemodestockagecompteurinterne10.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne01.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne01.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne01.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne01.setrequired(true); this.cbocodemodestockagecompteurexterne01.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne01.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne01.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne01.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne02.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne02.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne02.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne02.setrequired(true); this.cbocodemodestockagecompteurexterne02.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne02.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne02.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne02.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne03.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne03.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne03.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne03.setrequired(true); this.cbocodemodestockagecompteurexterne03.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne03.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne03.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne03.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne04.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne04.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne04.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne04.setrequired(true); this.cbocodemodestockagecompteurexterne04.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne04.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne04.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne04.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne05.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne05.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne05.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne05.setrequired(true); this.cbocodemodestockagecompteurexterne05.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne05.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne05.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne05.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne06.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne06.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne06.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne06.setrequired(true); this.cbocodemodestockagecompteurexterne06.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne06.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne06.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne06.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne07.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne07.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne07.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne07.setrequired(true); this.cbocodemodestockagecompteurexterne07.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne07.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne07.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne07.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne08.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne08.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne08.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne08.setrequired(true); this.cbocodemodestockagecompteurexterne08.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne08.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne08.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne08.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne09.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne09.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne09.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne09.setrequired(true); this.cbocodemodestockagecompteurexterne09.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne09.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne09.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne09.setpreventinvalidinput(true); this.cbocodemodestockagecompteurexterne10.setwidth(350, unit.pixels); this.cbocodemodestockagecompteurexterne10.addclassname(combobox_left_label); this.cbocodemodestockagecompteurexterne10.setitemlabelgenerator(systememodestockageinterneexterne::getlibellemodestockage); this.cbocodemodestockagecompteurexterne10.setrequired(true); this.cbocodemodestockagecompteurexterne10.setrequiredindicatorvisible(true); this.cbocodemodestockagecompteurexterne10.setclearbuttonvisible(true); this.cbocodemodestockagecompteurexterne10.setallowcustomvalue(false); this.cbocodemodestockagecompteurexterne10.setpreventinvalidinput(true); label lblnorubriquevalidationstatus = new label(); this.binder.forfield(this.txtnorubrique) .asrequired("la saisie du n° rubrique est obligatoire. veuillez saisir le n° rubrique.") .withvalidator(text -> text != null && text.length() <= 10, "n° rubrique ne peut contenir au plus 10 caractères") .withvalidationstatushandler(status -> {lblnorubriquevalidationstatus.settext(status.getmessage().orelse("")); lblnorubriquevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getnorubrique, rubrique::setnorubrique); label lbllibellerubriquevalidationstatus = new label(); this.binder.forfield(this.txtlibellerubrique) .asrequired("la saisie du libellé de la rubrique est obligatoire. veuillez saisir le libellé de la rubrique.") .withvalidator(text -> text.length() <= 50, "libellé rubrique ne peut contenir au plus 50 caractères.") .withvalidationstatushandler(status -> {lbllibellerubriquevalidationstatus.settext(status.getmessage().orelse("")); lbllibellerubriquevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getlibellerubrique, rubrique::setlibellerubrique); label lbllibellecourtrubriquevalidationstatus = new label(); this.binder.forfield(this.txtlibellecourtrubrique) .asrequired("la saisie du libellé abrégé de la rubrique est obligatoire. veuillez saisir le libellé de la rubrique.") .withvalidator(text -> text.length() <= 30, "libellé abrégé rubrique ne peut contenir au plus 30 caractères.") .withvalidationstatushandler(status -> {lbllibellecourtrubriquevalidationstatus.settext(status.getmessage().orelse("")); lbllibellecourtrubriquevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getlibellecourtrubrique, rubrique::setlibellecourtrubrique); this.binder.forfield(this.chkinactif) .bind(rubrique::isinactif, rubrique::setinactif); this.binder.forfield(this.chkeditionfacture) .bind(rubrique::iseditionfacture, rubrique::seteditionfacture); this.binder.forfield(this.chkeditionsynthetique) .bind(rubrique::iseditionsynthetique, rubrique::seteditionsynthetique); label lblmodevalorisationrubriquevalidationstatus = new label(); this.binder.forfield(this.cbocodemodevalorisationrubrique) .asrequired("la saisie du mode de valorisation de la rubrique est requise. veuillez sélectionner un mode de valorisation de la rubrique") .bind(rubrique::getmodevalorisationrubrique, rubrique::setmodevalorisationrubrique); label lblmontantfixevalidationstatus = new label(); this.binder.forfield(this.txtmontantfixe) .withvalidationstatushandler(status -> {lblmontantfixevalidationstatus.settext(status.getmessage().orelse("")); lblmontantfixevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getmontantfixe, rubrique::setmontantfixe); label lblmodevalorisationbasevalidationstatus = new label(); this.binder.forfield(this.cbocodemodevalorisationbase) .bind(rubrique::getmodevalorisationbase, rubrique::setmodevalorisationbase); label lblbasefixevalidationstatus = new label(); this.binder.forfield(this.txtbasefixe) .withvalidationstatushandler(status -> {lblbasefixevalidationstatus.settext(status.getmessage().orelse("")); lblbasefixevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getbasefixe, rubrique::setbasefixe); label lblmodevalorisationtauxvalidationstatus = new label(); this.binder.forfield(this.cbocodemodevalorisationtaux) .bind(rubrique::getmodevalorisationtaux, rubrique::setmodevalorisationtaux); label lbltauxfixevalidationstatus = new label(); this.binder.forfield(this.txttauxfixe) .withvalidationstatushandler(status -> {lbltauxfixevalidationstatus.settext(status.getmessage().orelse("")); lbltauxfixevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::gettauxfixe, rubrique::settauxfixe); label lblcoefficientmultiplicateurvalidationstatus = new label(); this.binder.forfield(this.txtcoefficientmultiplicateur) .asrequired("la saisie du coefficient multiplicateur est obligatoire. veuillez saisir le coefficient multiplicateur.") .withvalidationstatushandler(status -> {lblcoefficientmultiplicateurvalidationstatus.settext(status.getmessage().orelse("")); lblcoefficientmultiplicateurvalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getcoefficientmultiplicateur, rubrique::setcoefficientmultiplicateur); label lbltranchevaleurvalidationstatus = new label(); this.binder.forfield(this.cbocodetranche) .bind(rubrique::gettranche, rubrique::settranche); label lblvariablerubriquevalidationstatus = new label(); this.binder.forfield(this.cbocodevariablerubrique) .bind(rubrique::getvariablerubrique, rubrique::setvariablerubrique); label lblconstanterubriquevalidationstatus = new label(); this.binder.forfield(this.cbocodeconstanterubrique) .bind(rubrique::getconstanterubrique, rubrique::setconstanterubrique); label lblvariablebasevalidationstatus = new label(); this.binder.forfield(this.cbocodevariablebase) .bind(rubrique::getvariablebase, rubrique::setvariablebase); label lblconstantebasevalidationstatus = new label(); this.binder.forfield(this.cbocodeconstantebase) .bind(rubrique::getconstantebase, rubrique::setconstantebase); label lblvariabletauxvalidationstatus = new label(); this.binder.forfield(this.cbocodevariabletaux) .bind(rubrique::getvariabletaux, rubrique::setvariabletaux); label lblconstantetauxvalidationstatus = new label(); this.binder.forfield(this.cbocodeconstantetaux) .bind(rubrique::getconstantetaux, rubrique::setconstantetaux); label lblvaleurminimumvalidationstatus = new label(); this.binder.forfield(this.cbocodevaleurminimum) .bind(rubrique::getvaleurminimum, rubrique::setvaleurminimum); label lblvaleurminimumfixevalidationstatus = new label(); this.binder.forfield(this.txtvaleurminimumfixe) .withvalidationstatushandler(status -> {lblvaleurminimumfixevalidationstatus.settext(status.getmessage().orelse("")); lblvaleurminimumfixevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getvaleurminimumfixe, rubrique::setvaleurminimumfixe); label lblvaleurmaximumvalidationstatus = new label(); this.binder.forfield(this.cbocodevaleurmaximum) .bind(rubrique::getvaleurmaximum, rubrique::setvaleurmaximum); label lblvaleurmaximumfixevalidationstatus = new label(); this.binder.forfield(this.txtvaleurmaximumfixe) .withvalidationstatushandler(status -> {lblvaleurmaximumfixevalidationstatus.settext(status.getmessage().orelse("")); lblvaleurmaximumfixevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getvaleurmaximumfixe, rubrique::setvaleurmaximumfixe); label lblconstantevaleurminimumvalidationstatus = new label(); this.binder.forfield(this.cbocodeconstantevaleurminimum) .bind(rubrique::getconstantevaleurminimum, rubrique::setconstantevaleurminimum); label lblconstantevaleurmaximumvalidationstatus = new label(); this.binder.forfield(this.cbocodeconstantevaleurmaximum) .bind(rubrique::getconstantevaleurmaximum, rubrique::setconstantevaleurmaximum); label lblmodeabattementvalidationstatus = new label(); this.binder.forfield(this.cbocodemodeabattement) .bind(rubrique::getmodeabattement, rubrique::setmodeabattement); label lblabattementfixevalidationstatus = new label(); this.binder.forfield(this.txtabattementfixe) .withvalidationstatushandler(status -> {lblabattementfixevalidationstatus.settext(status.getmessage().orelse("")); lblabattementfixevalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getabattementfixe, rubrique::setabattementfixe); label lblmodearrondissementvalidationstatus = new label(); this.binder.forfield(this.cbocodemodearrondissement) .bind(rubrique::getmodearrondissement, rubrique::setmodearrondissement); label lblnombrechiffrearrondissementvalidationstatus = new label(); this.binder.forfield(this.txtnombrechiffrearrondissement) .withvalidationstatushandler(status -> {lblnombrechiffrearrondissementvalidationstatus.settext(status.getmessage().orelse("")); lblnombrechiffrearrondissementvalidationstatus.setvisible(status.iserror());}) .bind(rubrique::getnombrechiffrearrondissement, rubrique::setnombrechiffrearrondissement); label lblmodestockagecompteurbase01validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurbase01) .bind(rubrique::getmodestockagecompteurbase01, rubrique::setmodestockagecompteurbase01); label lblmodestockagecompteurbase02validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurbase02) .bind(rubrique::getmodestockagecompteurbase02, rubrique::setmodestockagecompteurbase02); label lblmodestockagecompteurbase03validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurbase03) .bind(rubrique::getmodestockagecompteurbase03, rubrique::setmodestockagecompteurbase03); label lblmodestockagecompteurbase04validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurbase04) .bind(rubrique::getmodestockagecompteurbase04, rubrique::setmodestockagecompteurbase04); label lblmodestockagecompteurmontant01validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurmontant01) .bind(rubrique::getmodestockagecompteurmontant01, rubrique::setmodestockagecompteurmontant01); label lblmodestockagecompteurmontant02validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurmontant02) .bind(rubrique::getmodestockagecompteurmontant02, rubrique::setmodestockagecompteurmontant02); label lblmodestockagecompteurmontant03validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurmontant03) .bind(rubrique::getmodestockagecompteurmontant03, rubrique::setmodestockagecompteurmontant03); label lblmodestockagecompteurmontant04validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurmontant04) .bind(rubrique::getmodestockagecompteurmontant04, rubrique::setmodestockagecompteurmontant04); label lblmodestockagecompteurinterne01validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne01) .bind(rubrique::getmodestockagecompteurinterne01, rubrique::setmodestockagecompteurinterne01); label lblmodestockagecompteurinterne02validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne02) .bind(rubrique::getmodestockagecompteurinterne02, rubrique::setmodestockagecompteurinterne02); label lblmodestockagecompteurinterne03validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne03) .bind(rubrique::getmodestockagecompteurinterne03, rubrique::setmodestockagecompteurinterne03); label lblmodestockagecompteurinterne04validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne04) .bind(rubrique::getmodestockagecompteurinterne04, rubrique::setmodestockagecompteurinterne04); label lblmodestockagecompteurinterne05validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne05) .bind(rubrique::getmodestockagecompteurinterne05, rubrique::setmodestockagecompteurinterne05); label lblmodestockagecompteurinterne06validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne06) .bind(rubrique::getmodestockagecompteurinterne06, rubrique::setmodestockagecompteurinterne06); label lblmodestockagecompteurinterne07validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne07) .bind(rubrique::getmodestockagecompteurinterne07, rubrique::setmodestockagecompteurinterne07); label lblmodestockagecompteurinterne08validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne08) .bind(rubrique::getmodestockagecompteurinterne08, rubrique::setmodestockagecompteurinterne08); label lblmodestockagecompteurinterne09validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne09) .bind(rubrique::getmodestockagecompteurinterne09, rubrique::setmodestockagecompteurinterne09); label lblmodestockagecompteurinterne10validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurinterne10) .bind(rubrique::getmodestockagecompteurinterne10, rubrique::setmodestockagecompteurinterne10); label lblmodestockagecompteurexterne01validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne01) .bind(rubrique::getmodestockagecompteurexterne01, rubrique::setmodestockagecompteurexterne01); label lblmodestockagecompteurexterne02validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne02) .bind(rubrique::getmodestockagecompteurexterne02, rubrique::setmodestockagecompteurexterne02); label lblmodestockagecompteurexterne03validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne03) .bind(rubrique::getmodestockagecompteurexterne03, rubrique::setmodestockagecompteurexterne03); label lblmodestockagecompteurexterne04validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne04) .bind(rubrique::getmodestockagecompteurexterne04, rubrique::setmodestockagecompteurexterne04); label lblmodestockagecompteurexterne05validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne05) .bind(rubrique::getmodestockagecompteurexterne05, rubrique::setmodestockagecompteurexterne05); label lblmodestockagecompteurexterne06validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne06) .bind(rubrique::getmodestockagecompteurexterne06, rubrique::setmodestockagecompteurexterne06); label lblmodestockagecompteurexterne07validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne07) .bind(rubrique::getmodestockagecompteurexterne07, rubrique::setmodestockagecompteurexterne07); label lblmodestockagecompteurexterne08validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne08) .bind(rubrique::getmodestockagecompteurexterne08, rubrique::setmodestockagecompteurexterne08); label lblmodestockagecompteurexterne09validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne09) .bind(rubrique::getmodestockagecompteurexterne09, rubrique::setmodestockagecompteurexterne09); label lblmodestockagecompteurexterne10validationstatus = new label(); this.binder.forfield(this.cbocodemodestockagecompteurexterne10) .bind(rubrique::getmodestockagecompteurexterne10, rubrique::setmodestockagecompteurexterne10); this.tabinfogeneraleformlayout.addformitem(this.txtnorubrique, "n° rubrique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabinfogeneraleformlayout.addformitem(this.txtlibellerubrique, "libellé rubrique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabinfogeneraleformlayout.addformitem(this.txtlibellecourtrubrique, "libellé abrégé rubrique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabinfogeneraleformlayout.addformitem(this.chkinactif, "inactif :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabinfogeneraleformlayout.addformitem(this.chkeditionfacture, "edition facture :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabinfogeneraleformlayout.addformitem(this.chkeditionsynthetique, "edition synthétique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodemodevalorisationrubrique, "mode valorisation rubrique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.txtmontantfixe, "montant fixe :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodemodevalorisationbase, "mode détermination base :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.txtbasefixe, "basefixe :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodemodevalorisationtaux, "mode détermination taux :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.txttauxfixe, "taux fixe :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.txtcoefficientmultiplicateur, "coefficient multiplicateur :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodetranche, "tranche :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodevariablerubrique, "variable rubrique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodeconstanterubrique, "emploifonds rubrique :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodevariablebase, "variable base :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodeconstantebase, "emploifonds base :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodevariabletaux, "variable taux :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabdefinitionformlayout.addformitem(this.cbocodeconstantetaux, "emploifonds taux :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.cbocodevaleurminimum, "valeur minimum :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.txtvaleurminimumfixe, "valeur minimum fixe :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.cbocodevaleurmaximum, "titre civilité :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.txtvaleurmaximumfixe, "valeur maximum fixe :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.cbocodeconstantevaleurminimum, "emploifonds valeur minimum :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.cbocodeconstantevaleurmaximum, "emploifonds valeur maximum :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.cbocodemodeabattement, "mode abattement :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.txtabattementfixe, "abattement fixe :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.cbocodemodearrondissement, "mode arrondissement :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabajustementformlayout.addformitem(this.txtnombrechiffrearrondissement, "nombre chiffre arrondissement :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurbase01, "compteur base 01 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurbase02, "compteur base 02 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurbase03, "compteur base 03 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurbase04, "compteur base 04 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurmontant01, "compteur montant 01 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurmontant02, "compteur montant 02 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurmontant03, "compteur montant 03 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurbasemontantformlayout.addformitem(this.cbocodemodestockagecompteurmontant04, "compteur montant 04 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne01, "compteur interne 01 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne02, "compteur interne 02 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne03, "compteur interne 03 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne04, "compteur interne 04 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne05, "compteur interne 05 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne06, "compteur interne 06 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne07, "compteur interne 07 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne08, "compteur interne 08 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne09, "compteur interne 09 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurinterneformlayout.addformitem(this.cbocodemodestockagecompteurinterne10, "compteur interne 10 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne01, "compteur externe 01 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne02, "compteur externe 02 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne03, "compteur externe 03 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne04, "compteur externe 04 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne05, "compteur externe 05 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne06, "compteur externe 06 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne07, "compteur externe 07 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne08, "compteur externe 08 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne09, "compteur externe 09 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); this.tabcompteurexterneformlayout.addformitem(this.cbocodemodestockagecompteurexterne10, "compteur externe 10 :").getstyle().set("--vaadin-form-item-label-width", form_item_label_width200); tabinfogeneraleformlayout.setresponsivesteps(new formlayout.responsivestep("0", 1, formlayout.responsivestep.labelsposition.top), new formlayout.responsivestep(panel_flex_basis, 2, formlayout.responsivestep.labelsposition.aside)); tabdefinitionformlayout.setresponsivesteps(new formlayout.responsivestep("0", 1, formlayout.responsivestep.labelsposition.top), new formlayout.responsivestep(panel_flex_basis, 2, formlayout.responsivestep.labelsposition.aside)); tabajustementformlayout.setresponsivesteps(new formlayout.responsivestep("0", 1, formlayout.responsivestep.labelsposition.top), new formlayout.responsivestep(panel_flex_basis, 2, formlayout.responsivestep.labelsposition.aside)); this.tabcompteurbasemontantformlayout.setresponsivesteps(new formlayout.responsivestep("0", 1, formlayout.responsivestep.labelsposition.top), new formlayout.responsivestep(panel_flex_basis, 2, formlayout.responsivestep.labelsposition.aside)); this.tabcompteurinterneformlayout.setresponsivesteps(new formlayout.responsivestep("0", 1, formlayout.responsivestep.labelsposition.top), new formlayout.responsivestep(panel_flex_basis, 2, formlayout.responsivestep.labelsposition.aside)); this.tabcompteurexterneformlayout.setresponsivesteps(new formlayout.responsivestep("0", 1, formlayout.responsivestep.labelsposition.top), new formlayout.responsivestep(panel_flex_basis, 2, formlayout.responsivestep.labelsposition.aside)); this.tabstopages.put(this.tabinfogenerale, this.tabinfogeneraleformlayout); this.tabstopages.put(this.tabdefinition, this.tabdefinitionformlayout); this.tabstopages.put(this.tabajustement, this.tabajustementformlayout); this.tabstopages.put(this.tabcompteurbasemontant, this.tabcompteurbasemontantformlayout); this.tabstopages.put(this.tabcompteurinterne, this.tabcompteurinterneformlayout); this.tabstopages.put(this.tabcompteurexterne, this.tabcompteurexterneformlayout); this.tabs.add(this.tabinfogenerale, this.tabdefinition, this.tabajustement, this.tabcompteurbasemontant, this.tabcompteurinterne, this.tabcompteurexterne); this.pages.add(this.tabinfogeneraleformlayout, this.tabdefinitionformlayout, this.tabajustementformlayout, this.tabcompteurbasemontantformlayout, this.tabcompteurinterneformlayout, this.tabcompteurexterneformlayout); this.tabs.addselectedchangelistener(event -> { vaadinsession.getcurrent().setattribute(cached_selected_tab_index, this.tabs.getselectedindex()); this.showselectedtab(); }); if (vaadinsession.getcurrent().getattribute(cached_selected_tab_index) == null) { vaadinsession.getcurrent().setattribute(cached_selected_tab_index, 0); } this.tabs.setselectedindex((int)vaadinsession.getcurrent().getattribute(cached_selected_tab_index)); this.showselectedtab(); } catch (exception e) { messagedialoghelper.showalertdialog("editerrubriquedialog.configurecomponents", e.tostring()); e.printstacktrace(); } }
jdissou/sigdep01_01
[ 1, 0, 0, 0 ]
15,434
@JsonGetter("name") public String getName ( ) { return this.name; }
@JsonGetter("name") public String getName ( ) { return this.name; }
@jsongetter("name") public string getname ( ) { return this.name; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,435
@JsonSetter("name") public void setName (String value) { this.name = value; }
@JsonSetter("name") public void setName (String value) { this.name = value; }
@jsonsetter("name") public void setname (string value) { this.name = value; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,436
@JsonGetter("product_details") public ProductData getProductDetails ( ) { return this.productDetails; }
@JsonGetter("product_details") public ProductData getProductDetails ( ) { return this.productDetails; }
@jsongetter("product_details") public productdata getproductdetails ( ) { return this.productdetails; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,437
@JsonSetter("product_details") public void setProductDetails (ProductData value) { this.productDetails = value; }
@JsonSetter("product_details") public void setProductDetails (ProductData value) { this.productDetails = value; }
@jsonsetter("product_details") public void setproductdetails (productdata value) { this.productdetails = value; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,438
@JsonGetter("product_id") public Integer getProductId ( ) { return this.productId; }
@JsonGetter("product_id") public Integer getProductId ( ) { return this.productId; }
@jsongetter("product_id") public integer getproductid ( ) { return this.productid; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,439
@JsonSetter("product_id") public void setProductId (Integer value) { this.productId = value; }
@JsonSetter("product_id") public void setProductId (Integer value) { this.productId = value; }
@jsonsetter("product_id") public void setproductid (integer value) { this.productid = value; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,440
@JsonGetter("product_identifiers") public ProductIdentifiers getProductIdentifiers ( ) { return this.productIdentifiers; }
@JsonGetter("product_identifiers") public ProductIdentifiers getProductIdentifiers ( ) { return this.productIdentifiers; }
@jsongetter("product_identifiers") public productidentifiers getproductidentifiers ( ) { return this.productidentifiers; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,441
@JsonSetter("product_identifiers") public void setProductIdentifiers (ProductIdentifiers value) { this.productIdentifiers = value; }
@JsonSetter("product_identifiers") public void setProductIdentifiers (ProductIdentifiers value) { this.productIdentifiers = value; }
@jsonsetter("product_identifiers") public void setproductidentifiers (productidentifiers value) { this.productidentifiers = value; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,442
@JsonGetter("product_timestamps") public ProductTimestamps getProductTimestamps ( ) { return this.productTimestamps; }
@JsonGetter("product_timestamps") public ProductTimestamps getProductTimestamps ( ) { return this.productTimestamps; }
@jsongetter("product_timestamps") public producttimestamps getproducttimestamps ( ) { return this.producttimestamps; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,443
@JsonSetter("product_timestamps") public void setProductTimestamps (ProductTimestamps value) { this.productTimestamps = value; }
@JsonSetter("product_timestamps") public void setProductTimestamps (ProductTimestamps value) { this.productTimestamps = value; }
@jsonsetter("product_timestamps") public void setproducttimestamps (producttimestamps value) { this.producttimestamps = value; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,444
@JsonGetter("purchase_history") public List<PurchaseInfo> getPurchaseHistory ( ) { return this.purchaseHistory; }
@JsonGetter("purchase_history") public List<PurchaseInfo> getPurchaseHistory ( ) { return this.purchaseHistory; }
@jsongetter("purchase_history") public list<purchaseinfo> getpurchasehistory ( ) { return this.purchasehistory; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
15,445
@JsonSetter("purchase_history") public void setPurchaseHistory (List<PurchaseInfo> value) { this.purchaseHistory = value; }
@JsonSetter("purchase_history") public void setPurchaseHistory (List<PurchaseInfo> value) { this.purchaseHistory = value; }
@jsonsetter("purchase_history") public void setpurchasehistory (list<purchaseinfo> value) { this.purchasehistory = value; }
information-machine/information-machine-api-android
[ 0, 0, 0, 0 ]
23,670
public Configs getConfigs() { Configs configs = null; InputStream is = settingsFacade.getRawConfig(SMS_CONFIGS_FILE_NAME); String errorMessage = null; if (is == null) { throw new JsonIOException(SMS_CONFIGS_FILE_NAME + " missing"); } try { String jsonText = IOUtils.toString(is); Gson gson = new Gson(); configs = gson.fromJson(jsonText, Configs.class); } catch (Exception e) { errorMessage = "Might you have a malformed " + SMS_CONFIGS_FILE_NAME + " file? " + e.toString(); } finally { try { is.close(); } catch (IOException e) { // Ignore IO exception, what are we going to do anyway? logger.error("IOException when closing config file {}: {}", SMS_CONFIGS_FILE_NAME, e); } } if (errorMessage != null) { throw new JsonIOException(errorMessage); } return configs; }
public Configs getConfigs() { Configs configs = null; InputStream is = settingsFacade.getRawConfig(SMS_CONFIGS_FILE_NAME); String errorMessage = null; if (is == null) { throw new JsonIOException(SMS_CONFIGS_FILE_NAME + " missing"); } try { String jsonText = IOUtils.toString(is); Gson gson = new Gson(); configs = gson.fromJson(jsonText, Configs.class); } catch (Exception e) { errorMessage = "Might you have a malformed " + SMS_CONFIGS_FILE_NAME + " file? " + e.toString(); } finally { try { is.close(); } catch (IOException e) { logger.error("IOException when closing config file {}: {}", SMS_CONFIGS_FILE_NAME, e); } } if (errorMessage != null) { throw new JsonIOException(errorMessage); } return configs; }
public configs getconfigs() { configs configs = null; inputstream is = settingsfacade.getrawconfig(sms_configs_file_name); string errormessage = null; if (is == null) { throw new jsonioexception(sms_configs_file_name + " missing"); } try { string jsontext = ioutils.tostring(is); gson gson = new gson(); configs = gson.fromjson(jsontext, configs.class); } catch (exception e) { errormessage = "might you have a malformed " + sms_configs_file_name + " file? " + e.tostring(); } finally { try { is.close(); } catch (ioexception e) { logger.error("ioexception when closing config file {}: {}", sms_configs_file_name, e); } } if (errormessage != null) { throw new jsonioexception(errormessage); } return configs; }
jkondrat/modules
[ 1, 0, 0, 0 ]
15,511
@Override public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { // we don't need the plainSocket if (autoClose) plainSocket.close(); // create and connect SSL socket, but don't do hostname/certificate verification yet. final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0); sslSocketFactory.setTrustManagers(this.trustManager); final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port); // Protocols... final List<String> protocols = new ArrayList<String>(); for (final String protocol : sock.getSupportedProtocols()) { if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol); } sock.setEnabledProtocols(protocols.toArray(new String[0])); // Ciphers... final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS); ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites())); ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); // All all already enabled ones for compatibility. sock.setEnabledCipherSuites(ciphers.toArray(new String[0])); // set up SNI before the handshake. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { sslSocketFactory.setHostname(sock, host); } else { // This hack seems to work on my 4.0.4 tablet. try { final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(sock, host); } catch (final Exception e) { LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e)); } } // verify hostname and certificate. final SSLSession session = sock.getSession(); if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite()); return sock; }
@Override public Socket createSocket (final Socket plainSocket, final String host, final int port, final boolean autoClose) throws IOException, UnknownHostException { if (autoClose) plainSocket.close(); final SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0); sslSocketFactory.setTrustManagers(this.trustManager); final SSLSocket sock = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port); final List<String> protocols = new ArrayList<String>(); for (final String protocol : sock.getSupportedProtocols()) { if (!protocol.toUpperCase(Locale.ENGLISH).contains("SSL")) protocols.add(protocol); } sock.setEnabledProtocols(protocols.toArray(new String[0])); final HashSet<String> ciphers = new HashSet<String>(ALLOWED_CIPHERS); ciphers.retainAll(Arrays.asList(sock.getSupportedCipherSuites())); ciphers.addAll(new HashSet<String>(Arrays.asList(sock.getEnabledCipherSuites()))); sock.setEnabledCipherSuites(ciphers.toArray(new String[0])); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { sslSocketFactory.setHostname(sock, host); } else { try { final java.lang.reflect.Method setHostnameMethod = sock.getClass().getMethod("setHostname", String.class); setHostnameMethod.invoke(sock, host); } catch (final Exception e) { LOG.w("SNI not useable: %s", ExcpetionHelper.causeTrace(e)); } } final SSLSession session = sock.getSession(); if (!HOSTNAME_VERIFIER.verify(host, session)) throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host); LOG.i("Connected %s %s %s.", session.getPeerHost(), session.getProtocol(), session.getCipherSuite()); return sock; }
@override public socket createsocket (final socket plainsocket, final string host, final int port, final boolean autoclose) throws ioexception, unknownhostexception { if (autoclose) plainsocket.close(); final sslcertificatesocketfactory sslsocketfactory = (sslcertificatesocketfactory) sslcertificatesocketfactory.getdefault(0); sslsocketfactory.settrustmanagers(this.trustmanager); final sslsocket sock = (sslsocket) sslsocketfactory.createsocket(inetaddress.getbyname(host), port); final list<string> protocols = new arraylist<string>(); for (final string protocol : sock.getsupportedprotocols()) { if (!protocol.touppercase(locale.english).contains("ssl")) protocols.add(protocol); } sock.setenabledprotocols(protocols.toarray(new string[0])); final hashset<string> ciphers = new hashset<string>(allowed_ciphers); ciphers.retainall(arrays.aslist(sock.getsupportedciphersuites())); ciphers.addall(new hashset<string>(arrays.aslist(sock.getenabledciphersuites()))); sock.setenabledciphersuites(ciphers.toarray(new string[0])); if (build.version.sdk_int >= build.version_codes.jelly_bean_mr1) { sslsocketfactory.sethostname(sock, host); } else { try { final java.lang.reflect.method sethostnamemethod = sock.getclass().getmethod("sethostname", string.class); sethostnamemethod.invoke(sock, host); } catch (final exception e) { log.w("sni not useable: %s", excpetionhelper.causetrace(e)); } } final sslsession session = sock.getsession(); if (!hostname_verifier.verify(host, session)) throw new sslpeerunverifiedexception("cannot verify hostname: " + host); log.i("connected %s %s %s.", session.getpeerhost(), session.getprotocol(), session.getciphersuite()); return sock; }
haku/Onosendai
[ 1, 0, 0, 0 ]
23,703
@Test public void providerCannotBeUsedIfNotAssigned() throws IOException, InterruptedException { setupWorkspace("user_defined_providers"); EventCollector collector = new EventCollector(EnumSet.allOf(EventKind.class)); parser = createParser(collector); // TODO(T48080142): When we wrap up all of these validation errors into something human // friendly, this will become a build file error thrown.expect(Exception.class); thrown.expectMessage("//not_assigned:defs.bzl referenced from //not_assigned:BUCK"); parser.getManifest(ForwardRelPath.of("not_assigned/BUCK")); }
@Test public void providerCannotBeUsedIfNotAssigned() throws IOException, InterruptedException { setupWorkspace("user_defined_providers"); EventCollector collector = new EventCollector(EnumSet.allOf(EventKind.class)); parser = createParser(collector); thrown.expect(Exception.class); thrown.expectMessage("//not_assigned:defs.bzl referenced from //not_assigned:BUCK"); parser.getManifest(ForwardRelPath.of("not_assigned/BUCK")); }
@test public void providercannotbeusedifnotassigned() throws ioexception, interruptedexception { setupworkspace("user_defined_providers"); eventcollector collector = new eventcollector(enumset.allof(eventkind.class)); parser = createparser(collector); thrown.expect(exception.class); thrown.expectmessage("//not_assigned:defs.bzl referenced from //not_assigned:buck"); parser.getmanifest(forwardrelpath.of("not_assigned/buck")); }
jasonnam/buck
[ 0, 0, 1, 0 ]
15,556
@Test public void testDeleteBuildDefinition() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); BuildDefinition buildDefinition = project.getBuildDefinitions().get( 1 ); project.getBuildDefinitions().remove( 0 ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check size is now 1", 1, project.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = project.getBuildDefinitions().get( 0 ); assertBuildDefinitionEquals( buildDefinition, retrievedBuildDefinition ); assertScheduleEquals( testSchedule2, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile2, retrievedBuildDefinition.getProfile() ); // !! These actually aren't happening !! // TODO: test the def was physically deleted // TODO: test the schedule/profile was NOT physically deleted }
@Test public void testDeleteBuildDefinition() throws ContinuumStoreException { Project project = projectDao.getProjectWithAllDetails( testProject1.getId() ); BuildDefinition buildDefinition = project.getBuildDefinitions().get( 1 ); project.getBuildDefinitions().remove( 0 ); projectDao.updateProject( project ); project = projectDao.getProjectWithAllDetails( testProject1.getId() ); assertEquals( "check size is now 1", 1, project.getBuildDefinitions().size() ); BuildDefinition retrievedBuildDefinition = project.getBuildDefinitions().get( 0 ); assertBuildDefinitionEquals( buildDefinition, retrievedBuildDefinition ); assertScheduleEquals( testSchedule2, retrievedBuildDefinition.getSchedule() ); assertProfileEquals( testProfile2, retrievedBuildDefinition.getProfile() ); }
@test public void testdeletebuilddefinition() throws continuumstoreexception { project project = projectdao.getprojectwithalldetails( testproject1.getid() ); builddefinition builddefinition = project.getbuilddefinitions().get( 1 ); project.getbuilddefinitions().remove( 0 ); projectdao.updateproject( project ); project = projectdao.getprojectwithalldetails( testproject1.getid() ); assertequals( "check size is now 1", 1, project.getbuilddefinitions().size() ); builddefinition retrievedbuilddefinition = project.getbuilddefinitions().get( 0 ); assertbuilddefinitionequals( builddefinition, retrievedbuilddefinition ); assertscheduleequals( testschedule2, retrievedbuilddefinition.getschedule() ); assertprofileequals( testprofile2, retrievedbuilddefinition.getprofile() ); }
isabella232/continuum
[ 0, 0, 0, 1 ]
15,558
@Test public void testDeleteGroupBuildDefinition() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); projectGroup.getBuildDefinitions().remove( 0 ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check size is now 0", 0, projectGroup.getBuildDefinitions().size() ); // !! These actually aren't happening !! // TODO: test the def was physically deleted // TODO: test the schedule/profile was NOT physically deleted }
@Test public void testDeleteGroupBuildDefinition() throws ContinuumStoreException { ProjectGroup projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); projectGroup.getBuildDefinitions().remove( 0 ); projectGroupDao.updateProjectGroup( projectGroup ); projectGroup = projectGroupDao.getProjectGroupWithBuildDetailsByProjectGroupId( defaultProjectGroup.getId() ); assertEquals( "check size is now 0", 0, projectGroup.getBuildDefinitions().size() ); }
@test public void testdeletegroupbuilddefinition() throws continuumstoreexception { projectgroup projectgroup = projectgroupdao.getprojectgroupwithbuilddetailsbyprojectgroupid( defaultprojectgroup.getid() ); projectgroup.getbuilddefinitions().remove( 0 ); projectgroupdao.updateprojectgroup( projectgroup ); projectgroup = projectgroupdao.getprojectgroupwithbuilddetailsbyprojectgroupid( defaultprojectgroup.getid() ); assertequals( "check size is now 0", 0, projectgroup.getbuilddefinitions().size() ); }
isabella232/continuum
[ 0, 0, 0, 1 ]
32,006
@Override public void handleEvent(Event event) { List<Entity> entities = entityManager.getEntitiesContainingComponent(VisionComponent.class); if (entities == null) return; EntityCreatedEvent entityCreatedEvent = (EntityCreatedEvent) event; for (Entity entity : entities) { VisionComponent visionComponent = (VisionComponent) entityManager.getComponentInEntity(entity, VisionComponent.class); visionComponent.createEntity(entityCreatedEvent.getEntity()); System.out.println("EntityEvent: " + entityCreatedEvent.getEntity()); } }
@Override public void handleEvent(Event event) { List<Entity> entities = entityManager.getEntitiesContainingComponent(VisionComponent.class); if (entities == null) return; EntityCreatedEvent entityCreatedEvent = (EntityCreatedEvent) event; for (Entity entity : entities) { VisionComponent visionComponent = (VisionComponent) entityManager.getComponentInEntity(entity, VisionComponent.class); visionComponent.createEntity(entityCreatedEvent.getEntity()); System.out.println("EntityEvent: " + entityCreatedEvent.getEntity()); } }
@override public void handleevent(event event) { list<entity> entities = entitymanager.getentitiescontainingcomponent(visioncomponent.class); if (entities == null) return; entitycreatedevent entitycreatedevent = (entitycreatedevent) event; for (entity entity : entities) { visioncomponent visioncomponent = (visioncomponent) entitymanager.getcomponentinentity(entity, visioncomponent.class); visioncomponent.createentity(entitycreatedevent.getentity()); system.out.println("entityevent: " + entitycreatedevent.getentity()); } }
haxic/Heavy-Space
[ 1, 0, 0, 0 ]
23,877
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO: Manage sizes to avoid specific ones. It always must be parent size (match_parent) int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); mWidth.set(widthSize); mHeight.set(heightSize); mQuadrangle.set(0, 0, widthSize, heightSize); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); mWidth.set(widthSize); mHeight.set(heightSize); mQuadrangle.set(0, 0, widthSize, heightSize); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }
@override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { int widthsize = measurespec.getsize(widthmeasurespec); int heightsize = measurespec.getsize(heightmeasurespec); mwidth.set(widthsize); mheight.set(heightsize); mquadrangle.set(0, 0, widthsize, heightsize); super.onmeasure(widthmeasurespec, heightmeasurespec); }
gemalto/idcloud-kyc-sample-android
[ 0, 1, 0, 0 ]
7,781
public static void main(String args[]) throws FileNotFoundException { // TODO: use sane arg parsing if (args.length != 7 && args.length != 8) { throw new RuntimeException("usage: Processor trace-file tcg-dump-out inst-info-dump hierarchy-dump test-case-name test-method-name tested-class [output-package]"); } String traceFileName = args[0]; String tcgDump = args[1]; String iiDump = args[2]; String hierDump = args[3]; String testCaseName = args[4]; String testMethodName = args[5]; ClassName testedClass = ClassName.fromDotted(args[6]); String outputPackage = args.length == 8 ? args[7] : testedClass.dottedPackageName(); Hierarchy hierarchy = Hierarchy.createFromFile(hierDump); TestCaseGenerator tcg = new TestCaseGenerator(testCaseName, outputPackage); TestMethodGenerator tmg = new TestMethodGenerator(testMethodName, hierarchy, true); tcg.addChunk(tmg); InputStream in = new FileInputStream(traceFileName); Deserializer<TraceEvent> d = Deserializer.getDeserializer(in, TraceEvent.class); Map<Instance, InstanceInfo> iis = readInstanceInfos(iiDump); Processor p = new Processor(tmg, testedClass, iis, hierarchy); d.process(p); PrintStream ps = new PrintStream(tcgDump); Serializer<TestCaseGenerator> s = Serializer.getSerializer(ps); s.write(tcg); s.close(); }
public static void main(String args[]) throws FileNotFoundException { if (args.length != 7 && args.length != 8) { throw new RuntimeException("usage: Processor trace-file tcg-dump-out inst-info-dump hierarchy-dump test-case-name test-method-name tested-class [output-package]"); } String traceFileName = args[0]; String tcgDump = args[1]; String iiDump = args[2]; String hierDump = args[3]; String testCaseName = args[4]; String testMethodName = args[5]; ClassName testedClass = ClassName.fromDotted(args[6]); String outputPackage = args.length == 8 ? args[7] : testedClass.dottedPackageName(); Hierarchy hierarchy = Hierarchy.createFromFile(hierDump); TestCaseGenerator tcg = new TestCaseGenerator(testCaseName, outputPackage); TestMethodGenerator tmg = new TestMethodGenerator(testMethodName, hierarchy, true); tcg.addChunk(tmg); InputStream in = new FileInputStream(traceFileName); Deserializer<TraceEvent> d = Deserializer.getDeserializer(in, TraceEvent.class); Map<Instance, InstanceInfo> iis = readInstanceInfos(iiDump); Processor p = new Processor(tmg, testedClass, iis, hierarchy); d.process(p); PrintStream ps = new PrintStream(tcgDump); Serializer<TestCaseGenerator> s = Serializer.getSerializer(ps); s.write(tcg); s.close(); }
public static void main(string args[]) throws filenotfoundexception { if (args.length != 7 && args.length != 8) { throw new runtimeexception("usage: processor trace-file tcg-dump-out inst-info-dump hierarchy-dump test-case-name test-method-name tested-class [output-package]"); } string tracefilename = args[0]; string tcgdump = args[1]; string iidump = args[2]; string hierdump = args[3]; string testcasename = args[4]; string testmethodname = args[5]; classname testedclass = classname.fromdotted(args[6]); string outputpackage = args.length == 8 ? args[7] : testedclass.dottedpackagename(); hierarchy hierarchy = hierarchy.createfromfile(hierdump); testcasegenerator tcg = new testcasegenerator(testcasename, outputpackage); testmethodgenerator tmg = new testmethodgenerator(testmethodname, hierarchy, true); tcg.addchunk(tmg); inputstream in = new fileinputstream(tracefilename); deserializer<traceevent> d = deserializer.getdeserializer(in, traceevent.class); map<instance, instanceinfo> iis = readinstanceinfos(iidump); processor p = new processor(tmg, testedclass, iis, hierarchy); d.process(p); printstream ps = new printstream(tcgdump); serializer<testcasegenerator> s = serializer.getserializer(ps); s.write(tcg); s.close(); }
glasser/amock
[ 1, 0, 0, 0 ]
7,812
@Override public void run(double frac) { logger.trace("run -> begin of method"); try { workingDataset = new GranularityAggregationTree(sourceDataset.getDataColumnSchema(),granularities.length+1); ArrayList<TemporalObject> currentBranches = new ArrayList<TemporalObject>(); ArrayList<ArrayList<TemporalObject>> currentLeaves = new ArrayList<ArrayList<TemporalObject>>(); for(TemporalObject iO : sourceDataset.temporalObjects()) { long inf = iO.getTemporalElement().asGeneric().getGranule().getInf(); int i = 0; for(TemporalObject iB : currentBranches) { if (iB.getTemporalElement().asGeneric().getGranule().contains(inf)) { currentLeaves.get(i).add(iO); break; } i++; } if(i >= currentBranches.size()) { Granule newGranule = new Granule(inf,inf,granularities[0]); Instant newTe = workingDataset.addInstant(newGranule); currentBranches.add(workingDataset.addTemporalObject(newTe)); ArrayList<TemporalObject> leaves = new ArrayList<TemporalObject>(); leaves.add(iO); currentLeaves.add(leaves); } } long[] roots = new long[currentBranches.size()]; for(int i=0; i<currentBranches.size(); i++) roots[i] = currentBranches.get(i).getId(); if (granularities.length > 1) { for(int i=1; i<granularities.length;i++) { ArrayList<ArrayList<TemporalObject>> futureLeaves = new ArrayList<ArrayList<TemporalObject>>(); ArrayList<TemporalObject> futureBranches = new ArrayList<TemporalObject>(); int whichChild = 0; for(int k=0; k<currentLeaves.size();k++) { ArrayList<TemporalObject> iCurrentLeaves = currentLeaves.get(k); while(iCurrentLeaves.size() > 0) { TemporalObject currentLeave = iCurrentLeaves.get(0); iCurrentLeaves.remove(0); TemporalObject targetBranch = null; long inf = currentLeave.getTemporalElement().asGeneric().getInf(); long sup = currentLeave.getTemporalElement().asGeneric().getSup(); whichChild = 0; for(int l=0; l<k; l++) whichChild += currentBranches.get(l).getChildCount(); for(TemporalObject potentialBranch : currentBranches.get(k).childObjects()) { if (potentialBranch.getTemporalElement().asGeneric().getGranule().contains(inf)) { targetBranch = potentialBranch; break; } whichChild++; } if (targetBranch == null) { Granule newGranule = new Granule(inf,sup,granularities[i]); Instant newTe = workingDataset.addInstant(newGranule); targetBranch = workingDataset.addTemporalObject(newTe); futureBranches.add(targetBranch); futureLeaves.add(new ArrayList<TemporalObject>()); whichChild = futureLeaves.size() - 1; currentBranches.get(k).linkWithChild(targetBranch); } futureLeaves.get(whichChild).add(currentLeave); } } if(i==granularities.length-1) { for(int j=0; j<futureBranches.size(); j++ ) { aggregate(futureBranches.get(j),futureLeaves.get(j),granularities.length-1); } } else { currentBranches = futureBranches; currentLeaves = futureLeaves; } } for(long iRoot : roots) aggregate(workingDataset.getTemporalObject(iRoot),0); } else { for(int i=0; i<roots.length; i++) aggregate(workingDataset.getTemporalObject(roots[i]),currentLeaves.get(i),0); } // TODO this could be cleaned for (long rootId : roots) { workingDataset.getTemporalObject(rootId).setRoot(true); } } catch (TemporalDataException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }
@Override public void run(double frac) { logger.trace("run -> begin of method"); try { workingDataset = new GranularityAggregationTree(sourceDataset.getDataColumnSchema(),granularities.length+1); ArrayList<TemporalObject> currentBranches = new ArrayList<TemporalObject>(); ArrayList<ArrayList<TemporalObject>> currentLeaves = new ArrayList<ArrayList<TemporalObject>>(); for(TemporalObject iO : sourceDataset.temporalObjects()) { long inf = iO.getTemporalElement().asGeneric().getGranule().getInf(); int i = 0; for(TemporalObject iB : currentBranches) { if (iB.getTemporalElement().asGeneric().getGranule().contains(inf)) { currentLeaves.get(i).add(iO); break; } i++; } if(i >= currentBranches.size()) { Granule newGranule = new Granule(inf,inf,granularities[0]); Instant newTe = workingDataset.addInstant(newGranule); currentBranches.add(workingDataset.addTemporalObject(newTe)); ArrayList<TemporalObject> leaves = new ArrayList<TemporalObject>(); leaves.add(iO); currentLeaves.add(leaves); } } long[] roots = new long[currentBranches.size()]; for(int i=0; i<currentBranches.size(); i++) roots[i] = currentBranches.get(i).getId(); if (granularities.length > 1) { for(int i=1; i<granularities.length;i++) { ArrayList<ArrayList<TemporalObject>> futureLeaves = new ArrayList<ArrayList<TemporalObject>>(); ArrayList<TemporalObject> futureBranches = new ArrayList<TemporalObject>(); int whichChild = 0; for(int k=0; k<currentLeaves.size();k++) { ArrayList<TemporalObject> iCurrentLeaves = currentLeaves.get(k); while(iCurrentLeaves.size() > 0) { TemporalObject currentLeave = iCurrentLeaves.get(0); iCurrentLeaves.remove(0); TemporalObject targetBranch = null; long inf = currentLeave.getTemporalElement().asGeneric().getInf(); long sup = currentLeave.getTemporalElement().asGeneric().getSup(); whichChild = 0; for(int l=0; l<k; l++) whichChild += currentBranches.get(l).getChildCount(); for(TemporalObject potentialBranch : currentBranches.get(k).childObjects()) { if (potentialBranch.getTemporalElement().asGeneric().getGranule().contains(inf)) { targetBranch = potentialBranch; break; } whichChild++; } if (targetBranch == null) { Granule newGranule = new Granule(inf,sup,granularities[i]); Instant newTe = workingDataset.addInstant(newGranule); targetBranch = workingDataset.addTemporalObject(newTe); futureBranches.add(targetBranch); futureLeaves.add(new ArrayList<TemporalObject>()); whichChild = futureLeaves.size() - 1; currentBranches.get(k).linkWithChild(targetBranch); } futureLeaves.get(whichChild).add(currentLeave); } } if(i==granularities.length-1) { for(int j=0; j<futureBranches.size(); j++ ) { aggregate(futureBranches.get(j),futureLeaves.get(j),granularities.length-1); } } else { currentBranches = futureBranches; currentLeaves = futureLeaves; } } for(long iRoot : roots) aggregate(workingDataset.getTemporalObject(iRoot),0); } else { for(int i=0; i<roots.length; i++) aggregate(workingDataset.getTemporalObject(roots[i]),currentLeaves.get(i),0); } for (long rootId : roots) { workingDataset.getTemporalObject(rootId).setRoot(true); } } catch (TemporalDataException e1) { e1.printStackTrace(); } }
@override public void run(double frac) { logger.trace("run -> begin of method"); try { workingdataset = new granularityaggregationtree(sourcedataset.getdatacolumnschema(),granularities.length+1); arraylist<temporalobject> currentbranches = new arraylist<temporalobject>(); arraylist<arraylist<temporalobject>> currentleaves = new arraylist<arraylist<temporalobject>>(); for(temporalobject io : sourcedataset.temporalobjects()) { long inf = io.gettemporalelement().asgeneric().getgranule().getinf(); int i = 0; for(temporalobject ib : currentbranches) { if (ib.gettemporalelement().asgeneric().getgranule().contains(inf)) { currentleaves.get(i).add(io); break; } i++; } if(i >= currentbranches.size()) { granule newgranule = new granule(inf,inf,granularities[0]); instant newte = workingdataset.addinstant(newgranule); currentbranches.add(workingdataset.addtemporalobject(newte)); arraylist<temporalobject> leaves = new arraylist<temporalobject>(); leaves.add(io); currentleaves.add(leaves); } } long[] roots = new long[currentbranches.size()]; for(int i=0; i<currentbranches.size(); i++) roots[i] = currentbranches.get(i).getid(); if (granularities.length > 1) { for(int i=1; i<granularities.length;i++) { arraylist<arraylist<temporalobject>> futureleaves = new arraylist<arraylist<temporalobject>>(); arraylist<temporalobject> futurebranches = new arraylist<temporalobject>(); int whichchild = 0; for(int k=0; k<currentleaves.size();k++) { arraylist<temporalobject> icurrentleaves = currentleaves.get(k); while(icurrentleaves.size() > 0) { temporalobject currentleave = icurrentleaves.get(0); icurrentleaves.remove(0); temporalobject targetbranch = null; long inf = currentleave.gettemporalelement().asgeneric().getinf(); long sup = currentleave.gettemporalelement().asgeneric().getsup(); whichchild = 0; for(int l=0; l<k; l++) whichchild += currentbranches.get(l).getchildcount(); for(temporalobject potentialbranch : currentbranches.get(k).childobjects()) { if (potentialbranch.gettemporalelement().asgeneric().getgranule().contains(inf)) { targetbranch = potentialbranch; break; } whichchild++; } if (targetbranch == null) { granule newgranule = new granule(inf,sup,granularities[i]); instant newte = workingdataset.addinstant(newgranule); targetbranch = workingdataset.addtemporalobject(newte); futurebranches.add(targetbranch); futureleaves.add(new arraylist<temporalobject>()); whichchild = futureleaves.size() - 1; currentbranches.get(k).linkwithchild(targetbranch); } futureleaves.get(whichchild).add(currentleave); } } if(i==granularities.length-1) { for(int j=0; j<futurebranches.size(); j++ ) { aggregate(futurebranches.get(j),futureleaves.get(j),granularities.length-1); } } else { currentbranches = futurebranches; currentleaves = futureleaves; } } for(long iroot : roots) aggregate(workingdataset.gettemporalobject(iroot),0); } else { for(int i=0; i<roots.length; i++) aggregate(workingdataset.gettemporalobject(roots[i]),currentleaves.get(i),0); } for (long rootid : roots) { workingdataset.gettemporalobject(rootid).setroot(true); } } catch (temporaldataexception e1) { e1.printstacktrace(); } }
ieg-vienna/TimeBench
[ 1, 0, 0, 0 ]
7,861
@Override @SuppressFBWarnings("BC_UNCONFIRMED_CAST") protected void runApiSpecificTests(HttpSecurityDescription securityDescription) throws SuiteBroken { this.currentState.selectedHeiId = getParameterValue(HEI_ID_PARAMETER, this::getSelectedHeiId); }
@Override @SuppressFBWarnings("BC_UNCONFIRMED_CAST") protected void runApiSpecificTests(HttpSecurityDescription securityDescription) throws SuiteBroken { this.currentState.selectedHeiId = getParameterValue(HEI_ID_PARAMETER, this::getSelectedHeiId); }
@override @suppressfbwarnings("bc_unconfirmed_cast") protected void runapispecifictests(httpsecuritydescription securitydescription) throws suitebroken { this.currentstate.selectedheiid = getparametervalue(hei_id_parameter, this::getselectedheiid); }
j-be/ewp-registry-service
[ 1, 0, 0, 0 ]
7,912
private BeanDescriptorImpl<T> getBeanDescriptorInternal() { return new BeanDescriptorImpl<T>( beanClass, getClassLevelConstraintsAsDescriptors(), getConstrainedPropertiesAsDescriptors(), getMethodsAsDescriptors(), defaultGroupSequenceIsRedefined(), getDefaultGroupSequence( null ) ); }
private BeanDescriptorImpl<T> getBeanDescriptorInternal() { return new BeanDescriptorImpl<T>( beanClass, getClassLevelConstraintsAsDescriptors(), getConstrainedPropertiesAsDescriptors(), getMethodsAsDescriptors(), defaultGroupSequenceIsRedefined(), getDefaultGroupSequence( null ) ); }
private beandescriptorimpl<t> getbeandescriptorinternal() { return new beandescriptorimpl<t>( beanclass, getclasslevelconstraintsasdescriptors(), getconstrainedpropertiesasdescriptors(), getmethodsasdescriptors(), defaultgroupsequenceisredefined(), getdefaultgroupsequence( null ) ); }
gastaldi/hibernate-validator
[ 0, 0, 0, 0 ]
8,028
public void webHookEvent(GerritProjectEvent projectEvent) { log.info("Got Webhook:" + projectEvent); // TODO Update open changes according to event. For now, just read them all scheduleRefresh(); }
public void webHookEvent(GerritProjectEvent projectEvent) { log.info("Got Webhook:" + projectEvent); scheduleRefresh(); }
public void webhookevent(gerritprojectevent projectevent) { log.info("got webhook:" + projectevent); schedulerefresh(); }
johannesc/gerrit-builder-plugin
[ 0, 1, 0, 0 ]
16,325
private void orderButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderButtonActionPerformed AddOrderForm orderForm = AddOrderForm.getInstance(); System.out.println(lowOnStock.get(stockTable.getSelectedColumn())); AdminMainForm admin = AdminMainForm.getInstance(); admin.showForm(orderForm); orderForm.setDrug(lowOnStock.get(stockTable.getSelectedRow())); //orderForm.setVisible(true);// TODO add your handling code here: }
private void orderButtonActionPerformed(java.awt.event.ActionEvent evt) { AddOrderForm orderForm = AddOrderForm.getInstance(); System.out.println(lowOnStock.get(stockTable.getSelectedColumn())); AdminMainForm admin = AdminMainForm.getInstance(); admin.showForm(orderForm); orderForm.setDrug(lowOnStock.get(stockTable.getSelectedRow())); }
private void orderbuttonactionperformed(java.awt.event.actionevent evt) { addorderform orderform = addorderform.getinstance(); system.out.println(lowonstock.get(stocktable.getselectedcolumn())); adminmainform admin = adminmainform.getinstance(); admin.showform(orderform); orderform.setdrug(lowonstock.get(stocktable.getselectedrow())); }
isurunix/pharmacy-manager
[ 0, 1, 0, 0 ]
22
public boolean usesRegs() { // FIXME: this is almost certainly boned. a Reg could appear in the // address expressions. for (int i=0;i<rhs().length;++i) { if (usesDirectly(i) && rhs()[i] instanceof Reg) { return true; } } if (opcode.form().implicitUses(head().code()).length!=0) { return true; } return false; }
public boolean usesRegs() { for (int i=0;i<rhs().length;++i) { if (usesDirectly(i) && rhs()[i] instanceof Reg) { return true; } } if (opcode.form().implicitUses(head().code()).length!=0) { return true; } return false; }
public boolean usesregs() { for (int i=0;i<rhs().length;++i) { if (usesdirectly(i) && rhs()[i] instanceof reg) { return true; } } if (opcode.form().implicituses(head().code()).length!=0) { return true; } return false; }
mihirlibran/cse605
[ 0, 0, 1, 0 ]
83
@Test public void parseNegativeIntegerLiteral( ) throws ExpressionException { LineSpecifier ls = new LineSpecifier(0, 10); Locale locale = new Locale(ls, 10); ExpressionParser parser = new ExpressionParser("-14458", locale); Expression exp = parser.parse(new Assembler.Builder().build()); assertEquals(2, exp._items.size()); ExpressionItem item0 = exp._items.get(0); assertTrue(item0 instanceof OperatorItem); // Operator op = ((OperatorItem) item0)._operator; // TODO check this value if we can, somehow ExpressionItem item1 = exp._items.get(1); assertTrue(item1 instanceof ValueItem); Value v1 = ((ValueItem)item1)._value; assertTrue(v1 instanceof IntegerValue); assertEquals(14458L, ((IntegerValue)v1)._value.get().longValue()); }
@Test public void parseNegativeIntegerLiteral( ) throws ExpressionException { LineSpecifier ls = new LineSpecifier(0, 10); Locale locale = new Locale(ls, 10); ExpressionParser parser = new ExpressionParser("-14458", locale); Expression exp = parser.parse(new Assembler.Builder().build()); assertEquals(2, exp._items.size()); ExpressionItem item0 = exp._items.get(0); assertTrue(item0 instanceof OperatorItem); ExpressionItem item1 = exp._items.get(1); assertTrue(item1 instanceof ValueItem); Value v1 = ((ValueItem)item1)._value; assertTrue(v1 instanceof IntegerValue); assertEquals(14458L, ((IntegerValue)v1)._value.get().longValue()); }
@test public void parsenegativeintegerliteral( ) throws expressionexception { linespecifier ls = new linespecifier(0, 10); locale locale = new locale(ls, 10); expressionparser parser = new expressionparser("-14458", locale); expression exp = parser.parse(new assembler.builder().build()); assertequals(2, exp._items.size()); expressionitem item0 = exp._items.get(0); asserttrue(item0 instanceof operatoritem); expressionitem item1 = exp._items.get(1); asserttrue(item1 instanceof valueitem); value v1 = ((valueitem)item1)._value; asserttrue(v1 instanceof integervalue); assertequals(14458l, ((integervalue)v1)._value.get().longvalue()); }
kduncan99/em2200-java
[ 1, 0, 0, 0 ]
118
@Override public void onLocationChanged(Location location) { mLocation = location; if (mLocation != null) { // Bug report: cached GeoPoint is being returned as the first value. // Wait for the 2nd value to be returned, which is hopefully not cached? ++mLocationCount; InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") lat: " + mLocation.getLatitude() + " long: " + mLocation.getLongitude() + " acc: " + mLocation.getAccuracy()); if (mLocationCount > 1) { mLocationDialog.setMessage(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateDouble(mLocation.getAccuracy()))); if (mLocation.getAccuracy() <= mLocationAccuracy) { returnLocation(); } } } else { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") null location"); } }
@Override public void onLocationChanged(Location location) { mLocation = location; if (mLocation != null) { ++mLocationCount; InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") lat: " + mLocation.getLatitude() + " long: " + mLocation.getLongitude() + " acc: " + mLocation.getAccuracy()); if (mLocationCount > 1) { mLocationDialog.setMessage(getString(R.string.location_provider_accuracy, mLocation.getProvider(), truncateDouble(mLocation.getAccuracy()))); if (mLocation.getAccuracy() <= mLocationAccuracy) { returnLocation(); } } } else { InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() + " onLocationChanged(" + mLocationCount + ") null location"); } }
@override public void onlocationchanged(location location) { mlocation = location; if (mlocation != null) { ++mlocationcount; infologger.geolog("geopointactivity: " + system.currenttimemillis() + " onlocationchanged(" + mlocationcount + ") lat: " + mlocation.getlatitude() + " long: " + mlocation.getlongitude() + " acc: " + mlocation.getaccuracy()); if (mlocationcount > 1) { mlocationdialog.setmessage(getstring(r.string.location_provider_accuracy, mlocation.getprovider(), truncatedouble(mlocation.getaccuracy()))); if (mlocation.getaccuracy() <= mlocationaccuracy) { returnlocation(); } } } else { infologger.geolog("geopointactivity: " + system.currenttimemillis() + " onlocationchanged(" + mlocationcount + ") null location"); } }
jorgepsendziuk/novo_coletor
[ 0, 0, 1, 0 ]
32,955
@Deprecated public FileDataSource generatePythonImpl(File spec, String artifactName, String groupId, String artifactVersion, String implemName) throws Exception { Yaml yaml = new Yaml(); LinkedHashMap swaggerFile = yaml.load(FileUtils.openInputStream(spec)); String groupIdApi = getPropInSwaggerFile(swaggerFile, "x-groupId"); String artifactNameApi = getPropInSwaggerFile(swaggerFile, "x-artifactName"); String artifactVersionApi = getPropInSwaggerFile(swaggerFile, "version"); String groupName = groupId.substring(groupId.lastIndexOf('.') + 1); StringBuilder artifactIdSb = new StringBuilder().append(groupName).append("-").append(artifactNameApi).append("-"); artifactIdSb.append(artifactName.replaceAll("-","")); CodegenConfigurator configurator = new CodegenConfigurator(); String artifactId = artifactIdSb.toString(); initializeConfigurator(spec, "KathraPython", artifactNameApi, groupIdApi, artifactVersion, "implem", artifactId, configurator); configurator.setArtifactVersionApi(artifactVersionApi); return getFileDataSource(spec, "implem", artifactIdSb, artifactId, configurator); }
@Deprecated public FileDataSource generatePythonImpl(File spec, String artifactName, String groupId, String artifactVersion, String implemName) throws Exception { Yaml yaml = new Yaml(); LinkedHashMap swaggerFile = yaml.load(FileUtils.openInputStream(spec)); String groupIdApi = getPropInSwaggerFile(swaggerFile, "x-groupId"); String artifactNameApi = getPropInSwaggerFile(swaggerFile, "x-artifactName"); String artifactVersionApi = getPropInSwaggerFile(swaggerFile, "version"); String groupName = groupId.substring(groupId.lastIndexOf('.') + 1); StringBuilder artifactIdSb = new StringBuilder().append(groupName).append("-").append(artifactNameApi).append("-"); artifactIdSb.append(artifactName.replaceAll("-","")); CodegenConfigurator configurator = new CodegenConfigurator(); String artifactId = artifactIdSb.toString(); initializeConfigurator(spec, "KathraPython", artifactNameApi, groupIdApi, artifactVersion, "implem", artifactId, configurator); configurator.setArtifactVersionApi(artifactVersionApi); return getFileDataSource(spec, "implem", artifactIdSb, artifactId, configurator); }
@deprecated public filedatasource generatepythonimpl(file spec, string artifactname, string groupid, string artifactversion, string implemname) throws exception { yaml yaml = new yaml(); linkedhashmap swaggerfile = yaml.load(fileutils.openinputstream(spec)); string groupidapi = getpropinswaggerfile(swaggerfile, "x-groupid"); string artifactnameapi = getpropinswaggerfile(swaggerfile, "x-artifactname"); string artifactversionapi = getpropinswaggerfile(swaggerfile, "version"); string groupname = groupid.substring(groupid.lastindexof('.') + 1); stringbuilder artifactidsb = new stringbuilder().append(groupname).append("-").append(artifactnameapi).append("-"); artifactidsb.append(artifactname.replaceall("-","")); codegenconfigurator configurator = new codegenconfigurator(); string artifactid = artifactidsb.tostring(); initializeconfigurator(spec, "kathrapython", artifactnameapi, groupidapi, artifactversion, "implem", artifactid, configurator); configurator.setartifactversionapi(artifactversionapi); return getfiledatasource(spec, "implem", artifactidsb, artifactid, configurator); }
kathra-project/kathra-codegen-swagger
[ 1, 0, 0, 0 ]
16,627
public void checkList() { if(observed.size() != cachedSize) { cachedSize = observed.size(); listUpdated(); } }
public void checkList() { if(observed.size() != cachedSize) { cachedSize = observed.size(); listUpdated(); } }
public void checklist() { if(observed.size() != cachedsize) { cachedsize = observed.size(); listupdated(); } }
justin-espedal/polydes
[ 0, 0, 1, 0 ]
16,754
@Override public boolean isReferenceTo(PsiElement psiElement) { if(!(psiElement instanceof PhpNamedElement)) { return false; } String text = getElement().getText(); if(StringUtils.isBlank(text)) { return false; } PsiElement namespace = element.getPrevSibling(); if(PhpPsiUtil.isOfType(namespace, PhpDocTokenTypes.DOC_NAMESPACE)) { // @TODO: namespace not supported return false; } String classByContext = PhpElementsUtil.getFqnForClassNameByContext(element, text); if(classByContext != null) { return StringUtils.stripStart(((PhpNamedElement) psiElement).getFQN(), "\\") .equalsIgnoreCase(StringUtils.stripStart(fqn, "\\")); } return false; }
@Override public boolean isReferenceTo(PsiElement psiElement) { if(!(psiElement instanceof PhpNamedElement)) { return false; } String text = getElement().getText(); if(StringUtils.isBlank(text)) { return false; } PsiElement namespace = element.getPrevSibling(); if(PhpPsiUtil.isOfType(namespace, PhpDocTokenTypes.DOC_NAMESPACE)) { return false; } String classByContext = PhpElementsUtil.getFqnForClassNameByContext(element, text); if(classByContext != null) { return StringUtils.stripStart(((PhpNamedElement) psiElement).getFQN(), "\\") .equalsIgnoreCase(StringUtils.stripStart(fqn, "\\")); } return false; }
@override public boolean isreferenceto(psielement psielement) { if(!(psielement instanceof phpnamedelement)) { return false; } string text = getelement().gettext(); if(stringutils.isblank(text)) { return false; } psielement namespace = element.getprevsibling(); if(phppsiutil.isoftype(namespace, phpdoctokentypes.doc_namespace)) { return false; } string classbycontext = phpelementsutil.getfqnforclassnamebycontext(element, text); if(classbycontext != null) { return stringutils.stripstart(((phpnamedelement) psielement).getfqn(), "\\") .equalsignorecase(stringutils.stripstart(fqn, "\\")); } return false; }
meyerbaptiste/idea-php-annotation-plugin
[ 0, 1, 0, 0 ]
16,808
public SyncStatusDetail synchronizeStack(Stack stack, UmsUsersState umsUsersState, UserSyncOptions options) { MDCBuilder.buildMdcContext(stack); String environmentCrn = stack.getEnvironmentCrn(); Multimap<String, String> warnings = ArrayListMultimap.create(); try { FreeIpaClient freeIpaClient = freeIpaClientFactory.getFreeIpaClientForStack(stack); UsersStateDifference usersStateDifferenceBeforeSync = compareUmsAndFreeIpa(umsUsersState, options, freeIpaClient); stateApplier.applyDifference(umsUsersState, environmentCrn, warnings, usersStateDifferenceBeforeSync, options, freeIpaClient); retrySyncIfBatchCallHasWarnings(stack, umsUsersState, warnings, options, freeIpaClient, usersStateDifferenceBeforeSync); if (options.isFullSync()) { // TODO For now we only sync cloud ids during full sync. We should eventually allow more granular syncs (actor level and group level sync). if (entitlementService.cloudIdentityMappingEnabled(stack.getAccountId())) { LOGGER.debug("Starting {} ...", SYNC_CLOUD_IDENTITIES); cloudIdentitySyncService.syncCloudIdentities(stack, umsUsersState, warnings::put); LOGGER.debug("Finished {}.", SYNC_CLOUD_IDENTITIES); } if (entitlementService.isEnvironmentPrivilegedUserEnabled(stack.getAccountId())) { LOGGER.debug("Starting {} ...", ADD_SUDO_RULES); try { sudoRuleService.setupSudoRule(stack, freeIpaClient); } catch (Exception e) { warnings.put(stack.getEnvironmentCrn(), e.getMessage()); LOGGER.error("{} failed for environment '{}'.", ADD_SUDO_RULES, stack.getEnvironmentCrn(), e); } LOGGER.debug("Finished {}.", ADD_SUDO_RULES); } } return toSyncStatusDetail(environmentCrn, warnings); } catch (TimeoutException e) { LOGGER.warn("Timed out while synchronizing environment {}", environmentCrn, e); return SyncStatusDetail.fail(environmentCrn, "Timed out", warnings); } catch (Exception e) { LOGGER.warn("Failed to synchronize environment {}", environmentCrn, e); return SyncStatusDetail.fail(environmentCrn, e.getLocalizedMessage(), warnings); } }
public SyncStatusDetail synchronizeStack(Stack stack, UmsUsersState umsUsersState, UserSyncOptions options) { MDCBuilder.buildMdcContext(stack); String environmentCrn = stack.getEnvironmentCrn(); Multimap<String, String> warnings = ArrayListMultimap.create(); try { FreeIpaClient freeIpaClient = freeIpaClientFactory.getFreeIpaClientForStack(stack); UsersStateDifference usersStateDifferenceBeforeSync = compareUmsAndFreeIpa(umsUsersState, options, freeIpaClient); stateApplier.applyDifference(umsUsersState, environmentCrn, warnings, usersStateDifferenceBeforeSync, options, freeIpaClient); retrySyncIfBatchCallHasWarnings(stack, umsUsersState, warnings, options, freeIpaClient, usersStateDifferenceBeforeSync); if (options.isFullSync()) { if (entitlementService.cloudIdentityMappingEnabled(stack.getAccountId())) { LOGGER.debug("Starting {} ...", SYNC_CLOUD_IDENTITIES); cloudIdentitySyncService.syncCloudIdentities(stack, umsUsersState, warnings::put); LOGGER.debug("Finished {}.", SYNC_CLOUD_IDENTITIES); } if (entitlementService.isEnvironmentPrivilegedUserEnabled(stack.getAccountId())) { LOGGER.debug("Starting {} ...", ADD_SUDO_RULES); try { sudoRuleService.setupSudoRule(stack, freeIpaClient); } catch (Exception e) { warnings.put(stack.getEnvironmentCrn(), e.getMessage()); LOGGER.error("{} failed for environment '{}'.", ADD_SUDO_RULES, stack.getEnvironmentCrn(), e); } LOGGER.debug("Finished {}.", ADD_SUDO_RULES); } } return toSyncStatusDetail(environmentCrn, warnings); } catch (TimeoutException e) { LOGGER.warn("Timed out while synchronizing environment {}", environmentCrn, e); return SyncStatusDetail.fail(environmentCrn, "Timed out", warnings); } catch (Exception e) { LOGGER.warn("Failed to synchronize environment {}", environmentCrn, e); return SyncStatusDetail.fail(environmentCrn, e.getLocalizedMessage(), warnings); } }
public syncstatusdetail synchronizestack(stack stack, umsusersstate umsusersstate, usersyncoptions options) { mdcbuilder.buildmdccontext(stack); string environmentcrn = stack.getenvironmentcrn(); multimap<string, string> warnings = arraylistmultimap.create(); try { freeipaclient freeipaclient = freeipaclientfactory.getfreeipaclientforstack(stack); usersstatedifference usersstatedifferencebeforesync = compareumsandfreeipa(umsusersstate, options, freeipaclient); stateapplier.applydifference(umsusersstate, environmentcrn, warnings, usersstatedifferencebeforesync, options, freeipaclient); retrysyncifbatchcallhaswarnings(stack, umsusersstate, warnings, options, freeipaclient, usersstatedifferencebeforesync); if (options.isfullsync()) { if (entitlementservice.cloudidentitymappingenabled(stack.getaccountid())) { logger.debug("starting {} ...", sync_cloud_identities); cloudidentitysyncservice.synccloudidentities(stack, umsusersstate, warnings::put); logger.debug("finished {}.", sync_cloud_identities); } if (entitlementservice.isenvironmentprivilegeduserenabled(stack.getaccountid())) { logger.debug("starting {} ...", add_sudo_rules); try { sudoruleservice.setupsudorule(stack, freeipaclient); } catch (exception e) { warnings.put(stack.getenvironmentcrn(), e.getmessage()); logger.error("{} failed for environment '{}'.", add_sudo_rules, stack.getenvironmentcrn(), e); } logger.debug("finished {}.", add_sudo_rules); } } return tosyncstatusdetail(environmentcrn, warnings); } catch (timeoutexception e) { logger.warn("timed out while synchronizing environment {}", environmentcrn, e); return syncstatusdetail.fail(environmentcrn, "timed out", warnings); } catch (exception e) { logger.warn("failed to synchronize environment {}", environmentcrn, e); return syncstatusdetail.fail(environmentcrn, e.getlocalizedmessage(), warnings); } }
mdvtlp/cloudbreak
[ 0, 1, 0, 0 ]
25,017
public static String obtainProcessID() { //get process id String pname = ManagementFactory.getRuntimeMXBean().getName(); //pid@hostname String pid = pname.split("@")[0]; // TODO: change this as soon as we switch to a java version >= 9 // import java.lang.ProcessHandle; // pid = ProcessHandle.current().pid(); return pid; }
public static String obtainProcessID() { String pname = ManagementFactory.getRuntimeMXBean().getName(); String pid = pname.split("@")[0]; return pid; }
public static string obtainprocessid() { string pname = managementfactory.getruntimemxbean().getname(); string pid = pname.split("@")[0]; return pid; }
mgd-hin/systemds
[ 1, 0, 0, 0 ]
16,892
public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); }
public static LeXeMerger build(String pathToMergeSchema) { if (builder == null) { builder = new GenericLexemeBuilder(); } return builder.build(pathToMergeSchema); }
public static lexemerger build(string pathtomergeschema) { if (builder == null) { builder = new genericlexemebuilder(); } return builder.build(pathtomergeschema); }
maybeec/lexeme
[ 0, 0, 0, 0 ]
16,946
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys() evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } File m = new File(controlFileName); String localName = m.getName() String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } return results; }
public static list<serviceresult> runxmlreplayfile(string xmlreplaybasedir, string controlfilename, string testgroupid, string onetestid, map<string, serviceresult> serviceresultsmap, boolean param_autodeleteposts, dump dump, string protohostportparam, authsmap defaultauths, list<string> reportslist, string reportsdir) throws exception { list<serviceresult> results = new arraylist<serviceresult>(); xmlreplayreport report = new xmlreplayreport(reportsdir); string controlfile = tools.glue(xmlreplaybasedir, "/", controlfilename); org.dom4j.document document; document = getdocument(controlfile); if (document==null){ throw new filenotfoundexception("xmlreplay control file ("+controlfilename+") not found in basedir: "+xmlreplaybasedir+" exiting test."); } string protohostport; if (tools.isempty(protohostportparam)){ protohostport = document.selectsinglenode("/xmlreplay/protohostport").gettext().trim(); system.out.println("deprecated: using protohostport ('"+protohostport+"') from xmlreplay file ('"+controlfile+"'), not master."); } else { protohostport = protohostportparam; } if (tools.isempty(protohostport)){ throw new exception("xmlreplay control file must have a protohostport element"); } string authsmapinfo; authsmap authsmap = readauths(document); if (authsmap.map.size()==0){ authsmap = defaultauths; authsmapinfo = "using defaultauths from master file: "+defaultauths; } else { authsmapinfo = "using authsmap from control file: "+authsmap; } report.addtestgroup(testgroupid, controlfilename); string xmlreplayheader = "========================================================================" +"\r\nxmlreplay running:" +"\r\n controlfile: "+ (new file(controlfile).getcanonicalpath()) +"\r\n protohostport: "+protohostport +"\r\n testgroup: "+testgroupid + (tools.notempty(onetestid) ? "\r\n onetestid: "+onetestid : "") +"\r\n authsmap: "+authsmapinfo +"\r\n param_autodeleteposts: "+param_autodeleteposts +"\r\n dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addruninfo(xmlreplayheader); system.out.println(xmlreplayheader); string autodeleteposts = ""; list<node> testgroupnodes; if (tools.notempty(testgroupid)){ testgroupnodes = document.selectnodes("//testgroup[@id='"+testgroupid+"']"); } else { testgroupnodes = document.selectnodes("//testgroup"); } jexlengine jexl = new jexlengine(); xmlreplayeval evalstruct = new xmlreplayeval(); evalstruct.serviceresultsmap = serviceresultsmap; evalstruct.jexl = jexl; for (node testgroup : testgroupnodes) { xmlreplayeval.mapcontextwkeys jc = new xmlreplayeval.mapcontextwkeys() evalstruct.jc = jc; autodeleteposts = testgroup.valueof("@autodeleteposts"); list<node> tests; if (tools.notempty(onetestid)){ tests = testgroup.selectnodes("test[@id='"+onetestid+"']"); } else { tests = testgroup.selectnodes("test"); } string authfortest = ""; int testelementindex = -1; for (node testnode : tests) { long starttime = system.currenttimemillis(); try { testelementindex++; string testid = testnode.valueof("@id"); boolean autodelete = param_autodeleteposts; string autodeletevalue = testnode.valueof("@autodeleteposts"); if (autodeletevalue != null && !autodeletevalue.trim().isempty()) { autodelete = boolean.valueof(autodeletevalue).booleanvalue(); } string testidlabel = tools.notempty(testid) ? (testgroupid+'.'+testid) : (testgroupid+'.'+testelementindex); string method = testnode.valueof("method"); string contenttype = testnode.valueof("contenttype"); string uri = testnode.valueof("uri"); string fullurl = tools.glue(protohostport, "/", uri); if (contenttype == null || contenttype.equals("")) { contenttype = xmlreplaytransport.application_xml; } string currentauthfortest = null; string authidfortest = testnode.valueof("@auth"); if (tools.notempty(authidfortest)){ currentauthfortest = authsmap.map.get(authidfortest); } else { string tokenauthexpression = testnode.valueof("@tokenauth"); if (tools.notempty(tokenauthexpression)){ currentauthfortest = "bearer " + evalstruct.eval(tokenauthexpression, serviceresultsmap, null, jexl, jc); } } if (tools.notempty(currentauthfortest)){ authfortest = currentauthfortest; } if (tools.isempty(authfortest)){ authfortest = defaultauths.getdefaultauth(); } if (uri.indexof("$")>-1){ uri = evalstruct.eval(uri, serviceresultsmap, null, jexl, jc); } fullurl = fixupfullurl(fullurl, protohostport, uri); list<integer> expectedcodes = new arraylist<integer>(); string expectedcodesstr = testnode.valueof("expectedcodes"); if (tools.notempty(expectedcodesstr)){ string[] codesarray = expectedcodesstr.split(","); for (string code : codesarray){ expectedcodes.add(new integer(code.trim())); } } node responsenode = testnode.selectsinglenode("response"); partsstruct expectedresponseparts = null; if (responsenode!=null){ expectedresponseparts = partsstruct.readparts(responsenode, testid, xmlreplaybasedir); } serviceresult serviceresult; boolean ispost = method.equalsignorecase("post"); boolean isput = method.equalsignorecase("put"); if ( ispost || isput ) { partsstruct parts = partsstruct.readparts(testnode, testid, xmlreplaybasedir); if (tools.notempty(parts.overridetestid)) { testid = parts.overridetestid; } if (ispost){ string csid = csidfromtestid(testnode, serviceresultsmap); if (tools.notempty(csid)) uri = tools.glue(uri, "/", csid+"/items/"); } else if (isput) { uri = fromtestid(uri, testnode, serviceresultsmap); } map<string,string> vars = null; if (parts.varslist.size()>0){ vars = parts.varslist.get(0); } serviceresult = xmlreplaytransport.dopost_putfromxml(parts.responsefilename, vars, protohostport, uri, method, contenttype, evalstruct, authfortest, testidlabel); serviceresult.autodelete = autodelete; if (vars!=null) { serviceresult.addvars(vars); } results.add(serviceresult); serviceresultsmap.put(testid, serviceresult); fullurl = fixupfullurl(fullurl, protohostport, uri); } else if (method.equalsignorecase("delete")){ string fromtestid = testnode.valueof("fromtestid"); serviceresult pr = serviceresultsmap.get(fromtestid); if (pr!=null){ serviceresult = xmlreplaytransport.dodelete(pr.deleteurl, authfortest, testidlabel, fromtestid); serviceresult.fromtestid = fromtestid; if (expectedcodes.size()>0){ serviceresult.expectedcodes = expectedcodes; } results.add(serviceresult); if (serviceresult.codeinsuccessrange(serviceresult.responsecode)){ serviceresultsmap.remove(fromtestid); } } else { if (tools.notempty(fromtestid)){ serviceresult = new serviceresult(); serviceresult.responsecode = 0; serviceresult.error = "id not found in element fromtestid: "+fromtestid; system.err.println("****\r\nserviceresult: "+serviceresult.error+". skipping test. full url: "+fullurl); } else { serviceresult = xmlreplaytransport.dodelete(fullurl, authfortest, testid, fromtestid); } serviceresult.fromtestid = fromtestid; results.add(serviceresult); } } else if (method.equalsignorecase("get")){ fullurl = fromtestid(fullurl, testnode, serviceresultsmap); serviceresult = xmlreplaytransport.doget(fullurl, authfortest, testidlabel); results.add(serviceresult); serviceresultsmap.put(testid, serviceresult); } else if (method.equalsignorecase("list")){ fullurl = fixupfullurl(fullurl, protohostport, uri); string listqueryparams = ""; serviceresult = xmlreplaytransport.dolist(fullurl, listqueryparams, authfortest, testidlabel); results.add(serviceresult); serviceresultsmap.put(testid, serviceresult); } else { throw new exception("http method not supported by xmlreplay: "+method); } serviceresult.testid = testid; serviceresult.fullurl = fullurl; serviceresult.auth = authfortest; serviceresult.method = method; if (expectedcodes.size()>0){ serviceresult.expectedcodes = expectedcodes; } if (tools.isempty(serviceresult.testid)) serviceresult.testid = testidlabel; if (tools.isempty(serviceresult.testgroupid)) serviceresult.testgroupid = testgroupid; node expectedlevel = testnode.selectsinglenode("response/expected"); if (expectedlevel!=null){ string level = expectedlevel.valueof("@level"); serviceresult.payloadstrictness = level; } boolean haserror = false; string verror = validateresponse(serviceresult, serviceresultsmap, expectedresponseparts, evalstruct); if (tools.notempty(verror)){ serviceresult.error = verror; serviceresult.failurereason = " : validation error; "; haserror = true; } if (haserror == false){ haserror = ! serviceresult.gotexpectedresult(); } boolean doingauto = (dump.dumpserviceresult == serviceresult.dump_options.auto); string serviceresultrow = serviceresult.dump(dump.dumpserviceresult, haserror)+"; time:"+(system.currenttimemillis()-starttime); string leader = (dump.dumpserviceresult == serviceresult.dump_options.detailed) ? "xmlreplay:"+testidlabel+": ": ""; report.addtestresult(serviceresult); if ( (dump.dumpserviceresult == serviceresult.dump_options.detailed) || (dump.dumpserviceresult == serviceresult.dump_options.full) ){ system.out.println("\r\n#---------------------#"); } system.out.println(timestring()+" "+leader+serviceresultrow+"\r\n"); if (dump.payloads || (doingauto&&haserror) ) { if (tools.notblank(serviceresult.requestpayload)){ system.out.println("\r\n========== request payload ==============="); system.out.println(serviceresult.requestpayload); system.out.println("==========================================\r\n"); } } if (dump.payloads || (doingauto&&haserror)) { if (tools.notblank(serviceresult.result)){ system.out.println("\r\n========== response payload =============="); system.out.println(serviceresult.result); system.out.println("==========================================\r\n"); } } } catch (throwable t) { string msg = "error: xmlreplay experienced an error in a test node: "+testnode+" throwable: "+t; system.out.println(msg); system.out.println(tools.getstacktrace(t)); serviceresult serviceresult = new serviceresult(); serviceresult.error = msg; serviceresult.failurereason = " : system error; "; results.add(serviceresult); } } if (tools.istrue(autodeleteposts) && param_autodeleteposts){ autodelete(serviceresultsmap, "default", 0); } } file m = new file(controlfilename); string localname = m.getname() string reportname = localname+'-'+testgroupid+".html"; file resultfile = report.savereport(xmlreplaybasedir, reportsdir, reportname); if (resultfile!=null) { string toc = report.gettoc(reportname); reportslist.add(toc); } return results; }
litchfieldhistoricalsociety/services
[ 1, 0, 0, 0 ]
25,235
@Test public void positionalConstructors() throws Exception { assertRejected(new ProxyWhitelist(), "new java.lang.Boolean java.lang.String", "['true'] as Boolean"); assertEvaluate(new StaticWhitelist("new java.lang.Boolean java.lang.String"), true, "['true'] as Boolean"); String cc = "staticMethod org.kohsuke.groovy.sandbox.impl.Checker checkedCast java.lang.Class java.lang.Object boolean boolean boolean"; assertRejected(new StaticWhitelist(cc), "new java.lang.Boolean java.lang.String", "Boolean x = ['true']; x"); assertEvaluate(new StaticWhitelist(cc, "new java.lang.Boolean java.lang.String"), true, "Boolean x = ['true']; x"); assertRejected(new ProxyWhitelist(), "new java.util.TreeMap java.util.Map", "[k: 1] as TreeMap"); assertEvaluate(new StaticWhitelist("new java.util.TreeMap java.util.Map"), Collections.singletonMap("k", 1), "[k: 1] as TreeMap"); assertRejected(new StaticWhitelist(cc), "new java.util.TreeMap java.util.Map", "TreeMap x = [k: 1]; x"); assertEvaluate(new StaticWhitelist(cc, "new java.util.TreeMap java.util.Map"), Collections.singletonMap("k", 1), "TreeMap x = [k: 1]; x"); // These go through a different code path: assertEvaluate(new ProxyWhitelist(), Arrays.asList(1), "[1] as LinkedList"); assertEvaluate(new ProxyWhitelist(), Arrays.asList("v"), "['v'] as LinkedList"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList(1), "LinkedList x = [1]; x"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList("v"), "LinkedList x = ['v']; x"); assertEvaluate(new ProxyWhitelist(), Arrays.asList(1), "int[] a = [1]; a as LinkedList"); assertEvaluate(new ProxyWhitelist(), Arrays.asList("v"), "String[] a = ['v']; a as LinkedList"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList("v"), "String[] a = ['v']; LinkedList x = a; x"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList("v"), "String[] a = ['v']; LinkedList x = a; x"); /* TODO casting arrays is not yet supported: assertRejected(new StaticWhitelist(cc), "new java.lang.Boolean java.lang.String", "String[] a = ['true']; Boolean x = a; x"); assertEvaluate(new StaticWhitelist(cc, "new java.lang.Boolean java.lang.String"), true, "String[] a = ['true']; Boolean x = a; x"); assertRejected(new ProxyWhitelist(), "new java.lang.Boolean java.lang.String", "String[] a = ['true']; a as Boolean"); assertEvaluate(new StaticWhitelist("new java.lang.Boolean java.lang.String"), true, "String[] a = ['true']; a as Boolean"); */ /* TODO tuple assignment is not yet supported: assertRejected(new ProxyWhitelist(), "new java.util.LinkedList java.util.Collection", "String[] a = ['v']; def (LinkedList x, int y) = [a, 1]; x"); assertEvaluate(new StaticWhitelist("new java.util.LinkedList java.util.Collection"), Arrays.asList("v"), "String[] a = ['v']; def (LinkedList x, int y) = [a, 1]; x"); */ }
@Test public void positionalConstructors() throws Exception { assertRejected(new ProxyWhitelist(), "new java.lang.Boolean java.lang.String", "['true'] as Boolean"); assertEvaluate(new StaticWhitelist("new java.lang.Boolean java.lang.String"), true, "['true'] as Boolean"); String cc = "staticMethod org.kohsuke.groovy.sandbox.impl.Checker checkedCast java.lang.Class java.lang.Object boolean boolean boolean"; assertRejected(new StaticWhitelist(cc), "new java.lang.Boolean java.lang.String", "Boolean x = ['true']; x"); assertEvaluate(new StaticWhitelist(cc, "new java.lang.Boolean java.lang.String"), true, "Boolean x = ['true']; x"); assertRejected(new ProxyWhitelist(), "new java.util.TreeMap java.util.Map", "[k: 1] as TreeMap"); assertEvaluate(new StaticWhitelist("new java.util.TreeMap java.util.Map"), Collections.singletonMap("k", 1), "[k: 1] as TreeMap"); assertRejected(new StaticWhitelist(cc), "new java.util.TreeMap java.util.Map", "TreeMap x = [k: 1]; x"); assertEvaluate(new StaticWhitelist(cc, "new java.util.TreeMap java.util.Map"), Collections.singletonMap("k", 1), "TreeMap x = [k: 1]; x"); assertEvaluate(new ProxyWhitelist(), Arrays.asList(1), "[1] as LinkedList"); assertEvaluate(new ProxyWhitelist(), Arrays.asList("v"), "['v'] as LinkedList"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList(1), "LinkedList x = [1]; x"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList("v"), "LinkedList x = ['v']; x"); assertEvaluate(new ProxyWhitelist(), Arrays.asList(1), "int[] a = [1]; a as LinkedList"); assertEvaluate(new ProxyWhitelist(), Arrays.asList("v"), "String[] a = ['v']; a as LinkedList"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList("v"), "String[] a = ['v']; LinkedList x = a; x"); assertEvaluate(new StaticWhitelist(cc), Arrays.asList("v"), "String[] a = ['v']; LinkedList x = a; x"); }
@test public void positionalconstructors() throws exception { assertrejected(new proxywhitelist(), "new java.lang.boolean java.lang.string", "['true'] as boolean"); assertevaluate(new staticwhitelist("new java.lang.boolean java.lang.string"), true, "['true'] as boolean"); string cc = "staticmethod org.kohsuke.groovy.sandbox.impl.checker checkedcast java.lang.class java.lang.object boolean boolean boolean"; assertrejected(new staticwhitelist(cc), "new java.lang.boolean java.lang.string", "boolean x = ['true']; x"); assertevaluate(new staticwhitelist(cc, "new java.lang.boolean java.lang.string"), true, "boolean x = ['true']; x"); assertrejected(new proxywhitelist(), "new java.util.treemap java.util.map", "[k: 1] as treemap"); assertevaluate(new staticwhitelist("new java.util.treemap java.util.map"), collections.singletonmap("k", 1), "[k: 1] as treemap"); assertrejected(new staticwhitelist(cc), "new java.util.treemap java.util.map", "treemap x = [k: 1]; x"); assertevaluate(new staticwhitelist(cc, "new java.util.treemap java.util.map"), collections.singletonmap("k", 1), "treemap x = [k: 1]; x"); assertevaluate(new proxywhitelist(), arrays.aslist(1), "[1] as linkedlist"); assertevaluate(new proxywhitelist(), arrays.aslist("v"), "['v'] as linkedlist"); assertevaluate(new staticwhitelist(cc), arrays.aslist(1), "linkedlist x = [1]; x"); assertevaluate(new staticwhitelist(cc), arrays.aslist("v"), "linkedlist x = ['v']; x"); assertevaluate(new proxywhitelist(), arrays.aslist(1), "int[] a = [1]; a as linkedlist"); assertevaluate(new proxywhitelist(), arrays.aslist("v"), "string[] a = ['v']; a as linkedlist"); assertevaluate(new staticwhitelist(cc), arrays.aslist("v"), "string[] a = ['v']; linkedlist x = a; x"); assertevaluate(new staticwhitelist(cc), arrays.aslist("v"), "string[] a = ['v']; linkedlist x = a; x"); }
maheshp/gocd-groovy-dsl-config-plugin
[ 1, 1, 0, 0 ]
685
public static final int testElementParsing ( final PrintStream out, final BufferedReader in, final String ... args) { final String ans=getval(out, in, "use owner document y/[n]/q"); if (isQuit(ans)) return 0; Document owner=null; if ((ans != null) && (ans.length() > 0) && ('y' == Character.toLowerCase(ans.charAt(0)))) { try { owner = DOMUtils.createDefaultDocument(); } catch(ParserConfigurationException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } final int nErr=testElementParsing(out, in, owner, args); if (owner != null) { // TODO show resulting document } return nErr; }
public static final int testElementParsing ( final PrintStream out, final BufferedReader in, final String ... args) { final String ans=getval(out, in, "use owner document y/[n]/q"); if (isQuit(ans)) return 0; Document owner=null; if ((ans != null) && (ans.length() > 0) && ('y' == Character.toLowerCase(ans.charAt(0)))) { try { owner = DOMUtils.createDefaultDocument(); } catch(ParserConfigurationException e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } final int nErr=testElementParsing(out, in, owner, args); if (owner != null) { } return nErr; }
public static final int testelementparsing ( final printstream out, final bufferedreader in, final string ... args) { final string ans=getval(out, in, "use owner document y/[n]/q"); if (isquit(ans)) return 0; document owner=null; if ((ans != null) && (ans.length() > 0) && ('y' == character.tolowercase(ans.charat(0)))) { try { owner = domutils.createdefaultdocument(); } catch(parserconfigurationexception e) { system.err.println(e.getclass().getname() + ": " + e.getmessage()); } } final int nerr=testelementparsing(out, in, owner, args); if (owner != null) { } return nerr; }
lgoldstein/communitychest
[ 0, 1, 0, 0 ]
33,498
@SuppressWarnings("fallthrough") @Override public Token<CppTokenId> nextToken() { while (true) { // special handling for escaped lines if (lastTokenEndedByEscapedLine > 0) { int c = read(false); lastTokenEndedByEscapedLine--; assert c == '\\' : "there must be \\"; c = read(false); assert c == '\n' || c == '\r' : "there must be \r or \n"; if (c == '\r') { lastTokenEndedByEscapedLine--; if (input.consumeNewline()) { lastTokenEndedByEscapedLine--; } return token(CppTokenId.ESCAPED_LINE); } else { lastTokenEndedByEscapedLine--; return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); // NOI18N } } else { int c = read(true); // if read of the first char caused skipping escaped line // do we need to backup and create escaped lines first? switch (c) { case '"': { Token<CppTokenId> out = finishDblQuote(); assert out != null : "not handled dobule quote"; return out; } case '\'': {// char literal Token<CppTokenId> out = finishSingleQuote(); assert out != null : "not handled single quote"; return out; } case '#': { Token<CppTokenId> out = finishSharp(); assert out != null : "not handled #"; return out; } case '/': switch (read(true)) { case '/': // in single-line or doxygen comment { Token<CppTokenId> out = finishLineComment(true); assert out != null : "not handled //"; return out; } case '=': // found /= return token(CppTokenId.SLASHEQ); case '*': // in multi-line or doxygen comment { Token<CppTokenId> out = finishBlockComment(true); assert out != null : "not handled /*"; return out; } } // end of switch() backup(1); return token(CppTokenId.SLASH); case '=': if (read(true) == '=') { return token(CppTokenId.EQEQ); } backup(1); return token(CppTokenId.EQ); case '>': switch (read(true)) { case '>': // >> if (read(true) == '=') { return token(CppTokenId.GTGTEQ); } backup(1); return token(CppTokenId.GTGT); case '=': // >= return token(CppTokenId.GTEQ); } backup(1); return token(CppTokenId.GT); case '<': { Token<CppTokenId> out = finishLT(); assert out != null : "not handled '<'"; return out; } case '+': switch (read(true)) { case '+': return token(CppTokenId.PLUSPLUS); case '=': return token(CppTokenId.PLUSEQ); } backup(1); return token(CppTokenId.PLUS); case '-': switch (read(true)) { case '-': return token(CppTokenId.MINUSMINUS); case '>': if (read(true) == '*') { return token(CppTokenId.ARROWMBR); } backup(1); return token(CppTokenId.ARROW); case '=': return token(CppTokenId.MINUSEQ); } backup(1); return token(CppTokenId.MINUS); case '*': switch (read(true)) { case '/': // invalid comment end - */ or int*/* */ if (read(true) == '*') { backup(2); return token(CppTokenId.STAR); } backup(1); return token(CppTokenId.INVALID_COMMENT_END); case '=': return token(CppTokenId.STAREQ); } backup(1); return token(CppTokenId.STAR); case '|': switch (read(true)) { case '|': return token(CppTokenId.BARBAR); case '=': return token(CppTokenId.BAREQ); } backup(1); return token(CppTokenId.BAR); case '&': switch (read(true)) { case '&': return token(CppTokenId.AMPAMP); case '=': return token(CppTokenId.AMPEQ); } backup(1); return token(CppTokenId.AMP); case '%': { Token<CppTokenId> out = finishPercent(); assert out != null : "not handled %"; return out; } case '^': if (read(true) == '=') { return token(CppTokenId.CARETEQ); } backup(1); return token(CppTokenId.CARET); case '!': if (read(true) == '=') { return token(CppTokenId.NOTEQ); } backup(1); return token(CppTokenId.NOT); case '.': if ((c = read(true)) == '.') { if (read(true) == '.') { // ellipsis ... return token(CppTokenId.ELLIPSIS); } else { input.backup(2); } } else if ('0' <= c && c <= '9') { // float literal return finishNumberLiteral(read(true), true); } else if (c == '*') { return token(CppTokenId.DOTMBR); } else { backup(1); } return token(CppTokenId.DOT); case ':': if (read(true) == ':') { return token(CppTokenId.SCOPE); } backup(1); return token(CppTokenId.COLON); case '~': return token(CppTokenId.TILDE); case ',': return token(CppTokenId.COMMA); case ';': return token(CppTokenId.SEMICOLON); case '?': return token(CppTokenId.QUESTION); case '(': return token(CppTokenId.LPAREN); case ')': return token(CppTokenId.RPAREN); case '[': return token(CppTokenId.LBRACKET); case ']': return token(CppTokenId.RBRACKET); case '{': return token(CppTokenId.LBRACE); case '}': return token(CppTokenId.RBRACE); case '`': return token(CppTokenId.GRAVE_ACCENT); case '@': return token(CppTokenId.AT); case '0': // in a number literal c = read(true); if (c == 'x' || c == 'X' || // in hexadecimal (possibly floating-point) literal c == 'b' || c == 'B' ) { // in bianry literal boolean inFraction = false; while (true) { switch (read(true)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': break; case '.': // hex float literal if (!inFraction) { inFraction = true; } else { // two dots in the float literal return token(CppTokenId.FLOAT_LITERAL_INVALID); } break; case 'l': case 'L': // 0x1234l or 0x1234L return finishLongLiteral(read(true)); case 'p': case 'P': // binary exponent return finishFloatExponent(); case 'u': case 'U': return finishUnsignedLiteral(read(true)); default: backup(1); // if float then before mandatory binary exponent => invalid return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID : CppTokenId.INT_LITERAL); } } // end of while(true) } return finishNumberLiteral(c, false); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return finishNumberLiteral(read(true), false); case '\\': return token(CppTokenId.BACK_SLASH); case '\r': consumeNewline(); return token(CppTokenId.NEW_LINE); case '\n': return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); // NOI18N // All Character.isWhitespace(c) below 0x80 follow // ['\t' - '\f'] and [0x1c - ' '] case '\t': case 0x0b: case '\f': case 0x1c: case 0x1d: case 0x1e: case 0x1f: return finishWhitespace(); case ' ': c = read(true); if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { // Return single space as flyweight token backup(1); return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); // NOI18N } return finishWhitespace(); case EOF: if (isTokenSplittedByEscapedLine()) { backup(1); assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine; break; } return null; case '$': // dollar is extension in gcc and msvc $ is a valid start of identifiers // return token(CppTokenId.DOLLAR); default: c = translateSurrogates(c); if (CndLexerUtilities.isCppIdentifierStart(c)) { if (c == 'L' || c == 'U' || c == 'u' || c == 'R') { int next = read(true); boolean raw_string = (c == 'R'); if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) { // uR, UR or LR raw_string = true; next = read(true); } else if (next == '8' && c == 'u') { // u8 next = read(true); if (next == 'R') { // u8R raw_string = true; next = read(true); } } if (next == '"') { // string with L/U/u/R prefixes Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote(); assert out != null : "not handled dobule quote"; return out; } else if (next == '\'' && !raw_string) { // char with L or U/u prefix Token<CppTokenId> out = finishSingleQuote(); assert out != null : "not handled single quote"; return out; } else { backup(1); } } if (c == 'E') { if(isExecSQL(c)) { Token<CppTokenId> out = finishExecSQL(); assert out != null : "not handled exec sql"; return out; } } return keywordOrIdentifier(c); } if (Character.isWhitespace(c)) { return finishWhitespace(); } // Invalid char return token(CppTokenId.ERROR); } } // end of switch (c) } // end of while(true) }
@SuppressWarnings("fallthrough") @Override public Token<CppTokenId> nextToken() { while (true) { if (lastTokenEndedByEscapedLine > 0) { int c = read(false); lastTokenEndedByEscapedLine--; assert c == '\\' : "there must be \\"; c = read(false); assert c == '\n' || c == '\r' : "there must be \r or \n"; if (c == '\r') { lastTokenEndedByEscapedLine--; if (input.consumeNewline()) { lastTokenEndedByEscapedLine--; } return token(CppTokenId.ESCAPED_LINE); } else { lastTokenEndedByEscapedLine--; return token(CppTokenId.ESCAPED_LINE, "\\\n", PartType.COMPLETE); } } else { int c = read(true); switch (c) { case '"': { Token<CppTokenId> out = finishDblQuote(); assert out != null : "not handled dobule quote"; return out; } case '\'': Token<CppTokenId> out = finishSingleQuote(); assert out != null : "not handled single quote"; return out; } case '#': { Token<CppTokenId> out = finishSharp(); assert out != null : "not handled #"; return out; } case '/': switch (read(true)) { case '/': { Token<CppTokenId> out = finishLineComment(true); assert out != null : "not handled //"; return out; } case '=': return token(CppTokenId.SLASHEQ); case '*': { Token<CppTokenId> out = finishBlockComment(true); assert out != null : "not handled /*"; return out; } } backup(1); return token(CppTokenId.SLASH); case '=': if (read(true) == '=') { return token(CppTokenId.EQEQ); } backup(1); return token(CppTokenId.EQ); case '>': switch (read(true)) { case '>': if (read(true) == '=') { return token(CppTokenId.GTGTEQ); } backup(1); return token(CppTokenId.GTGT); case '=': return token(CppTokenId.GTEQ); } backup(1); return token(CppTokenId.GT); case '<': { Token<CppTokenId> out = finishLT(); assert out != null : "not handled '<'"; return out; } case '+': switch (read(true)) { case '+': return token(CppTokenId.PLUSPLUS); case '=': return token(CppTokenId.PLUSEQ); } backup(1); return token(CppTokenId.PLUS); case '-': switch (read(true)) { case '-': return token(CppTokenId.MINUSMINUS); case '>': if (read(true) == '*') { return token(CppTokenId.ARROWMBR); } backup(1); return token(CppTokenId.ARROW); case '=': return token(CppTokenId.MINUSEQ); } backup(1); return token(CppTokenId.MINUS); case '*': switch (read(true)) { case '/': if (read(true) == '*') { backup(2); return token(CppTokenId.STAR); } backup(1); return token(CppTokenId.INVALID_COMMENT_END); case '=': return token(CppTokenId.STAREQ); } backup(1); return token(CppTokenId.STAR); case '|': switch (read(true)) { case '|': return token(CppTokenId.BARBAR); case '=': return token(CppTokenId.BAREQ); } backup(1); return token(CppTokenId.BAR); case '&': switch (read(true)) { case '&': return token(CppTokenId.AMPAMP); case '=': return token(CppTokenId.AMPEQ); } backup(1); return token(CppTokenId.AMP); case '%': { Token<CppTokenId> out = finishPercent(); assert out != null : "not handled %"; return out; } case '^': if (read(true) == '=') { return token(CppTokenId.CARETEQ); } backup(1); return token(CppTokenId.CARET); case '!': if (read(true) == '=') { return token(CppTokenId.NOTEQ); } backup(1); return token(CppTokenId.NOT); case '.': if ((c = read(true)) == '.') { if (read(true) == '.') { return token(CppTokenId.ELLIPSIS); } else { input.backup(2); } } else if ('0' <= c && c <= '9') { return finishNumberLiteral(read(true), true); } else if (c == '*') { return token(CppTokenId.DOTMBR); } else { backup(1); } return token(CppTokenId.DOT); case ':': if (read(true) == ':') { return token(CppTokenId.SCOPE); } backup(1); return token(CppTokenId.COLON); case '~': return token(CppTokenId.TILDE); case ',': return token(CppTokenId.COMMA); case ';': return token(CppTokenId.SEMICOLON); case '?': return token(CppTokenId.QUESTION); case '(': return token(CppTokenId.LPAREN); case ')': return token(CppTokenId.RPAREN); case '[': return token(CppTokenId.LBRACKET); case ']': return token(CppTokenId.RBRACKET); case '{': return token(CppTokenId.LBRACE); case '}': return token(CppTokenId.RBRACE); case '`': return token(CppTokenId.GRAVE_ACCENT); case '@': return token(CppTokenId.AT); case '0': c = read(true); if (c == 'x' || c == 'X' || c == 'b' || c == 'B' ) { boolean inFraction = false; while (true) { switch (read(true)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': break; case '.': if (!inFraction) { inFraction = true; } else { return token(CppTokenId.FLOAT_LITERAL_INVALID); } break; case 'l': case 'L': return finishLongLiteral(read(true)); case 'p': case 'P': return finishFloatExponent(); case 'u': case 'U': return finishUnsignedLiteral(read(true)); default: backup(1); return token(inFraction ? CppTokenId.FLOAT_LITERAL_INVALID : CppTokenId.INT_LITERAL); } } } return finishNumberLiteral(c, false); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return finishNumberLiteral(read(true), false); case '\\': return token(CppTokenId.BACK_SLASH); case '\r': consumeNewline(); return token(CppTokenId.NEW_LINE); case '\n': return token(CppTokenId.NEW_LINE, "\n", PartType.COMPLETE); case '\t': case 0x0b: case '\f': case 0x1c: case 0x1d: case 0x1e: case 0x1f: return finishWhitespace(); case ' ': c = read(true); if (c == EOF || !Character.isWhitespace(c) || c == '\n' || c == '\r') { backup(1); return token(CppTokenId.WHITESPACE, " ", PartType.COMPLETE); } return finishWhitespace(); case EOF: if (isTokenSplittedByEscapedLine()) { backup(1); assert lastTokenEndedByEscapedLine > 0 : "lastTokenEndedByEscapedLine is " + lastTokenEndedByEscapedLine; break; } return null; case '$': default: c = translateSurrogates(c); if (CndLexerUtilities.isCppIdentifierStart(c)) { if (c == 'L' || c == 'U' || c == 'u' || c == 'R') { int next = read(true); boolean raw_string = (c == 'R'); if (next == 'R' && (c == 'u' || c == 'U' || c == 'L')) { raw_string = true; next = read(true); } else if (next == '8' && c == 'u') { next = read(true); if (next == 'R') { raw_string = true; next = read(true); } } if (next == '"') { Token<CppTokenId> out = raw_string ? finishRawString() : finishDblQuote(); assert out != null : "not handled dobule quote"; return out; } else if (next == '\'' && !raw_string) { Token<CppTokenId> out = finishSingleQuote(); assert out != null : "not handled single quote"; return out; } else { backup(1); } } if (c == 'E') { if(isExecSQL(c)) { Token<CppTokenId> out = finishExecSQL(); assert out != null : "not handled exec sql"; return out; } } return keywordOrIdentifier(c); } if (Character.isWhitespace(c)) { return finishWhitespace(); } return token(CppTokenId.ERROR); } } } }
@suppresswarnings("fallthrough") @override public token<cpptokenid> nexttoken() { while (true) { if (lasttokenendedbyescapedline > 0) { int c = read(false); lasttokenendedbyescapedline--; assert c == '\\' : "there must be \\"; c = read(false); assert c == '\n' || c == '\r' : "there must be \r or \n"; if (c == '\r') { lasttokenendedbyescapedline--; if (input.consumenewline()) { lasttokenendedbyescapedline--; } return token(cpptokenid.escaped_line); } else { lasttokenendedbyescapedline--; return token(cpptokenid.escaped_line, "\\\n", parttype.complete); } } else { int c = read(true); switch (c) { case '"': { token<cpptokenid> out = finishdblquote(); assert out != null : "not handled dobule quote"; return out; } case '\'': token<cpptokenid> out = finishsinglequote(); assert out != null : "not handled single quote"; return out; } case '#': { token<cpptokenid> out = finishsharp(); assert out != null : "not handled #"; return out; } case '/': switch (read(true)) { case '/': { token<cpptokenid> out = finishlinecomment(true); assert out != null : "not handled //"; return out; } case '=': return token(cpptokenid.slasheq); case '*': { token<cpptokenid> out = finishblockcomment(true); assert out != null : "not handled /*"; return out; } } backup(1); return token(cpptokenid.slash); case '=': if (read(true) == '=') { return token(cpptokenid.eqeq); } backup(1); return token(cpptokenid.eq); case '>': switch (read(true)) { case '>': if (read(true) == '=') { return token(cpptokenid.gtgteq); } backup(1); return token(cpptokenid.gtgt); case '=': return token(cpptokenid.gteq); } backup(1); return token(cpptokenid.gt); case '<': { token<cpptokenid> out = finishlt(); assert out != null : "not handled '<'"; return out; } case '+': switch (read(true)) { case '+': return token(cpptokenid.plusplus); case '=': return token(cpptokenid.pluseq); } backup(1); return token(cpptokenid.plus); case '-': switch (read(true)) { case '-': return token(cpptokenid.minusminus); case '>': if (read(true) == '*') { return token(cpptokenid.arrowmbr); } backup(1); return token(cpptokenid.arrow); case '=': return token(cpptokenid.minuseq); } backup(1); return token(cpptokenid.minus); case '*': switch (read(true)) { case '/': if (read(true) == '*') { backup(2); return token(cpptokenid.star); } backup(1); return token(cpptokenid.invalid_comment_end); case '=': return token(cpptokenid.stareq); } backup(1); return token(cpptokenid.star); case '|': switch (read(true)) { case '|': return token(cpptokenid.barbar); case '=': return token(cpptokenid.bareq); } backup(1); return token(cpptokenid.bar); case '&': switch (read(true)) { case '&': return token(cpptokenid.ampamp); case '=': return token(cpptokenid.ampeq); } backup(1); return token(cpptokenid.amp); case '%': { token<cpptokenid> out = finishpercent(); assert out != null : "not handled %"; return out; } case '^': if (read(true) == '=') { return token(cpptokenid.careteq); } backup(1); return token(cpptokenid.caret); case '!': if (read(true) == '=') { return token(cpptokenid.noteq); } backup(1); return token(cpptokenid.not); case '.': if ((c = read(true)) == '.') { if (read(true) == '.') { return token(cpptokenid.ellipsis); } else { input.backup(2); } } else if ('0' <= c && c <= '9') { return finishnumberliteral(read(true), true); } else if (c == '*') { return token(cpptokenid.dotmbr); } else { backup(1); } return token(cpptokenid.dot); case ':': if (read(true) == ':') { return token(cpptokenid.scope); } backup(1); return token(cpptokenid.colon); case '~': return token(cpptokenid.tilde); case ',': return token(cpptokenid.comma); case ';': return token(cpptokenid.semicolon); case '?': return token(cpptokenid.question); case '(': return token(cpptokenid.lparen); case ')': return token(cpptokenid.rparen); case '[': return token(cpptokenid.lbracket); case ']': return token(cpptokenid.rbracket); case '{': return token(cpptokenid.lbrace); case '}': return token(cpptokenid.rbrace); case '`': return token(cpptokenid.grave_accent); case '@': return token(cpptokenid.at); case '0': c = read(true); if (c == 'x' || c == 'x' || c == 'b' || c == 'b' ) { boolean infraction = false; while (true) { switch (read(true)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': break; case '.': if (!infraction) { infraction = true; } else { return token(cpptokenid.float_literal_invalid); } break; case 'l': case 'l': return finishlongliteral(read(true)); case 'p': case 'p': return finishfloatexponent(); case 'u': case 'u': return finishunsignedliteral(read(true)); default: backup(1); return token(infraction ? cpptokenid.float_literal_invalid : cpptokenid.int_literal); } } } return finishnumberliteral(c, false); case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return finishnumberliteral(read(true), false); case '\\': return token(cpptokenid.back_slash); case '\r': consumenewline(); return token(cpptokenid.new_line); case '\n': return token(cpptokenid.new_line, "\n", parttype.complete); case '\t': case 0x0b: case '\f': case 0x1c: case 0x1d: case 0x1e: case 0x1f: return finishwhitespace(); case ' ': c = read(true); if (c == eof || !character.iswhitespace(c) || c == '\n' || c == '\r') { backup(1); return token(cpptokenid.whitespace, " ", parttype.complete); } return finishwhitespace(); case eof: if (istokensplittedbyescapedline()) { backup(1); assert lasttokenendedbyescapedline > 0 : "lasttokenendedbyescapedline is " + lasttokenendedbyescapedline; break; } return null; case '$': default: c = translatesurrogates(c); if (cndlexerutilities.iscppidentifierstart(c)) { if (c == 'l' || c == 'u' || c == 'u' || c == 'r') { int next = read(true); boolean raw_string = (c == 'r'); if (next == 'r' && (c == 'u' || c == 'u' || c == 'l')) { raw_string = true; next = read(true); } else if (next == '8' && c == 'u') { next = read(true); if (next == 'r') { raw_string = true; next = read(true); } } if (next == '"') { token<cpptokenid> out = raw_string ? finishrawstring() : finishdblquote(); assert out != null : "not handled dobule quote"; return out; } else if (next == '\'' && !raw_string) { token<cpptokenid> out = finishsinglequote(); assert out != null : "not handled single quote"; return out; } else { backup(1); } } if (c == 'e') { if(isexecsql(c)) { token<cpptokenid> out = finishexecsql(); assert out != null : "not handled exec sql"; return out; } } return keywordoridentifier(c); } if (character.iswhitespace(c)) { return finishwhitespace(); } return token(cpptokenid.error); } } } }
leginee/netbeans
[ 1, 0, 0, 0 ]
25,373
protected void evaluateAndShowHint() { myEvaluator.evaluate(myExpression, new XEvaluationCallbackBase() { public void evaluated(@NotNull final XValue result) { result.computePresentation(new XValueNode() { @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value, boolean hasChildren) { setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, hasChildren); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String separator, @NonNls @NotNull String value, boolean hasChildren) { setPresentation(icon, type, separator, value, null, hasChildren); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value, @Nullable NotNullFunction<String, String> valuePresenter, boolean hasChildren) { setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren); } @Override public void setGroupingPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean expand) { setPresentation(icon, value, valuePresenter, true); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean hasChildren) { doSetPresentation(icon, null, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator, @NonNls @NotNull final String value, @Nullable final NotNullFunction<String, String> valuePresenter, final boolean hasChildren) { doSetPresentation(icon, type, separator, value, valuePresenter == null ? null : new XValuePresenterAdapter(valuePresenter), hasChildren); } private void doSetPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator, @NonNls @Nullable final String value, @Nullable final XValuePresenter valuePresenter, final boolean hasChildren) { AppUIUtil.invokeOnEdt(new Runnable() { public void run() { doShowHint(result, separator, value, type, valuePresenter == null ? XValueNodeImpl.DEFAULT_VALUE_PRESENTER : valuePresenter, hasChildren); } }); } public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value, final boolean hasChildren) { setPresentation(icon, type, value, hasChildren); } public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator, @NonNls @NotNull final String value, final boolean hasChildren) { setPresentation(icon, type, separator, value, hasChildren); } public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) { //todo[nik] implement? } public boolean isObsolete() { //todo[nik] return false; } }, XValuePlace.TOOLTIP); } public void errorOccurred(@NotNull final String errorMessage) { LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage); } }, myExpressionPosition); }
protected void evaluateAndShowHint() { myEvaluator.evaluate(myExpression, new XEvaluationCallbackBase() { public void evaluated(@NotNull final XValue result) { result.computePresentation(new XValueNode() { @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value, boolean hasChildren) { setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, hasChildren); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String separator, @NonNls @NotNull String value, boolean hasChildren) { setPresentation(icon, type, separator, value, null, hasChildren); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String type, @NonNls @NotNull String value, @Nullable NotNullFunction<String, String> valuePresenter, boolean hasChildren) { setPresentation(icon, type, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren); } @Override public void setGroupingPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean expand) { setPresentation(icon, value, valuePresenter, true); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable String value, @Nullable XValuePresenter valuePresenter, boolean hasChildren) { doSetPresentation(icon, null, XDebuggerUIConstants.EQ_TEXT, value, valuePresenter, hasChildren); } @Override public void setPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator, @NonNls @NotNull final String value, @Nullable final NotNullFunction<String, String> valuePresenter, final boolean hasChildren) { doSetPresentation(icon, type, separator, value, valuePresenter == null ? null : new XValuePresenterAdapter(valuePresenter), hasChildren); } private void doSetPresentation(@Nullable Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator, @NonNls @Nullable final String value, @Nullable final XValuePresenter valuePresenter, final boolean hasChildren) { AppUIUtil.invokeOnEdt(new Runnable() { public void run() { doShowHint(result, separator, value, type, valuePresenter == null ? XValueNodeImpl.DEFAULT_VALUE_PRESENTER : valuePresenter, hasChildren); } }); } public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String value, final boolean hasChildren) { setPresentation(icon, type, value, hasChildren); } public void setPresentation(@NonNls final String name, @Nullable final Icon icon, @NonNls @Nullable final String type, @NonNls @NotNull final String separator, @NonNls @NotNull final String value, final boolean hasChildren) { setPresentation(icon, type, separator, value, hasChildren); } public void setFullValueEvaluator(@NotNull XFullValueEvaluator fullValueEvaluator) { } public boolean isObsolete() { return false; } }, XValuePlace.TOOLTIP); } public void errorOccurred(@NotNull final String errorMessage) { LOG.debug("Cannot evaluate '" + myExpression + "':" + errorMessage); } }, myExpressionPosition); }
protected void evaluateandshowhint() { myevaluator.evaluate(myexpression, new xevaluationcallbackbase() { public void evaluated(@notnull final xvalue result) { result.computepresentation(new xvaluenode() { @override public void setpresentation(@nullable icon icon, @nonnls @nullable string type, @nonnls @notnull string value, boolean haschildren) { setpresentation(icon, type, xdebuggeruiconstants.eq_text, value, haschildren); } @override public void setpresentation(@nullable icon icon, @nonnls @nullable string type, @nonnls @notnull string separator, @nonnls @notnull string value, boolean haschildren) { setpresentation(icon, type, separator, value, null, haschildren); } @override public void setpresentation(@nullable icon icon, @nonnls @nullable string type, @nonnls @notnull string value, @nullable notnullfunction<string, string> valuepresenter, boolean haschildren) { setpresentation(icon, type, xdebuggeruiconstants.eq_text, value, valuepresenter, haschildren); } @override public void setgroupingpresentation(@nullable icon icon, @nonnls @nullable string value, @nullable xvaluepresenter valuepresenter, boolean expand) { setpresentation(icon, value, valuepresenter, true); } @override public void setpresentation(@nullable icon icon, @nonnls @nullable string value, @nullable xvaluepresenter valuepresenter, boolean haschildren) { dosetpresentation(icon, null, xdebuggeruiconstants.eq_text, value, valuepresenter, haschildren); } @override public void setpresentation(@nullable icon icon, @nonnls @nullable final string type, @nonnls @notnull final string separator, @nonnls @notnull final string value, @nullable final notnullfunction<string, string> valuepresenter, final boolean haschildren) { dosetpresentation(icon, type, separator, value, valuepresenter == null ? null : new xvaluepresenteradapter(valuepresenter), haschildren); } private void dosetpresentation(@nullable icon icon, @nonnls @nullable final string type, @nonnls @notnull final string separator, @nonnls @nullable final string value, @nullable final xvaluepresenter valuepresenter, final boolean haschildren) { appuiutil.invokeonedt(new runnable() { public void run() { doshowhint(result, separator, value, type, valuepresenter == null ? xvaluenodeimpl.default_value_presenter : valuepresenter, haschildren); } }); } public void setpresentation(@nonnls final string name, @nullable final icon icon, @nonnls @nullable final string type, @nonnls @notnull final string value, final boolean haschildren) { setpresentation(icon, type, value, haschildren); } public void setpresentation(@nonnls final string name, @nullable final icon icon, @nonnls @nullable final string type, @nonnls @notnull final string separator, @nonnls @notnull final string value, final boolean haschildren) { setpresentation(icon, type, separator, value, haschildren); } public void setfullvalueevaluator(@notnull xfullvalueevaluator fullvalueevaluator) { } public boolean isobsolete() { return false; } }, xvalueplace.tooltip); } public void erroroccurred(@notnull final string errormessage) { log.debug("cannot evaluate '" + myexpression + "':" + errormessage); } }, myexpressionposition); }
liveqmock/platform-tools-idea
[ 0, 1, 0, 0 ]
25,388
@DB private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId, boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr, final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId); final DataCenterVO zone = _dcDao.findById(zoneId); // this method supports only guest network creation if (ntwkOff.getTrafficType() != TrafficType.Guest) { s_logger.warn("Only guest networks can be created using this method"); return null; } final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType); //check resource limits if (updateResourceCount) { _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled); } // Validate network offering if (ntwkOff.getState() != NetworkOffering.State.Enabled) { // see NetworkOfferingVO final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled); ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId"); throw ex; } // Validate physical network if (pNtwk.getState() != PhysicalNetwork.State.Enabled) { // see PhysicalNetworkVO.java final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState()); ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId"); throw ex; } boolean ipv6 = false; if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) { ipv6 = true; } // Validate zone if (zone.getNetworkType() == NetworkType.Basic) { // In Basic zone the network should have aclType=Domain, domainId=1, subdomainAccess=true if (aclType == null || aclType != ACLType.Domain) { throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); } // Only one guest network is supported in Basic zone final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest); if (!guestNetworks.isEmpty()) { throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic); } // if zone is basic, only Shared network offerings w/o source nat service are allowed if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + " service are allowed"); } if (domainId == null || domainId != Domain.ROOT_DOMAIN) { throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain"); } if (subdomainAccess == null) { subdomainAccess = true; } else if (!subdomainAccess) { throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone"); } if (vlanId == null) { vlanId = Vlan.UNTAGGED; } else { if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) { throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic); } } } else if (zone.getNetworkType() == NetworkType.Advanced) { if (zone.isSecurityGroupEnabled()) { if (isolatedPvlan != null) { throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!"); } // Only Account specific Isolated network with sourceNat service disabled are allowed in security group // enabled zone if (ntwkOff.getGuestType() != GuestType.Shared) { throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone"); } if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) { throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone"); } } //don't allow eip/elb networks in Advance zone if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) { throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic); } } if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) { throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size"); } //TODO(VXLAN): Support VNI specified // VlanId can be specified only when network offering supports it final boolean vlanSpecified = vlanId != null; if (vlanSpecified != ntwkOff.isSpecifyVlan()) { if (vlanSpecified) { throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false"); } else { throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true"); } } if (vlanSpecified) { URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk); // Aux: generate secondary URI for secondary VLAN ID (if provided) for performing checks URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null; //don't allow to specify vlan tag used by physical network for dynamic vlan allocation if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) { throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName()); } if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) { throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName()); } if (! UuidUtils.validateUUID(vlanId)){ // For Isolated and L2 networks, don't allow to create network with vlan that already exists in the zone if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) { if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) { throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId); } else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) { throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId); } else { final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri)); //for the network that is created as part of private gateway, //the vnet is not coming from the data center vnet table, so the list can be empty if (!dcVnets.isEmpty()) { final DataCenterVnetVO dcVnet = dcVnets.get(0); // Fail network creation if specified vlan is dedicated to a different account if (dcVnet.getAccountGuestVlanMapId() != null) { final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId(); final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId); if (map.getAccountId() != owner.getAccountId()) { throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account"); } // Fail network creation if owner has a dedicated range of vlans but the specified vlan belongs to the system pool } else { final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId()); if (maps != null && !maps.isEmpty()) { final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId()); final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId()); if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) { throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner " + owner.getAccountName()); } } } } } } else { // don't allow to creating shared network with given Vlan ID, if there already exists a isolated network or // shared network with same Vlan ID in the zone if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) { throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId); } } } } // If networkDomain is not specified, take it from the global configuration if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), Service.Dns); final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { if (networkDomain != null) { // TBD: NetworkOfferingId and zoneId. Send uuids instead. throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId); } } else { if (networkDomain == null) { // 1) Get networkDomain from the corresponding account/domain/zone if (aclType == ACLType.Domain) { networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId); } else if (aclType == ACLType.Account) { networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId); } // 2) If null, generate networkDomain using domain suffix from the global config variables if (networkDomain == null) { networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId); } } else { // validate network domain if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\""); } } } } // In Advance zone Cidr for Shared networks and Isolated networks w/o source nat service can't be NULL - 2.2.x // limitation, remove after we introduce support for multiple ip ranges // with different Cidrs for the same Shared network final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && ntwkOff.getTrafficType() == TrafficType.Guest && (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))); if (cidr == null && ip6Cidr == null && cidrRequired) { if (ntwkOff.getGuestType() == GuestType.Shared) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared); } else { throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); } } checkL2OfferingServices(ntwkOff); // No cidr can be specified in Basic zone if (zone.getNetworkType() == NetworkType.Basic && cidr != null) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic); } // Check if cidr is RFC1918 compliant if the network is Guest Isolated for IPv4 if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant"); } } final String networkDomainFinal = networkDomain; final String vlanIdFinal = vlanId; final Boolean subdomainAccessFinal = subdomainAccess; final Network network = Transaction.execute(new TransactionCallback<Network>() { @Override public Network doInTransaction(final TransactionStatus status) { Long physicalNetworkId = null; if (pNtwk != null) { physicalNetworkId = pNtwk.getId(); } final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId); final NetworkVO userNetwork = new NetworkVO(); userNetwork.setNetworkDomain(networkDomainFinal); if (cidr != null && gateway != null) { userNetwork.setCidr(cidr); userNetwork.setGateway(gateway); } if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) { userNetwork.setIp6Cidr(ip6Cidr); userNetwork.setIp6Gateway(ip6Gateway); } if (externalId != null) { userNetwork.setExternalId(externalId); } if (StringUtils.isNotBlank(routerIp)) { userNetwork.setRouterIp(routerIp); } if (StringUtils.isNotBlank(routerIpv6)) { userNetwork.setRouterIpv6(routerIpv6); } if (vlanIdFinal != null) { if (isolatedPvlan == null) { URI uri = null; if (UuidUtils.validateUUID(vlanIdFinal)){ //Logical router's UUID provided as VLAN_ID userNetwork.setVlanIdAsUUID(vlanIdFinal); //Set transient field } else { uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk); } if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) { throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal + " already exists or overlaps with other network pvlans in zone " + zoneId); } userNetwork.setBroadcastUri(uri); if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan); } else { userNetwork.setBroadcastDomainType(BroadcastDomainType.Native); } } else { if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!"); } URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString()); if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) { throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal + " and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType + " already exists or overlaps with other network pvlans in zone " + zoneId); } userNetwork.setBroadcastUri(uri); userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan); userNetwork.setPvlanType(isolatedPvlanType); } } final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, isDisplayNetworkEnabled); Network network = null; if (networks == null || networks.isEmpty()) { throw new CloudRuntimeException("Fail to create a network"); } else { if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { Network defaultGuestNetwork = networks.get(0); for (final Network nw : networks) { if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) { defaultGuestNetwork = nw; } } network = defaultGuestNetwork; } else { // For shared network network = networks.get(0); } } if (updateResourceCount) { _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled); } return network; } }); CallContext.current().setEventDetails("Network Id: " + network.getId()); CallContext.current().putContextParameter(Network.class, network.getUuid()); return network; }
@DB private Network createGuestNetwork(final long networkOfferingId, final String name, final String displayText, final String gateway, final String cidr, String vlanId, boolean bypassVlanOverlapCheck, String networkDomain, final Account owner, final Long domainId, final PhysicalNetwork pNtwk, final long zoneId, final ACLType aclType, Boolean subdomainAccess, final Long vpcId, final String ip6Gateway, final String ip6Cidr, final Boolean isDisplayNetworkEnabled, final String isolatedPvlan, Network.PVlanType isolatedPvlanType, String externalId, final Boolean isPrivateNetwork, String routerIp, String routerIpv6) throws ConcurrentOperationException, InsufficientCapacityException, ResourceAllocationException { final NetworkOfferingVO ntwkOff = _networkOfferingDao.findById(networkOfferingId); final DataCenterVO zone = _dcDao.findById(zoneId); if (ntwkOff.getTrafficType() != TrafficType.Guest) { s_logger.warn("Only guest networks can be created using this method"); return null; } final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType); if (updateResourceCount) { _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network, isDisplayNetworkEnabled); } if (ntwkOff.getState() != NetworkOffering.State.Enabled) { final InvalidParameterValueException ex = new InvalidParameterValueException("Can't use specified network offering id as its state is not " + NetworkOffering.State.Enabled); ex.addProxyObject(ntwkOff.getUuid(), "networkOfferingId"); throw ex; } if (pNtwk.getState() != PhysicalNetwork.State.Enabled) { final InvalidParameterValueException ex = new InvalidParameterValueException("Specified physical network id is" + " in incorrect state:" + pNtwk.getState()); ex.addProxyObject(pNtwk.getUuid(), "physicalNetworkId"); throw ex; } boolean ipv6 = false; if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) { ipv6 = true; } if (zone.getNetworkType() == NetworkType.Basic) { if (aclType == null || aclType != ACLType.Domain) { throw new InvalidParameterValueException("Only AclType=Domain can be specified for network creation in Basic zone"); } final List<NetworkVO> guestNetworks = _networksDao.listByZoneAndTrafficType(zone.getId(), TrafficType.Guest); if (!guestNetworks.isEmpty()) { throw new InvalidParameterValueException("Can't have more than one Guest network in zone with network type " + NetworkType.Basic); } if (!(ntwkOff.getGuestType() == GuestType.Shared && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))) { throw new InvalidParameterValueException("For zone of type " + NetworkType.Basic + " only offerings of " + "guestType " + GuestType.Shared + " with disabled " + Service.SourceNat.getName() + " service are allowed"); } if (domainId == null || domainId != Domain.ROOT_DOMAIN) { throw new InvalidParameterValueException("Guest network in Basic zone should be dedicated to ROOT domain"); } if (subdomainAccess == null) { subdomainAccess = true; } else if (!subdomainAccess) { throw new InvalidParameterValueException("Subdomain access should be set to true for the" + " guest network in the Basic zone"); } if (vlanId == null) { vlanId = Vlan.UNTAGGED; } else { if (!vlanId.equalsIgnoreCase(Vlan.UNTAGGED)) { throw new InvalidParameterValueException("Only vlan " + Vlan.UNTAGGED + " can be created in " + "the zone of type " + NetworkType.Basic); } } } else if (zone.getNetworkType() == NetworkType.Advanced) { if (zone.isSecurityGroupEnabled()) { if (isolatedPvlan != null) { throw new InvalidParameterValueException("Isolated Private VLAN is not supported with security group!"); } if (ntwkOff.getGuestType() != GuestType.Shared) { throw new InvalidParameterValueException("Only shared guest network can be created in security group enabled zone"); } if (_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat)) { throw new InvalidParameterValueException("Service SourceNat is not allowed in security group enabled zone"); } } if (ntwkOff.isElasticIp() || ntwkOff.isElasticLb()) { throw new InvalidParameterValueException("Elastic IP and Elastic LB services are supported in zone of type " + NetworkType.Basic); } } if (ipv6 && NetUtils.getIp6CidrSize(ip6Cidr) != 64) { throw new InvalidParameterValueException("IPv6 subnet should be exactly 64-bits in size"); } final boolean vlanSpecified = vlanId != null; if (vlanSpecified != ntwkOff.isSpecifyVlan()) { if (vlanSpecified) { throw new InvalidParameterValueException("Can't specify vlan; corresponding offering says specifyVlan=false"); } else { throw new InvalidParameterValueException("Vlan has to be specified; corresponding offering says specifyVlan=true"); } } if (vlanSpecified) { URI uri = encodeVlanIdIntoBroadcastUri(vlanId, pNtwk); URI secondaryUri = StringUtils.isNotBlank(isolatedPvlan) ? BroadcastDomainType.fromString(isolatedPvlan) : null; if (!(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(uri)).size() > 0) { throw new InvalidParameterValueException("The VLAN tag to use for new guest network, " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName()); } if (secondaryUri != null && !(bypassVlanOverlapCheck && ntwkOff.getGuestType() == GuestType.Shared) && _dcDao.findVnet(zoneId, pNtwk.getId(), BroadcastDomainType.getValue(secondaryUri)).size() > 0) { throw new InvalidParameterValueException("The VLAN tag for isolated PVLAN " + isolatedPvlan + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName()); } if (! UuidUtils.validateUUID(vlanId)){ if (!hasGuestBypassVlanOverlapCheck(bypassVlanOverlapCheck, ntwkOff, isPrivateNetwork)) { if (_networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), null).size() > 0) { throw new InvalidParameterValueException("Network with vlan " + vlanId + " already exists or overlaps with other network vlans in zone " + zoneId); } else if (secondaryUri != null && _networksDao.listByZoneAndUriAndGuestType(zoneId, secondaryUri.toString(), null).size() > 0) { throw new InvalidParameterValueException("Network with vlan " + isolatedPvlan + " already exists or overlaps with other network vlans in zone " + zoneId); } else { final List<DataCenterVnetVO> dcVnets = _datacenterVnetDao.findVnet(zoneId, BroadcastDomainType.getValue(uri)); if (!dcVnets.isEmpty()) { final DataCenterVnetVO dcVnet = dcVnets.get(0); if (dcVnet.getAccountGuestVlanMapId() != null) { final Long accountGuestVlanMapId = dcVnet.getAccountGuestVlanMapId(); final AccountGuestVlanMapVO map = _accountGuestVlanMapDao.findById(accountGuestVlanMapId); if (map.getAccountId() != owner.getAccountId()) { throw new InvalidParameterValueException("Vlan " + vlanId + " is dedicated to a different account"); } } else { final List<AccountGuestVlanMapVO> maps = _accountGuestVlanMapDao.listAccountGuestVlanMapsByAccount(owner.getAccountId()); if (maps != null && !maps.isEmpty()) { final int vnetsAllocatedToAccount = _datacenterVnetDao.countVnetsAllocatedToAccount(zoneId, owner.getAccountId()); final int vnetsDedicatedToAccount = _datacenterVnetDao.countVnetsDedicatedToAccount(zoneId, owner.getAccountId()); if (vnetsAllocatedToAccount < vnetsDedicatedToAccount) { throw new InvalidParameterValueException("Specified vlan " + vlanId + " doesn't belong" + " to the vlan range dedicated to the owner " + owner.getAccountName()); } } } } } } else { if (!bypassVlanOverlapCheck && _networksDao.listByZoneAndUriAndGuestType(zoneId, uri.toString(), GuestType.Isolated).size() > 0 ) { throw new InvalidParameterValueException("There is an existing isolated/shared network that overlaps with vlan id:" + vlanId + " in zone " + zoneId); } } } } if (_networkModel.areServicesSupportedByNetworkOffering(networkOfferingId, Service.Dns)) { final Map<Network.Capability, String> dnsCapabilities = _networkModel.getNetworkOfferingServiceCapabilities(_entityMgr.findById(NetworkOffering.class, networkOfferingId), Service.Dns); final String isUpdateDnsSupported = dnsCapabilities.get(Capability.AllowDnsSuffixModification); if (isUpdateDnsSupported == null || !Boolean.valueOf(isUpdateDnsSupported)) { if (networkDomain != null) { throw new InvalidParameterValueException("Domain name change is not supported by network offering id=" + networkOfferingId + " in zone id=" + zoneId); } } else { if (networkDomain == null) { if (aclType == ACLType.Domain) { networkDomain = _networkModel.getDomainNetworkDomain(domainId, zoneId); } else if (aclType == ACLType.Account) { networkDomain = _networkModel.getAccountNetworkDomain(owner.getId(), zoneId); } if (networkDomain == null) { networkDomain = "cs" + Long.toHexString(owner.getId()) + GuestDomainSuffix.valueIn(zoneId); } } else { if (!NetUtils.verifyDomainName(networkDomain)) { throw new InvalidParameterValueException("Invalid network domain. Total length shouldn't exceed 190 chars. Each domain " + "label must be between 1 and 63 characters long, can contain ASCII letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\""); } } } } final boolean cidrRequired = zone.getNetworkType() == NetworkType.Advanced && ntwkOff.getTrafficType() == TrafficType.Guest && (ntwkOff.getGuestType() == GuestType.Shared || (ntwkOff.getGuestType() == GuestType.Isolated && !_networkModel.areServicesSupportedByNetworkOffering(ntwkOff.getId(), Service.SourceNat))); if (cidr == null && ip6Cidr == null && cidrRequired) { if (ntwkOff.getGuestType() == GuestType.Shared) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask are required when create network of" + " type " + Network.GuestType.Shared); } else { throw new InvalidParameterValueException("gateway/netmask are required when create network of" + " type " + GuestType.Isolated + " with service " + Service.SourceNat.getName() + " disabled"); } } checkL2OfferingServices(ntwkOff); if (zone.getNetworkType() == NetworkType.Basic && cidr != null) { throw new InvalidParameterValueException("StartIp/endIp/gateway/netmask can't be specified for zone of type " + NetworkType.Basic); } if (cidr != null && ntwkOff.getGuestType() == Network.GuestType.Isolated && ntwkOff.getTrafficType() == TrafficType.Guest) { if (!NetUtils.validateGuestCidr(cidr)) { throw new InvalidParameterValueException("Virtual Guest Cidr " + cidr + " is not RFC 1918 or 6598 compliant"); } } final String networkDomainFinal = networkDomain; final String vlanIdFinal = vlanId; final Boolean subdomainAccessFinal = subdomainAccess; final Network network = Transaction.execute(new TransactionCallback<Network>() { @Override public Network doInTransaction(final TransactionStatus status) { Long physicalNetworkId = null; if (pNtwk != null) { physicalNetworkId = pNtwk.getId(); } final DataCenterDeployment plan = new DataCenterDeployment(zoneId, null, null, null, null, physicalNetworkId); final NetworkVO userNetwork = new NetworkVO(); userNetwork.setNetworkDomain(networkDomainFinal); if (cidr != null && gateway != null) { userNetwork.setCidr(cidr); userNetwork.setGateway(gateway); } if (StringUtils.isNoneBlank(ip6Gateway, ip6Cidr)) { userNetwork.setIp6Cidr(ip6Cidr); userNetwork.setIp6Gateway(ip6Gateway); } if (externalId != null) { userNetwork.setExternalId(externalId); } if (StringUtils.isNotBlank(routerIp)) { userNetwork.setRouterIp(routerIp); } if (StringUtils.isNotBlank(routerIpv6)) { userNetwork.setRouterIpv6(routerIpv6); } if (vlanIdFinal != null) { if (isolatedPvlan == null) { URI uri = null; if (UuidUtils.validateUUID(vlanIdFinal)){ userNetwork.setVlanIdAsUUID(vlanIdFinal); } else { uri = encodeVlanIdIntoBroadcastUri(vlanIdFinal, pNtwk); } if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString()).size() > 0) { throw new InvalidParameterValueException("Network with vlan " + vlanIdFinal + " already exists or overlaps with other network pvlans in zone " + zoneId); } userNetwork.setBroadcastUri(uri); if (!vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { userNetwork.setBroadcastDomainType(BroadcastDomainType.Vlan); } else { userNetwork.setBroadcastDomainType(BroadcastDomainType.Native); } } else { if (vlanIdFinal.equalsIgnoreCase(Vlan.UNTAGGED)) { throw new InvalidParameterValueException("Cannot support pvlan with untagged primary vlan!"); } URI uri = NetUtils.generateUriForPvlan(vlanIdFinal, isolatedPvlan, isolatedPvlanType.toString()); if (_networksDao.listByPhysicalNetworkPvlan(physicalNetworkId, uri.toString(), isolatedPvlanType).size() > 0) { throw new InvalidParameterValueException("Network with primary vlan " + vlanIdFinal + " and secondary vlan " + isolatedPvlan + " type " + isolatedPvlanType + " already exists or overlaps with other network pvlans in zone " + zoneId); } userNetwork.setBroadcastUri(uri); userNetwork.setBroadcastDomainType(BroadcastDomainType.Pvlan); userNetwork.setPvlanType(isolatedPvlanType); } } final List<? extends Network> networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, isDisplayNetworkEnabled); Network network = null; if (networks == null || networks.isEmpty()) { throw new CloudRuntimeException("Fail to create a network"); } else { if (networks.size() > 0 && networks.get(0).getGuestType() == Network.GuestType.Isolated && networks.get(0).getTrafficType() == TrafficType.Guest) { Network defaultGuestNetwork = networks.get(0); for (final Network nw : networks) { if (nw.getCidr() != null && nw.getCidr().equals(zone.getGuestNetworkCidr())) { defaultGuestNetwork = nw; } } network = defaultGuestNetwork; } else { network = networks.get(0); } } if (updateResourceCount) { _resourceLimitMgr.incrementResourceCount(owner.getId(), ResourceType.network, isDisplayNetworkEnabled); } return network; } }); CallContext.current().setEventDetails("Network Id: " + network.getId()); CallContext.current().putContextParameter(Network.class, network.getUuid()); return network; }
@db private network createguestnetwork(final long networkofferingid, final string name, final string displaytext, final string gateway, final string cidr, string vlanid, boolean bypassvlanoverlapcheck, string networkdomain, final account owner, final long domainid, final physicalnetwork pntwk, final long zoneid, final acltype acltype, boolean subdomainaccess, final long vpcid, final string ip6gateway, final string ip6cidr, final boolean isdisplaynetworkenabled, final string isolatedpvlan, network.pvlantype isolatedpvlantype, string externalid, final boolean isprivatenetwork, string routerip, string routeripv6) throws concurrentoperationexception, insufficientcapacityexception, resourceallocationexception { final networkofferingvo ntwkoff = _networkofferingdao.findbyid(networkofferingid); final datacentervo zone = _dcdao.findbyid(zoneid); if (ntwkoff.gettraffictype() != traffictype.guest) { s_logger.warn("only guest networks can be created using this method"); return null; } final boolean updateresourcecount = resourcecountneedsupdate(ntwkoff, acltype); if (updateresourcecount) { _resourcelimitmgr.checkresourcelimit(owner, resourcetype.network, isdisplaynetworkenabled); } if (ntwkoff.getstate() != networkoffering.state.enabled) { final invalidparametervalueexception ex = new invalidparametervalueexception("can't use specified network offering id as its state is not " + networkoffering.state.enabled); ex.addproxyobject(ntwkoff.getuuid(), "networkofferingid"); throw ex; } if (pntwk.getstate() != physicalnetwork.state.enabled) { final invalidparametervalueexception ex = new invalidparametervalueexception("specified physical network id is" + " in incorrect state:" + pntwk.getstate()); ex.addproxyobject(pntwk.getuuid(), "physicalnetworkid"); throw ex; } boolean ipv6 = false; if (stringutils.isnoneblank(ip6gateway, ip6cidr)) { ipv6 = true; } if (zone.getnetworktype() == networktype.basic) { if (acltype == null || acltype != acltype.domain) { throw new invalidparametervalueexception("only acltype=domain can be specified for network creation in basic zone"); } final list<networkvo> guestnetworks = _networksdao.listbyzoneandtraffictype(zone.getid(), traffictype.guest); if (!guestnetworks.isempty()) { throw new invalidparametervalueexception("can't have more than one guest network in zone with network type " + networktype.basic); } if (!(ntwkoff.getguesttype() == guesttype.shared && !_networkmodel.areservicessupportedbynetworkoffering(ntwkoff.getid(), service.sourcenat))) { throw new invalidparametervalueexception("for zone of type " + networktype.basic + " only offerings of " + "guesttype " + guesttype.shared + " with disabled " + service.sourcenat.getname() + " service are allowed"); } if (domainid == null || domainid != domain.root_domain) { throw new invalidparametervalueexception("guest network in basic zone should be dedicated to root domain"); } if (subdomainaccess == null) { subdomainaccess = true; } else if (!subdomainaccess) { throw new invalidparametervalueexception("subdomain access should be set to true for the" + " guest network in the basic zone"); } if (vlanid == null) { vlanid = vlan.untagged; } else { if (!vlanid.equalsignorecase(vlan.untagged)) { throw new invalidparametervalueexception("only vlan " + vlan.untagged + " can be created in " + "the zone of type " + networktype.basic); } } } else if (zone.getnetworktype() == networktype.advanced) { if (zone.issecuritygroupenabled()) { if (isolatedpvlan != null) { throw new invalidparametervalueexception("isolated private vlan is not supported with security group!"); } if (ntwkoff.getguesttype() != guesttype.shared) { throw new invalidparametervalueexception("only shared guest network can be created in security group enabled zone"); } if (_networkmodel.areservicessupportedbynetworkoffering(ntwkoff.getid(), service.sourcenat)) { throw new invalidparametervalueexception("service sourcenat is not allowed in security group enabled zone"); } } if (ntwkoff.iselasticip() || ntwkoff.iselasticlb()) { throw new invalidparametervalueexception("elastic ip and elastic lb services are supported in zone of type " + networktype.basic); } } if (ipv6 && netutils.getip6cidrsize(ip6cidr) != 64) { throw new invalidparametervalueexception("ipv6 subnet should be exactly 64-bits in size"); } final boolean vlanspecified = vlanid != null; if (vlanspecified != ntwkoff.isspecifyvlan()) { if (vlanspecified) { throw new invalidparametervalueexception("can't specify vlan; corresponding offering says specifyvlan=false"); } else { throw new invalidparametervalueexception("vlan has to be specified; corresponding offering says specifyvlan=true"); } } if (vlanspecified) { uri uri = encodevlanidintobroadcasturi(vlanid, pntwk); uri secondaryuri = stringutils.isnotblank(isolatedpvlan) ? broadcastdomaintype.fromstring(isolatedpvlan) : null; if (!(bypassvlanoverlapcheck && ntwkoff.getguesttype() == guesttype.shared) && _dcdao.findvnet(zoneid, pntwk.getid(), broadcastdomaintype.getvalue(uri)).size() > 0) { throw new invalidparametervalueexception("the vlan tag to use for new guest network, " + vlanid + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getname()); } if (secondaryuri != null && !(bypassvlanoverlapcheck && ntwkoff.getguesttype() == guesttype.shared) && _dcdao.findvnet(zoneid, pntwk.getid(), broadcastdomaintype.getvalue(secondaryuri)).size() > 0) { throw new invalidparametervalueexception("the vlan tag for isolated pvlan " + isolatedpvlan + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getname()); } if (! uuidutils.validateuuid(vlanid)){ if (!hasguestbypassvlanoverlapcheck(bypassvlanoverlapcheck, ntwkoff, isprivatenetwork)) { if (_networksdao.listbyzoneanduriandguesttype(zoneid, uri.tostring(), null).size() > 0) { throw new invalidparametervalueexception("network with vlan " + vlanid + " already exists or overlaps with other network vlans in zone " + zoneid); } else if (secondaryuri != null && _networksdao.listbyzoneanduriandguesttype(zoneid, secondaryuri.tostring(), null).size() > 0) { throw new invalidparametervalueexception("network with vlan " + isolatedpvlan + " already exists or overlaps with other network vlans in zone " + zoneid); } else { final list<datacentervnetvo> dcvnets = _datacentervnetdao.findvnet(zoneid, broadcastdomaintype.getvalue(uri)); if (!dcvnets.isempty()) { final datacentervnetvo dcvnet = dcvnets.get(0); if (dcvnet.getaccountguestvlanmapid() != null) { final long accountguestvlanmapid = dcvnet.getaccountguestvlanmapid(); final accountguestvlanmapvo map = _accountguestvlanmapdao.findbyid(accountguestvlanmapid); if (map.getaccountid() != owner.getaccountid()) { throw new invalidparametervalueexception("vlan " + vlanid + " is dedicated to a different account"); } } else { final list<accountguestvlanmapvo> maps = _accountguestvlanmapdao.listaccountguestvlanmapsbyaccount(owner.getaccountid()); if (maps != null && !maps.isempty()) { final int vnetsallocatedtoaccount = _datacentervnetdao.countvnetsallocatedtoaccount(zoneid, owner.getaccountid()); final int vnetsdedicatedtoaccount = _datacentervnetdao.countvnetsdedicatedtoaccount(zoneid, owner.getaccountid()); if (vnetsallocatedtoaccount < vnetsdedicatedtoaccount) { throw new invalidparametervalueexception("specified vlan " + vlanid + " doesn't belong" + " to the vlan range dedicated to the owner " + owner.getaccountname()); } } } } } } else { if (!bypassvlanoverlapcheck && _networksdao.listbyzoneanduriandguesttype(zoneid, uri.tostring(), guesttype.isolated).size() > 0 ) { throw new invalidparametervalueexception("there is an existing isolated/shared network that overlaps with vlan id:" + vlanid + " in zone " + zoneid); } } } } if (_networkmodel.areservicessupportedbynetworkoffering(networkofferingid, service.dns)) { final map<network.capability, string> dnscapabilities = _networkmodel.getnetworkofferingservicecapabilities(_entitymgr.findbyid(networkoffering.class, networkofferingid), service.dns); final string isupdatednssupported = dnscapabilities.get(capability.allowdnssuffixmodification); if (isupdatednssupported == null || !boolean.valueof(isupdatednssupported)) { if (networkdomain != null) { throw new invalidparametervalueexception("domain name change is not supported by network offering id=" + networkofferingid + " in zone id=" + zoneid); } } else { if (networkdomain == null) { if (acltype == acltype.domain) { networkdomain = _networkmodel.getdomainnetworkdomain(domainid, zoneid); } else if (acltype == acltype.account) { networkdomain = _networkmodel.getaccountnetworkdomain(owner.getid(), zoneid); } if (networkdomain == null) { networkdomain = "cs" + long.tohexstring(owner.getid()) + guestdomainsuffix.valuein(zoneid); } } else { if (!netutils.verifydomainname(networkdomain)) { throw new invalidparametervalueexception("invalid network domain. total length shouldn't exceed 190 chars. each domain " + "label must be between 1 and 63 characters long, can contain ascii letters 'a' through 'z', the digits '0' through '9', " + "and the hyphen ('-'); can't start or end with \"-\""); } } } } final boolean cidrrequired = zone.getnetworktype() == networktype.advanced && ntwkoff.gettraffictype() == traffictype.guest && (ntwkoff.getguesttype() == guesttype.shared || (ntwkoff.getguesttype() == guesttype.isolated && !_networkmodel.areservicessupportedbynetworkoffering(ntwkoff.getid(), service.sourcenat))); if (cidr == null && ip6cidr == null && cidrrequired) { if (ntwkoff.getguesttype() == guesttype.shared) { throw new invalidparametervalueexception("startip/endip/gateway/netmask are required when create network of" + " type " + network.guesttype.shared); } else { throw new invalidparametervalueexception("gateway/netmask are required when create network of" + " type " + guesttype.isolated + " with service " + service.sourcenat.getname() + " disabled"); } } checkl2offeringservices(ntwkoff); if (zone.getnetworktype() == networktype.basic && cidr != null) { throw new invalidparametervalueexception("startip/endip/gateway/netmask can't be specified for zone of type " + networktype.basic); } if (cidr != null && ntwkoff.getguesttype() == network.guesttype.isolated && ntwkoff.gettraffictype() == traffictype.guest) { if (!netutils.validateguestcidr(cidr)) { throw new invalidparametervalueexception("virtual guest cidr " + cidr + " is not rfc 1918 or 6598 compliant"); } } final string networkdomainfinal = networkdomain; final string vlanidfinal = vlanid; final boolean subdomainaccessfinal = subdomainaccess; final network network = transaction.execute(new transactioncallback<network>() { @override public network dointransaction(final transactionstatus status) { long physicalnetworkid = null; if (pntwk != null) { physicalnetworkid = pntwk.getid(); } final datacenterdeployment plan = new datacenterdeployment(zoneid, null, null, null, null, physicalnetworkid); final networkvo usernetwork = new networkvo(); usernetwork.setnetworkdomain(networkdomainfinal); if (cidr != null && gateway != null) { usernetwork.setcidr(cidr); usernetwork.setgateway(gateway); } if (stringutils.isnoneblank(ip6gateway, ip6cidr)) { usernetwork.setip6cidr(ip6cidr); usernetwork.setip6gateway(ip6gateway); } if (externalid != null) { usernetwork.setexternalid(externalid); } if (stringutils.isnotblank(routerip)) { usernetwork.setrouterip(routerip); } if (stringutils.isnotblank(routeripv6)) { usernetwork.setrouteripv6(routeripv6); } if (vlanidfinal != null) { if (isolatedpvlan == null) { uri uri = null; if (uuidutils.validateuuid(vlanidfinal)){ usernetwork.setvlanidasuuid(vlanidfinal); } else { uri = encodevlanidintobroadcasturi(vlanidfinal, pntwk); } if (_networksdao.listbyphysicalnetworkpvlan(physicalnetworkid, uri.tostring()).size() > 0) { throw new invalidparametervalueexception("network with vlan " + vlanidfinal + " already exists or overlaps with other network pvlans in zone " + zoneid); } usernetwork.setbroadcasturi(uri); if (!vlanidfinal.equalsignorecase(vlan.untagged)) { usernetwork.setbroadcastdomaintype(broadcastdomaintype.vlan); } else { usernetwork.setbroadcastdomaintype(broadcastdomaintype.native); } } else { if (vlanidfinal.equalsignorecase(vlan.untagged)) { throw new invalidparametervalueexception("cannot support pvlan with untagged primary vlan!"); } uri uri = netutils.generateuriforpvlan(vlanidfinal, isolatedpvlan, isolatedpvlantype.tostring()); if (_networksdao.listbyphysicalnetworkpvlan(physicalnetworkid, uri.tostring(), isolatedpvlantype).size() > 0) { throw new invalidparametervalueexception("network with primary vlan " + vlanidfinal + " and secondary vlan " + isolatedpvlan + " type " + isolatedpvlantype + " already exists or overlaps with other network pvlans in zone " + zoneid); } usernetwork.setbroadcasturi(uri); usernetwork.setbroadcastdomaintype(broadcastdomaintype.pvlan); usernetwork.setpvlantype(isolatedpvlantype); } } final list<? extends network> networks = setupnetwork(owner, ntwkoff, usernetwork, plan, name, displaytext, true, domainid, acltype, subdomainaccessfinal, vpcid, isdisplaynetworkenabled); network network = null; if (networks == null || networks.isempty()) { throw new cloudruntimeexception("fail to create a network"); } else { if (networks.size() > 0 && networks.get(0).getguesttype() == network.guesttype.isolated && networks.get(0).gettraffictype() == traffictype.guest) { network defaultguestnetwork = networks.get(0); for (final network nw : networks) { if (nw.getcidr() != null && nw.getcidr().equals(zone.getguestnetworkcidr())) { defaultguestnetwork = nw; } } network = defaultguestnetwork; } else { network = networks.get(0); } } if (updateresourcecount) { _resourcelimitmgr.incrementresourcecount(owner.getid(), resourcetype.network, isdisplaynetworkenabled); } return network; } }); callcontext.current().seteventdetails("network id: " + network.getid()); callcontext.current().putcontextparameter(network.class, network.getuuid()); return network; }
leolleeooleo/cloudstack
[ 1, 1, 0, 0 ]
25,403
public static String domToString(Document document) { Source source = new DOMSource(document); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys. INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1"); StringWriter sw=new StringWriter(); StreamResult resultStream = new StreamResult(sw); transformer.transform(source, resultStream); return sw.toString(); } catch (TransformerException e) { return e.toString(); } }
public static String domToString(Document document) { Source source = new DOMSource(document); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys. INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1"); StringWriter sw=new StringWriter(); StreamResult resultStream = new StreamResult(sw); transformer.transform(source, resultStream); return sw.toString(); } catch (TransformerException e) { return e.toString(); } }
public static string domtostring(document document) { source source = new domsource(document); try { transformerfactory factory = transformerfactory.newinstance(); transformer transformer = factory.newtransformer(); transformer.setoutputproperty(outputkeys. indent, "yes"); transformer.setoutputproperty("{http://xml.apache.org/xslt}indent-amount", "1"); stringwriter sw=new stringwriter(); streamresult resultstream = new streamresult(sw); transformer.transform(source, resultstream); return sw.tostring(); } catch (transformerexception e) { return e.tostring(); } }
mino98/stix
[ 1, 0, 0, 0 ]
25,580
private void deviceClientMonitorLoop() { do { try { // This synchronized block stops us from doing the select() if a new // Device is being added. // @see startMonitoringDevice() synchronized (mDevices) { } int count = mSelector.select(); if (mQuit) { return; } synchronized (mClientsToReopen) { if (mClientsToReopen.size() > 0) { Set<Client> clients = mClientsToReopen.keySet(); MonitorThread monitorThread = MonitorThread.getInstance(); for (Client client : clients) { Device device = client.getDeviceImpl(); int pid = client.getClientData().getPid(); monitorThread.dropClient(client, false /* notify */); // This is kinda bad, but if we don't wait a bit, the client // will never answer the second handshake! waitABit(); int port = mClientsToReopen.get(client); if (port == IDebugPortProvider.NO_STATIC_PORT) { port = getNextDebuggerPort(); } Log.d("DeviceMonitor", "Reopening " + client); openClient(device, pid, port, monitorThread); device.update(Device.CHANGE_CLIENT_LIST); } mClientsToReopen.clear(); } } if (count == 0) { continue; } Set<SelectionKey> keys = mSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isValid() && key.isReadable()) { Object attachment = key.attachment(); if (attachment instanceof Device) { Device device = (Device)attachment; SocketChannel socket = device.getClientMonitoringSocket(); if (socket != null) { try { int length = readLength(socket, mLengthBuffer2); processIncomingJdwpData(device, socket, length); } catch (IOException ioe) { Log.d("DeviceMonitor", "Error reading jdwp list: " + ioe.getMessage()); socket.close(); // restart the monitoring of that device synchronized (mDevices) { if (mDevices.contains(device)) { Log.d("DeviceMonitor", "Restarting monitoring service for " + device); startMonitoringDevice(device); } } } } } } } } catch (IOException e) { if (mQuit == false) { } } } while (mQuit == false); }
private void deviceClientMonitorLoop() { do { try { synchronized (mDevices) { } int count = mSelector.select(); if (mQuit) { return; } synchronized (mClientsToReopen) { if (mClientsToReopen.size() > 0) { Set<Client> clients = mClientsToReopen.keySet(); MonitorThread monitorThread = MonitorThread.getInstance(); for (Client client : clients) { Device device = client.getDeviceImpl(); int pid = client.getClientData().getPid(); monitorThread.dropClient(client, false); waitABit(); int port = mClientsToReopen.get(client); if (port == IDebugPortProvider.NO_STATIC_PORT) { port = getNextDebuggerPort(); } Log.d("DeviceMonitor", "Reopening " + client); openClient(device, pid, port, monitorThread); device.update(Device.CHANGE_CLIENT_LIST); } mClientsToReopen.clear(); } } if (count == 0) { continue; } Set<SelectionKey> keys = mSelector.selectedKeys(); Iterator<SelectionKey> iter = keys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isValid() && key.isReadable()) { Object attachment = key.attachment(); if (attachment instanceof Device) { Device device = (Device)attachment; SocketChannel socket = device.getClientMonitoringSocket(); if (socket != null) { try { int length = readLength(socket, mLengthBuffer2); processIncomingJdwpData(device, socket, length); } catch (IOException ioe) { Log.d("DeviceMonitor", "Error reading jdwp list: " + ioe.getMessage()); socket.close(); synchronized (mDevices) { if (mDevices.contains(device)) { Log.d("DeviceMonitor", "Restarting monitoring service for " + device); startMonitoringDevice(device); } } } } } } } } catch (IOException e) { if (mQuit == false) { } } } while (mQuit == false); }
private void deviceclientmonitorloop() { do { try { synchronized (mdevices) { } int count = mselector.select(); if (mquit) { return; } synchronized (mclientstoreopen) { if (mclientstoreopen.size() > 0) { set<client> clients = mclientstoreopen.keyset(); monitorthread monitorthread = monitorthread.getinstance(); for (client client : clients) { device device = client.getdeviceimpl(); int pid = client.getclientdata().getpid(); monitorthread.dropclient(client, false); waitabit(); int port = mclientstoreopen.get(client); if (port == idebugportprovider.no_static_port) { port = getnextdebuggerport(); } log.d("devicemonitor", "reopening " + client); openclient(device, pid, port, monitorthread); device.update(device.change_client_list); } mclientstoreopen.clear(); } } if (count == 0) { continue; } set<selectionkey> keys = mselector.selectedkeys(); iterator<selectionkey> iter = keys.iterator(); while (iter.hasnext()) { selectionkey key = iter.next(); iter.remove(); if (key.isvalid() && key.isreadable()) { object attachment = key.attachment(); if (attachment instanceof device) { device device = (device)attachment; socketchannel socket = device.getclientmonitoringsocket(); if (socket != null) { try { int length = readlength(socket, mlengthbuffer2); processincomingjdwpdata(device, socket, length); } catch (ioexception ioe) { log.d("devicemonitor", "error reading jdwp list: " + ioe.getmessage()); socket.close(); synchronized (mdevices) { if (mdevices.contains(device)) { log.d("devicemonitor", "restarting monitoring service for " + device); startmonitoringdevice(device); } } } } } } } } catch (ioexception e) { if (mquit == false) { } } } while (mquit == false); }
lrscp/ControlAndroidDeviceFromPC
[ 1, 0, 0, 0 ]
33,797
@POST @Path("/services") @Produces({ "application/json", "application/xml" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE + "\")") public RangerService createService(RangerService service) { if(LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.createService(" + service + ")"); } RangerService ret = null; RangerPerfTracer perf = null; try { if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createService(serviceName=" + service.getName() + ")"); } RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); validator.validate(service, Action.CREATE); UserSessionBase session = ContextUtil.getCurrentUserSession(); XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); if(session != null && !session.isSpnegoEnabled()){ bizUtil.hasAdminPermissions("Services"); // TODO: As of now we are allowing SYS_ADMIN to create all the // services including KMS bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); } if(session != null && session.isSpnegoEnabled()){ if (session.isKeyAdmin() && !xxServiceDef.getImplclassname().equals(EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { throw restErrorUtil.createRESTException("KeyAdmin can create/update/delete only KMS ", MessageEnums.OPER_NO_PERMISSION); } if ((!session.isKeyAdmin() && !session.isUserAdmin()) && xxServiceDef.getImplclassname().equals(EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { throw restErrorUtil.createRESTException("User cannot create/update/delete KMS Service", MessageEnums.OPER_NO_PERMISSION); } } ret = svcStore.createService(service); } catch(WebApplicationException excp) { throw excp; } catch(Throwable excp) { LOG.error("createService(" + service + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); } if(LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.createService(" + service + "): " + ret); } return ret; }
@POST @Path("/services") @Produces({ "application/json", "application/xml" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.CREATE_SERVICE + "\")") public RangerService createService(RangerService service) { if(LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.createService(" + service + ")"); } RangerService ret = null; RangerPerfTracer perf = null; try { if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.createService(serviceName=" + service.getName() + ")"); } RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); validator.validate(service, Action.CREATE); UserSessionBase session = ContextUtil.getCurrentUserSession(); XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); if(session != null && !session.isSpnegoEnabled()){ bizUtil.hasAdminPermissions("Services"); bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); } if(session != null && session.isSpnegoEnabled()){ if (session.isKeyAdmin() && !xxServiceDef.getImplclassname().equals(EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { throw restErrorUtil.createRESTException("KeyAdmin can create/update/delete only KMS ", MessageEnums.OPER_NO_PERMISSION); } if ((!session.isKeyAdmin() && !session.isUserAdmin()) && xxServiceDef.getImplclassname().equals(EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { throw restErrorUtil.createRESTException("User cannot create/update/delete KMS Service", MessageEnums.OPER_NO_PERMISSION); } } ret = svcStore.createService(service); } catch(WebApplicationException excp) { throw excp; } catch(Throwable excp) { LOG.error("createService(" + service + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); } if(LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.createService(" + service + "): " + ret); } return ret; }
@post @path("/services") @produces({ "application/json", "application/xml" }) @preauthorize("@rangerpreauthsecurityhandler.isapiaccessible(\"" + rangerapilist.create_service + "\")") public rangerservice createservice(rangerservice service) { if(log.isdebugenabled()) { log.debug("==> servicerest.createservice(" + service + ")"); } rangerservice ret = null; rangerperftracer perf = null; try { if(rangerperftracer.isperftraceenabled(perf_log)) { perf = rangerperftracer.getperftracer(perf_log, "servicerest.createservice(servicename=" + service.getname() + ")"); } rangerservicevalidator validator = validatorfactory.getservicevalidator(svcstore); validator.validate(service, action.create); usersessionbase session = contextutil.getcurrentusersession(); xxservicedef xxservicedef = daomanager.getxxservicedef().findbyname(service.gettype()); if(session != null && !session.isspnegoenabled()){ bizutil.hasadminpermissions("services"); bizutil.haskmspermissions("service", xxservicedef.getimplclassname()); } if(session != null && session.isspnegoenabled()){ if (session.iskeyadmin() && !xxservicedef.getimplclassname().equals(embeddedservicedefsutil.kms_impl_class_name)) { throw resterrorutil.createrestexception("keyadmin can create/update/delete only kms ", messageenums.oper_no_permission); } if ((!session.iskeyadmin() && !session.isuseradmin()) && xxservicedef.getimplclassname().equals(embeddedservicedefsutil.kms_impl_class_name)) { throw resterrorutil.createrestexception("user cannot create/update/delete kms service", messageenums.oper_no_permission); } } ret = svcstore.createservice(service); } catch(webapplicationexception excp) { throw excp; } catch(throwable excp) { log.error("createservice(" + service + ") failed", excp); throw resterrorutil.createrestexception(excp.getmessage()); } finally { rangerperftracer.log(perf); } if(log.isdebugenabled()) { log.debug("<== servicerest.createservice(" + service + "): " + ret); } return ret; }
lw-lin/incubator-ranger
[ 1, 0, 0, 0 ]
33,798
@PUT @Path("/services/{id}") @Produces({ "application/json", "application/xml" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE + "\")") public RangerService updateService(RangerService service) { if(LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.updateService(): " + service); } RangerService ret = null; RangerPerfTracer perf = null; try { if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updateService(serviceName=" + service.getName() + ")"); } RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); validator.validate(service, Action.UPDATE); bizUtil.hasAdminPermissions("Services"); // TODO: As of now we are allowing SYS_ADMIN to create all the // services including KMS XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); ret = svcStore.updateService(service); } catch(WebApplicationException excp) { throw excp; } catch(Throwable excp) { LOG.error("updateService(" + service + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); } if(LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.updateService(" + service + "): " + ret); } return ret; }
@PUT @Path("/services/{id}") @Produces({ "application/json", "application/xml" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.UPDATE_SERVICE + "\")") public RangerService updateService(RangerService service) { if(LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.updateService(): " + service); } RangerService ret = null; RangerPerfTracer perf = null; try { if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.updateService(serviceName=" + service.getName() + ")"); } RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); validator.validate(service, Action.UPDATE); bizUtil.hasAdminPermissions("Services"); XXServiceDef xxServiceDef = daoManager.getXXServiceDef().findByName(service.getType()); bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); ret = svcStore.updateService(service); } catch(WebApplicationException excp) { throw excp; } catch(Throwable excp) { LOG.error("updateService(" + service + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); } if(LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.updateService(" + service + "): " + ret); } return ret; }
@put @path("/services/{id}") @produces({ "application/json", "application/xml" }) @preauthorize("@rangerpreauthsecurityhandler.isapiaccessible(\"" + rangerapilist.update_service + "\")") public rangerservice updateservice(rangerservice service) { if(log.isdebugenabled()) { log.debug("==> servicerest.updateservice(): " + service); } rangerservice ret = null; rangerperftracer perf = null; try { if(rangerperftracer.isperftraceenabled(perf_log)) { perf = rangerperftracer.getperftracer(perf_log, "servicerest.updateservice(servicename=" + service.getname() + ")"); } rangerservicevalidator validator = validatorfactory.getservicevalidator(svcstore); validator.validate(service, action.update); bizutil.hasadminpermissions("services"); xxservicedef xxservicedef = daomanager.getxxservicedef().findbyname(service.gettype()); bizutil.haskmspermissions("service", xxservicedef.getimplclassname()); ret = svcstore.updateservice(service); } catch(webapplicationexception excp) { throw excp; } catch(throwable excp) { log.error("updateservice(" + service + ") failed", excp); throw resterrorutil.createrestexception(excp.getmessage()); } finally { rangerperftracer.log(perf); } if(log.isdebugenabled()) { log.debug("<== servicerest.updateservice(" + service + "): " + ret); } return ret; }
lw-lin/incubator-ranger
[ 1, 0, 0, 0 ]
33,799
@DELETE @Path("/services/{id}") @Produces({ "application/json", "application/xml" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE + "\")") public void deleteService(@PathParam("id") Long id) { if(LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.deleteService(" + id + ")"); } RangerPerfTracer perf = null; try { if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteService(serviceId=" + id + ")"); } RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); validator.validate(id, Action.DELETE); bizUtil.hasAdminPermissions("Services"); // TODO: As of now we are allowing SYS_ADMIN to create all the // services including KMS XXService service = daoManager.getXXService().getById(id); EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance(); if (service.getType().equals(embeddedServiceDefsUtil.getTagServiceDefId())){ List<XXService> referringServices=daoManager.getXXService().findByTagServiceId(id); if(!CollectionUtils.isEmpty(referringServices)){ Set<String> referringServiceNames=new HashSet<String>(); for(XXService xXService:referringServices){ referringServiceNames.add(xXService.getName()); if(referringServiceNames.size()>=10){ break; } } if(referringServices.size()<=10){ throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: "+referringServiceNames,MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); }else{ throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: "+referringServiceNames+" and more..",MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); } } } XXServiceDef xxServiceDef = daoManager.getXXServiceDef().getById(service.getType()); bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); tagStore.deleteAllTagObjectsForService(service.getName()); svcStore.deleteService(id); } catch(WebApplicationException excp) { throw excp; } catch(Throwable excp) { LOG.error("deleteService(" + id + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); } if(LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.deleteService(" + id + ")"); } }
@DELETE @Path("/services/{id}") @Produces({ "application/json", "application/xml" }) @PreAuthorize("@rangerPreAuthSecurityHandler.isAPIAccessible(\"" + RangerAPIList.DELETE_SERVICE + "\")") public void deleteService(@PathParam("id") Long id) { if(LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.deleteService(" + id + ")"); } RangerPerfTracer perf = null; try { if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteService(serviceId=" + id + ")"); } RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore); validator.validate(id, Action.DELETE); bizUtil.hasAdminPermissions("Services"); XXService service = daoManager.getXXService().getById(id); EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance(); if (service.getType().equals(embeddedServiceDefsUtil.getTagServiceDefId())){ List<XXService> referringServices=daoManager.getXXService().findByTagServiceId(id); if(!CollectionUtils.isEmpty(referringServices)){ Set<String> referringServiceNames=new HashSet<String>(); for(XXService xXService:referringServices){ referringServiceNames.add(xXService.getName()); if(referringServiceNames.size()>=10){ break; } } if(referringServices.size()<=10){ throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: "+referringServiceNames,MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); }else{ throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: "+referringServiceNames+" and more..",MessageEnums.OPER_NOT_ALLOWED_FOR_STATE); } } } XXServiceDef xxServiceDef = daoManager.getXXServiceDef().getById(service.getType()); bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname()); tagStore.deleteAllTagObjectsForService(service.getName()); svcStore.deleteService(id); } catch(WebApplicationException excp) { throw excp; } catch(Throwable excp) { LOG.error("deleteService(" + id + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } finally { RangerPerfTracer.log(perf); } if(LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.deleteService(" + id + ")"); } }
@delete @path("/services/{id}") @produces({ "application/json", "application/xml" }) @preauthorize("@rangerpreauthsecurityhandler.isapiaccessible(\"" + rangerapilist.delete_service + "\")") public void deleteservice(@pathparam("id") long id) { if(log.isdebugenabled()) { log.debug("==> servicerest.deleteservice(" + id + ")"); } rangerperftracer perf = null; try { if(rangerperftracer.isperftraceenabled(perf_log)) { perf = rangerperftracer.getperftracer(perf_log, "servicerest.deleteservice(serviceid=" + id + ")"); } rangerservicevalidator validator = validatorfactory.getservicevalidator(svcstore); validator.validate(id, action.delete); bizutil.hasadminpermissions("services"); xxservice service = daomanager.getxxservice().getbyid(id); embeddedservicedefsutil embeddedservicedefsutil = embeddedservicedefsutil.instance(); if (service.gettype().equals(embeddedservicedefsutil.gettagservicedefid())){ list<xxservice> referringservices=daomanager.getxxservice().findbytagserviceid(id); if(!collectionutils.isempty(referringservices)){ set<string> referringservicenames=new hashset<string>(); for(xxservice xxservice:referringservices){ referringservicenames.add(xxservice.getname()); if(referringservicenames.size()>=10){ break; } } if(referringservices.size()<=10){ throw resterrorutil.createrestexception("tag service '" + service.getname() + "' is being referenced by " + referringservices.size() + " services: "+referringservicenames,messageenums.oper_not_allowed_for_state); }else{ throw resterrorutil.createrestexception("tag service '" + service.getname() + "' is being referenced by " + referringservices.size() + " services: "+referringservicenames+" and more..",messageenums.oper_not_allowed_for_state); } } } xxservicedef xxservicedef = daomanager.getxxservicedef().getbyid(service.gettype()); bizutil.haskmspermissions("service", xxservicedef.getimplclassname()); tagstore.deletealltagobjectsforservice(service.getname()); svcstore.deleteservice(id); } catch(webapplicationexception excp) { throw excp; } catch(throwable excp) { log.error("deleteservice(" + id + ") failed", excp); throw resterrorutil.createrestexception(excp.getmessage()); } finally { rangerperftracer.log(perf); } if(log.isdebugenabled()) { log.debug("<== servicerest.deleteservice(" + id + ")"); } }
lw-lin/incubator-ranger
[ 1, 0, 0, 0 ]
9,239
@Issue("JENKINS-20415") @Test public void nonTopLevelItemGroup() throws Exception { MatrixProject mp = j.jenkins.createProject(MatrixProject.class, "mp"); mp.setAxes(new AxisList(new TextAxis("axis", "one", "two"))); assertEquals(2, mp.getItems().size()); ListView v = new ListView("v"); j.jenkins.addView(v); v.setIncludeRegex(".*"); v.setRecurse(true); // Note: did not manage to reproduce CCE until I changed expand to use ‘for (TopLevelItem item : items)’ rather than ‘for (Item item : items)’; perhaps a compiler-specific issue? assertEquals(Collections.singletonList(mp), v.getItems()); }
@Issue("JENKINS-20415") @Test public void nonTopLevelItemGroup() throws Exception { MatrixProject mp = j.jenkins.createProject(MatrixProject.class, "mp"); mp.setAxes(new AxisList(new TextAxis("axis", "one", "two"))); assertEquals(2, mp.getItems().size()); ListView v = new ListView("v"); j.jenkins.addView(v); v.setIncludeRegex(".*"); v.setRecurse(true); assertEquals(Collections.singletonList(mp), v.getItems()); }
@issue("jenkins-20415") @test public void nontoplevelitemgroup() throws exception { matrixproject mp = j.jenkins.createproject(matrixproject.class, "mp"); mp.setaxes(new axislist(new textaxis("axis", "one", "two"))); assertequals(2, mp.getitems().size()); listview v = new listview("v"); j.jenkins.addview(v); v.setincluderegex(".*"); v.setrecurse(true); assertequals(collections.singletonlist(mp), v.getitems()); }
mahevpm/Mahendran_Jenkins
[ 0, 0, 1, 0 ]
33,880
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { // TODO empty method, if you want to definition & registry , use it. }
@Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { }
@override public void postprocessbeandefinitionregistry(beandefinitionregistry beandefinitionregistry) throws beansexception { }
liuziyuan/retrofit-spring-boot-starter
[ 0, 1, 0, 0 ]
33,901
@Ignore // todo: test case for https://github.com/jhy/jsoup/issues/845. Doesn't work yet. @Test public void handlesMisnestedAInDivs() { String h = "<a href='#1'><div><div><a href='#2'>child</a</div</div></a>"; String w = "<a href=\"#1\"></a><div><a href=\"#1\"></a><div><a href=\"#1\"></a><a href=\"#2\">child</a></div></div>"; Document doc = Jsoup.parse(h); assertEquals( StringUtil.normaliseWhitespace(w), StringUtil.normaliseWhitespace(doc.body().html())); }
@Ignore @Test public void handlesMisnestedAInDivs() { String h = "<a href='#1'><div><div><a href='#2'>child</a</div</div></a>"; String w = "<a href=\"#1\"></a><div><a href=\"#1\"></a><div><a href=\"#1\"></a><a href=\"#2\">child</a></div></div>"; Document doc = Jsoup.parse(h); assertEquals( StringUtil.normaliseWhitespace(w), StringUtil.normaliseWhitespace(doc.body().html())); }
@ignore @test public void handlesmisnestedaindivs() { string h = "<a href='#1'><div><div><a href='#2'>child</a</div</div></a>"; string w = "<a href=\"#1\"></a><div><a href=\"#1\"></a><div><a href=\"#1\"></a><a href=\"#2\">child</a></div></div>"; document doc = jsoup.parse(h); assertequals( stringutil.normalisewhitespace(w), stringutil.normalisewhitespace(doc.body().html())); }
mikiec84/jsoup
[ 0, 0, 0, 1 ]
1,139
private void transformTimeSeries(String metricName, AnomalyDetectionContext anomalyDetectionContext) { // Transform the observed (current) time series if (anomalyDetectionContext.getTransformedCurrent(metricName) == null) { anomalyDetectionContext.setTransformedCurrent(metricName, anomalyDetectionContext.getCurrent(metricName)); } List<TransformationFunction> currentTimeSeriesTransformationChain = getCurrentTimeSeriesTransformationChain(); if (CollectionUtils.isNotEmpty(currentTimeSeriesTransformationChain)) { for (TransformationFunction tf : currentTimeSeriesTransformationChain) { anomalyDetectionContext .setTransformedCurrent(metricName, tf.transform(anomalyDetectionContext.getTransformedCurrent(metricName), anomalyDetectionContext)); } } // Transform baseline time series if (anomalyDetectionContext.getTransformedBaselines(metricName) == null) { anomalyDetectionContext.setTransformedBaselines(metricName, anomalyDetectionContext.getBaselines(metricName)); } List<TransformationFunction> baselineTimeSeriesTransformationChain = getBaselineTimeSeriesTransformationChain(); if (CollectionUtils.isNotEmpty(anomalyDetectionContext.getTransformedBaselines(metricName)) && CollectionUtils.isNotEmpty(baselineTimeSeriesTransformationChain)) { for (TransformationFunction tf : baselineTimeSeriesTransformationChain) { List<TimeSeries> transformedBaselines = new ArrayList<>(); for (TimeSeries ts : anomalyDetectionContext.getTransformedBaselines(metricName)) { TimeSeries transformedTS = tf.transform(ts, anomalyDetectionContext); transformedBaselines.add(transformedTS); } anomalyDetectionContext.setTransformedBaselines(metricName, transformedBaselines); } } }
private void transformTimeSeries(String metricName, AnomalyDetectionContext anomalyDetectionContext) { if (anomalyDetectionContext.getTransformedCurrent(metricName) == null) { anomalyDetectionContext.setTransformedCurrent(metricName, anomalyDetectionContext.getCurrent(metricName)); } List<TransformationFunction> currentTimeSeriesTransformationChain = getCurrentTimeSeriesTransformationChain(); if (CollectionUtils.isNotEmpty(currentTimeSeriesTransformationChain)) { for (TransformationFunction tf : currentTimeSeriesTransformationChain) { anomalyDetectionContext .setTransformedCurrent(metricName, tf.transform(anomalyDetectionContext.getTransformedCurrent(metricName), anomalyDetectionContext)); } } if (anomalyDetectionContext.getTransformedBaselines(metricName) == null) { anomalyDetectionContext.setTransformedBaselines(metricName, anomalyDetectionContext.getBaselines(metricName)); } List<TransformationFunction> baselineTimeSeriesTransformationChain = getBaselineTimeSeriesTransformationChain(); if (CollectionUtils.isNotEmpty(anomalyDetectionContext.getTransformedBaselines(metricName)) && CollectionUtils.isNotEmpty(baselineTimeSeriesTransformationChain)) { for (TransformationFunction tf : baselineTimeSeriesTransformationChain) { List<TimeSeries> transformedBaselines = new ArrayList<>(); for (TimeSeries ts : anomalyDetectionContext.getTransformedBaselines(metricName)) { TimeSeries transformedTS = tf.transform(ts, anomalyDetectionContext); transformedBaselines.add(transformedTS); } anomalyDetectionContext.setTransformedBaselines(metricName, transformedBaselines); } } }
private void transformtimeseries(string metricname, anomalydetectioncontext anomalydetectioncontext) { if (anomalydetectioncontext.gettransformedcurrent(metricname) == null) { anomalydetectioncontext.settransformedcurrent(metricname, anomalydetectioncontext.getcurrent(metricname)); } list<transformationfunction> currenttimeseriestransformationchain = getcurrenttimeseriestransformationchain(); if (collectionutils.isnotempty(currenttimeseriestransformationchain)) { for (transformationfunction tf : currenttimeseriestransformationchain) { anomalydetectioncontext .settransformedcurrent(metricname, tf.transform(anomalydetectioncontext.gettransformedcurrent(metricname), anomalydetectioncontext)); } } if (anomalydetectioncontext.gettransformedbaselines(metricname) == null) { anomalydetectioncontext.settransformedbaselines(metricname, anomalydetectioncontext.getbaselines(metricname)); } list<transformationfunction> baselinetimeseriestransformationchain = getbaselinetimeseriestransformationchain(); if (collectionutils.isnotempty(anomalydetectioncontext.gettransformedbaselines(metricname)) && collectionutils.isnotempty(baselinetimeseriestransformationchain)) { for (transformationfunction tf : baselinetimeseriestransformationchain) { list<timeseries> transformedbaselines = new arraylist<>(); for (timeseries ts : anomalydetectioncontext.gettransformedbaselines(metricname)) { timeseries transformedts = tf.transform(ts, anomalydetectioncontext); transformedbaselines.add(transformedts); } anomalydetectioncontext.settransformedbaselines(metricname, transformedbaselines); } } }
kupl/starlab-benchmarks
[ 0, 1, 0, 0 ]
17,582
@Override public void onManifest(String contentId, MediaPresentationDescription manifest) { Handler mainHandler = player.getMainHandler(); LoadControl loadControl = new DefaultLoadControl(new BufferPool(BUFFER_SEGMENT_SIZE)); DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(mainHandler, player); // Obtain Representations for playback. int maxDecodableFrameSize = MediaCodecUtil.maxH264DecodableFrameSize(); ArrayList<Representation> audioRepresentationsList = new ArrayList<Representation>(); ArrayList<Representation> videoRepresentationsList = new ArrayList<Representation>(); Period period = manifest.periods.get(0); boolean hasContentProtection = false; for (int i = 0; i < period.adaptationSets.size(); i++) { AdaptationSet adaptationSet = period.adaptationSets.get(i); hasContentProtection |= adaptationSet.hasContentProtection(); int adaptationSetType = adaptationSet.type; for (int j = 0; j < adaptationSet.representations.size(); j++) { Representation representation = adaptationSet.representations.get(j); if (adaptationSetType == AdaptationSet.TYPE_AUDIO) { audioRepresentationsList.add(representation); } else if (adaptationSetType == AdaptationSet.TYPE_VIDEO) { Format format = representation.format; if (format.width * format.height <= maxDecodableFrameSize) { videoRepresentationsList.add(representation); } else { // The device isn't capable of playing this stream. } } } } Representation[] videoRepresentations = new Representation[videoRepresentationsList.size()]; videoRepresentationsList.toArray(videoRepresentations); // Check drm support if necessary. DrmSessionManager drmSessionManager = null; if (hasContentProtection) { if (Util.SDK_INT < 18) { callback.onRenderersError(new UnsupportedOperationException( "Protected content not supported on API level " + Util.SDK_INT)); return; } try { Pair<DrmSessionManager, Boolean> drmSessionManagerData = V18Compat.getDrmSessionManagerData(player, drmCallback); drmSessionManager = drmSessionManagerData.first; if (!drmSessionManagerData.second) { // HD streams require L1 security. videoRepresentations = getSdRepresentations(videoRepresentations); } } catch (Exception e) { callback.onRenderersError(e); return; } } // Build the video renderer. DataSource videoDataSource = new HttpDataSource(userAgent, null, bandwidthMeter); ChunkSource videoChunkSource; String mimeType = videoRepresentations[0].format.mimeType; if (mimeType.equals(MimeTypes.VIDEO_MP4)) { videoChunkSource = new DashMp4ChunkSource(videoDataSource, new AdaptiveEvaluator(bandwidthMeter), videoRepresentations); } else if (mimeType.equals(MimeTypes.VIDEO_WEBM)) { // TODO: Figure out how to query supported vpX resolutions. For now, restrict to standard // definition streams. videoRepresentations = getSdRepresentations(videoRepresentations); videoChunkSource = new DashWebmChunkSource(videoDataSource, new AdaptiveEvaluator(bandwidthMeter), videoRepresentations); } else { throw new IllegalStateException("Unexpected mime type: " + mimeType); } ChunkSampleSource videoSampleSource = new ChunkSampleSource(videoChunkSource, loadControl, VIDEO_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, true, mainHandler, player, DemoPlayer.TYPE_VIDEO); MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(videoSampleSource, drmSessionManager, true, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT, 5000, mainHandler, player, 50); // Build the audio renderer. final String[] audioTrackNames; final MultiTrackChunkSource audioChunkSource; final MediaCodecAudioTrackRenderer audioRenderer; if (audioRepresentationsList.isEmpty()) { audioTrackNames = null; audioChunkSource = null; audioRenderer = null; } else { DataSource audioDataSource = new HttpDataSource(userAgent, null, bandwidthMeter); audioTrackNames = new String[audioRepresentationsList.size()]; ChunkSource[] audioChunkSources = new ChunkSource[audioRepresentationsList.size()]; FormatEvaluator audioEvaluator = new FormatEvaluator.FixedEvaluator(); for (int i = 0; i < audioRepresentationsList.size(); i++) { Representation representation = audioRepresentationsList.get(i); Format format = representation.format; audioTrackNames[i] = format.id + " (" + format.numChannels + "ch, " + format.audioSamplingRate + "Hz)"; audioChunkSources[i] = new DashMp4ChunkSource(audioDataSource, audioEvaluator, representation); } audioChunkSource = new MultiTrackChunkSource(audioChunkSources); SampleSource audioSampleSource = new ChunkSampleSource(audioChunkSource, loadControl, AUDIO_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, true, mainHandler, player, DemoPlayer.TYPE_AUDIO); audioRenderer = new MediaCodecAudioTrackRenderer(audioSampleSource, drmSessionManager, true, mainHandler, player); } // Build the debug renderer. TrackRenderer debugRenderer = debugTextView != null ? new DebugTrackRenderer(debugTextView, videoRenderer, videoSampleSource) : null; // Invoke the callback. String[][] trackNames = new String[DemoPlayer.RENDERER_COUNT][]; trackNames[DemoPlayer.TYPE_AUDIO] = audioTrackNames; MultiTrackChunkSource[] multiTrackChunkSources = new MultiTrackChunkSource[DemoPlayer.RENDERER_COUNT]; multiTrackChunkSources[DemoPlayer.TYPE_AUDIO] = audioChunkSource; TrackRenderer[] renderers = new TrackRenderer[DemoPlayer.RENDERER_COUNT]; renderers[DemoPlayer.TYPE_VIDEO] = videoRenderer; renderers[DemoPlayer.TYPE_AUDIO] = audioRenderer; renderers[DemoPlayer.TYPE_DEBUG] = debugRenderer; callback.onRenderers(trackNames, multiTrackChunkSources, renderers); }
@Override public void onManifest(String contentId, MediaPresentationDescription manifest) { Handler mainHandler = player.getMainHandler(); LoadControl loadControl = new DefaultLoadControl(new BufferPool(BUFFER_SEGMENT_SIZE)); DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(mainHandler, player); int maxDecodableFrameSize = MediaCodecUtil.maxH264DecodableFrameSize(); ArrayList<Representation> audioRepresentationsList = new ArrayList<Representation>(); ArrayList<Representation> videoRepresentationsList = new ArrayList<Representation>(); Period period = manifest.periods.get(0); boolean hasContentProtection = false; for (int i = 0; i < period.adaptationSets.size(); i++) { AdaptationSet adaptationSet = period.adaptationSets.get(i); hasContentProtection |= adaptationSet.hasContentProtection(); int adaptationSetType = adaptationSet.type; for (int j = 0; j < adaptationSet.representations.size(); j++) { Representation representation = adaptationSet.representations.get(j); if (adaptationSetType == AdaptationSet.TYPE_AUDIO) { audioRepresentationsList.add(representation); } else if (adaptationSetType == AdaptationSet.TYPE_VIDEO) { Format format = representation.format; if (format.width * format.height <= maxDecodableFrameSize) { videoRepresentationsList.add(representation); } else { } } } } Representation[] videoRepresentations = new Representation[videoRepresentationsList.size()]; videoRepresentationsList.toArray(videoRepresentations); DrmSessionManager drmSessionManager = null; if (hasContentProtection) { if (Util.SDK_INT < 18) { callback.onRenderersError(new UnsupportedOperationException( "Protected content not supported on API level " + Util.SDK_INT)); return; } try { Pair<DrmSessionManager, Boolean> drmSessionManagerData = V18Compat.getDrmSessionManagerData(player, drmCallback); drmSessionManager = drmSessionManagerData.first; if (!drmSessionManagerData.second) { videoRepresentations = getSdRepresentations(videoRepresentations); } } catch (Exception e) { callback.onRenderersError(e); return; } } DataSource videoDataSource = new HttpDataSource(userAgent, null, bandwidthMeter); ChunkSource videoChunkSource; String mimeType = videoRepresentations[0].format.mimeType; if (mimeType.equals(MimeTypes.VIDEO_MP4)) { videoChunkSource = new DashMp4ChunkSource(videoDataSource, new AdaptiveEvaluator(bandwidthMeter), videoRepresentations); } else if (mimeType.equals(MimeTypes.VIDEO_WEBM)) { videoRepresentations = getSdRepresentations(videoRepresentations); videoChunkSource = new DashWebmChunkSource(videoDataSource, new AdaptiveEvaluator(bandwidthMeter), videoRepresentations); } else { throw new IllegalStateException("Unexpected mime type: " + mimeType); } ChunkSampleSource videoSampleSource = new ChunkSampleSource(videoChunkSource, loadControl, VIDEO_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, true, mainHandler, player, DemoPlayer.TYPE_VIDEO); MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(videoSampleSource, drmSessionManager, true, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT, 5000, mainHandler, player, 50); final String[] audioTrackNames; final MultiTrackChunkSource audioChunkSource; final MediaCodecAudioTrackRenderer audioRenderer; if (audioRepresentationsList.isEmpty()) { audioTrackNames = null; audioChunkSource = null; audioRenderer = null; } else { DataSource audioDataSource = new HttpDataSource(userAgent, null, bandwidthMeter); audioTrackNames = new String[audioRepresentationsList.size()]; ChunkSource[] audioChunkSources = new ChunkSource[audioRepresentationsList.size()]; FormatEvaluator audioEvaluator = new FormatEvaluator.FixedEvaluator(); for (int i = 0; i < audioRepresentationsList.size(); i++) { Representation representation = audioRepresentationsList.get(i); Format format = representation.format; audioTrackNames[i] = format.id + " (" + format.numChannels + "ch, " + format.audioSamplingRate + "Hz)"; audioChunkSources[i] = new DashMp4ChunkSource(audioDataSource, audioEvaluator, representation); } audioChunkSource = new MultiTrackChunkSource(audioChunkSources); SampleSource audioSampleSource = new ChunkSampleSource(audioChunkSource, loadControl, AUDIO_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, true, mainHandler, player, DemoPlayer.TYPE_AUDIO); audioRenderer = new MediaCodecAudioTrackRenderer(audioSampleSource, drmSessionManager, true, mainHandler, player); } TrackRenderer debugRenderer = debugTextView != null ? new DebugTrackRenderer(debugTextView, videoRenderer, videoSampleSource) : null; String[][] trackNames = new String[DemoPlayer.RENDERER_COUNT][]; trackNames[DemoPlayer.TYPE_AUDIO] = audioTrackNames; MultiTrackChunkSource[] multiTrackChunkSources = new MultiTrackChunkSource[DemoPlayer.RENDERER_COUNT]; multiTrackChunkSources[DemoPlayer.TYPE_AUDIO] = audioChunkSource; TrackRenderer[] renderers = new TrackRenderer[DemoPlayer.RENDERER_COUNT]; renderers[DemoPlayer.TYPE_VIDEO] = videoRenderer; renderers[DemoPlayer.TYPE_AUDIO] = audioRenderer; renderers[DemoPlayer.TYPE_DEBUG] = debugRenderer; callback.onRenderers(trackNames, multiTrackChunkSources, renderers); }
@override public void onmanifest(string contentid, mediapresentationdescription manifest) { handler mainhandler = player.getmainhandler(); loadcontrol loadcontrol = new defaultloadcontrol(new bufferpool(buffer_segment_size)); defaultbandwidthmeter bandwidthmeter = new defaultbandwidthmeter(mainhandler, player); int maxdecodableframesize = mediacodecutil.maxh264decodableframesize(); arraylist<representation> audiorepresentationslist = new arraylist<representation>(); arraylist<representation> videorepresentationslist = new arraylist<representation>(); period period = manifest.periods.get(0); boolean hascontentprotection = false; for (int i = 0; i < period.adaptationsets.size(); i++) { adaptationset adaptationset = period.adaptationsets.get(i); hascontentprotection |= adaptationset.hascontentprotection(); int adaptationsettype = adaptationset.type; for (int j = 0; j < adaptationset.representations.size(); j++) { representation representation = adaptationset.representations.get(j); if (adaptationsettype == adaptationset.type_audio) { audiorepresentationslist.add(representation); } else if (adaptationsettype == adaptationset.type_video) { format format = representation.format; if (format.width * format.height <= maxdecodableframesize) { videorepresentationslist.add(representation); } else { } } } } representation[] videorepresentations = new representation[videorepresentationslist.size()]; videorepresentationslist.toarray(videorepresentations); drmsessionmanager drmsessionmanager = null; if (hascontentprotection) { if (util.sdk_int < 18) { callback.onrendererserror(new unsupportedoperationexception( "protected content not supported on api level " + util.sdk_int)); return; } try { pair<drmsessionmanager, boolean> drmsessionmanagerdata = v18compat.getdrmsessionmanagerdata(player, drmcallback); drmsessionmanager = drmsessionmanagerdata.first; if (!drmsessionmanagerdata.second) { videorepresentations = getsdrepresentations(videorepresentations); } } catch (exception e) { callback.onrendererserror(e); return; } } datasource videodatasource = new httpdatasource(useragent, null, bandwidthmeter); chunksource videochunksource; string mimetype = videorepresentations[0].format.mimetype; if (mimetype.equals(mimetypes.video_mp4)) { videochunksource = new dashmp4chunksource(videodatasource, new adaptiveevaluator(bandwidthmeter), videorepresentations); } else if (mimetype.equals(mimetypes.video_webm)) { videorepresentations = getsdrepresentations(videorepresentations); videochunksource = new dashwebmchunksource(videodatasource, new adaptiveevaluator(bandwidthmeter), videorepresentations); } else { throw new illegalstateexception("unexpected mime type: " + mimetype); } chunksamplesource videosamplesource = new chunksamplesource(videochunksource, loadcontrol, video_buffer_segments * buffer_segment_size, true, mainhandler, player, demoplayer.type_video); mediacodecvideotrackrenderer videorenderer = new mediacodecvideotrackrenderer(videosamplesource, drmsessionmanager, true, mediacodec.video_scaling_mode_scale_to_fit, 5000, mainhandler, player, 50); final string[] audiotracknames; final multitrackchunksource audiochunksource; final mediacodecaudiotrackrenderer audiorenderer; if (audiorepresentationslist.isempty()) { audiotracknames = null; audiochunksource = null; audiorenderer = null; } else { datasource audiodatasource = new httpdatasource(useragent, null, bandwidthmeter); audiotracknames = new string[audiorepresentationslist.size()]; chunksource[] audiochunksources = new chunksource[audiorepresentationslist.size()]; formatevaluator audioevaluator = new formatevaluator.fixedevaluator(); for (int i = 0; i < audiorepresentationslist.size(); i++) { representation representation = audiorepresentationslist.get(i); format format = representation.format; audiotracknames[i] = format.id + " (" + format.numchannels + "ch, " + format.audiosamplingrate + "hz)"; audiochunksources[i] = new dashmp4chunksource(audiodatasource, audioevaluator, representation); } audiochunksource = new multitrackchunksource(audiochunksources); samplesource audiosamplesource = new chunksamplesource(audiochunksource, loadcontrol, audio_buffer_segments * buffer_segment_size, true, mainhandler, player, demoplayer.type_audio); audiorenderer = new mediacodecaudiotrackrenderer(audiosamplesource, drmsessionmanager, true, mainhandler, player); } trackrenderer debugrenderer = debugtextview != null ? new debugtrackrenderer(debugtextview, videorenderer, videosamplesource) : null; string[][] tracknames = new string[demoplayer.renderer_count][]; tracknames[demoplayer.type_audio] = audiotracknames; multitrackchunksource[] multitrackchunksources = new multitrackchunksource[demoplayer.renderer_count]; multitrackchunksources[demoplayer.type_audio] = audiochunksource; trackrenderer[] renderers = new trackrenderer[demoplayer.renderer_count]; renderers[demoplayer.type_video] = videorenderer; renderers[demoplayer.type_audio] = audiorenderer; renderers[demoplayer.type_debug] = debugrenderer; callback.onrenderers(tracknames, multitrackchunksources, renderers); }
malmstein/ExoPlayer
[ 1, 0, 0, 0 ]
17,679
public void onFinished(JavaScriptObject jso) { applFormItems.clear(); applFormItems.addAll(JsonUtils.<ApplicationFormItemWithPrefilledValue>jsoAsList(jso)); applFormGenerators.clear(); if (applFormItems == null || applFormItems.isEmpty()) { // when there are no application form items FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon()) + ApplicationMessages.INSTANCE.noFormDefined()); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); contents.setWidget(ft); } else if (PerunEntity.VIRTUAL_ORGANIZATION.equals(entity) && "EXTENSION".equalsIgnoreCase(type) && Location.getParameter("targetexisting") != null) { // FIXME - this is probably not good, since it prevents vo extension when targetexisting is specified. if (Location.getParameter("targetexisting") != null) { Location.replace(Location.getParameter("targetexisting")); } // when there are no application form items FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon()) + ApplicationMessages.INSTANCE.alreadyVoMember()); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); contents.setWidget(ft); } else { // create application form prepareApplicationForm(); } session.getUiElements().setLogText("Loading " + type + " application form items in selected VO finished:" + applFormItems.size()); events.onFinished(jso); loaderImage.loadingFinished(); }
public void onFinished(JavaScriptObject jso) { applFormItems.clear(); applFormItems.addAll(JsonUtils.<ApplicationFormItemWithPrefilledValue>jsoAsList(jso)); applFormGenerators.clear(); if (applFormItems == null || applFormItems.isEmpty()) { FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon()) + ApplicationMessages.INSTANCE.noFormDefined()); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); contents.setWidget(ft); } else if (PerunEntity.VIRTUAL_ORGANIZATION.equals(entity) && "EXTENSION".equalsIgnoreCase(type) && Location.getParameter("targetexisting") != null) { if (Location.getParameter("targetexisting") != null) { Location.replace(Location.getParameter("targetexisting")); } FlexTable ft = new FlexTable(); ft.setSize("100%", "300px"); ft.setHTML(0, 0, new Image(LargeIcons.INSTANCE.errorIcon()) + ApplicationMessages.INSTANCE.alreadyVoMember()); ft.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER); ft.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_MIDDLE); contents.setWidget(ft); } else { prepareApplicationForm(); } session.getUiElements().setLogText("Loading " + type + " application form items in selected VO finished:" + applFormItems.size()); events.onFinished(jso); loaderImage.loadingFinished(); }
public void onfinished(javascriptobject jso) { applformitems.clear(); applformitems.addall(jsonutils.<applicationformitemwithprefilledvalue>jsoaslist(jso)); applformgenerators.clear(); if (applformitems == null || applformitems.isempty()) { flextable ft = new flextable(); ft.setsize("100%", "300px"); ft.sethtml(0, 0, new image(largeicons.instance.erroricon()) + applicationmessages.instance.noformdefined()); ft.getflexcellformatter().sethorizontalalignment(0, 0, hashorizontalalignment.align_center); ft.getflexcellformatter().setverticalalignment(0, 0, hasverticalalignment.align_middle); contents.setwidget(ft); } else if (perunentity.virtual_organization.equals(entity) && "extension".equalsignorecase(type) && location.getparameter("targetexisting") != null) { if (location.getparameter("targetexisting") != null) { location.replace(location.getparameter("targetexisting")); } flextable ft = new flextable(); ft.setsize("100%", "300px"); ft.sethtml(0, 0, new image(largeicons.instance.erroricon()) + applicationmessages.instance.alreadyvomember()); ft.getflexcellformatter().sethorizontalalignment(0, 0, hashorizontalalignment.align_center); ft.getflexcellformatter().setverticalalignment(0, 0, hasverticalalignment.align_middle); contents.setwidget(ft); } else { prepareapplicationform(); } session.getuielements().setlogtext("loading " + type + " application form items in selected vo finished:" + applformitems.size()); events.onfinished(jso); loaderimage.loadingfinished(); }
licehammer/perun
[ 0, 0, 1, 0 ]
9,531
private PathFormula withCorrectionTermsAndPC( Block pBlock, FormulaManagerView pFmgr, BooleanFormulaManagerView pBfmgr, BitvectorFormulaManagerView pBvfmgr, PathFormulaManager pPfmgr, CFA pCFA) { BooleanFormula extendedBlockFormula = pBlock.getFormula(); PathFormula unprimedBlockContext = pBlock.getUnprimedContext(); PathFormula primedBlockContext = pBlock.getPrimedContext(); SSAMap unprimedSSAMap = unprimedBlockContext.getSsa(); SSAMap primedSSAMap = primedBlockContext.getSsa(); for (String varName : programVariableNames) { // Add general correction v_1 = v_max if v is not in block formula (= not in primed context), if (!primedSSAMap.containsVariable(varName)) { BooleanFormula correctionterm = pBvfmgr.equal( makeVar(pPfmgr, pFmgr, this.unprimedContext, varName, STANDARD_UNPRIMED_SSA), makeVar(pPfmgr, pFmgr, this.primedContext, varName, highestSSA)); extendedBlockFormula = pBfmgr.and(extendedBlockFormula, correctionterm); } else { // Add low correction v_1 = v_? if unprimed context for v has higher index (? > 1). if (unprimedSSAMap.containsVariable(varName) && unprimedSSAMap.getIndex(varName) > STANDARD_UNPRIMED_SSA) { BooleanFormula correctionterm = pBvfmgr.equal( makeVar(pPfmgr, pFmgr, unprimedBlockContext, varName, STANDARD_UNPRIMED_SSA), makeVar( pPfmgr, pFmgr, unprimedBlockContext, varName, unprimedSSAMap.getIndex(varName))); extendedBlockFormula = pBfmgr.and(extendedBlockFormula, correctionterm); } // Add high correction v_? = v_max if primed context for v has lower index (? < max) if (primedSSAMap.getIndex(varName) < highestSSA) { BooleanFormula correctionterm = pBvfmgr.equal( makeVar( pPfmgr, pFmgr, primedBlockContext, varName, primedSSAMap.getIndex(varName)), makeVar(pPfmgr, pFmgr, primedBlockContext, varName, highestSSA)); extendedBlockFormula = pBfmgr.and(extendedBlockFormula, correctionterm); } } } // Add program counter int predID = getID(pBlock.getPredecessorLocation()); int succID = getID(pBlock.getSuccessorLocation()); BooleanFormula pcBefore = pFmgr.instantiate( makeProgramcounterFormula(predID, pBvfmgr, pCFA), SSAMap.emptySSAMap().withDefault(STANDARD_UNPRIMED_SSA)); BooleanFormula pcAfter = pFmgr.instantiate( makeProgramcounterFormula(succID, pBvfmgr, pCFA), SSAMap.emptySSAMap().withDefault(PC_PRIMED_SSA)); extendedBlockFormula = pBfmgr.and(pcBefore, extendedBlockFormula, pcAfter); @SuppressWarnings("deprecation") // TODO: seems buggy because it implicitly combines extendedBlockFormula and // primedContext.getSsa() with PointerTargetSet of primedBlockContext, is this correct? PathFormula pathFormula = pPfmgr.makeNewPathFormula( primedBlockContext.updateFormula(extendedBlockFormula), this.primedContext.getSsa()); return pathFormula; }
private PathFormula withCorrectionTermsAndPC( Block pBlock, FormulaManagerView pFmgr, BooleanFormulaManagerView pBfmgr, BitvectorFormulaManagerView pBvfmgr, PathFormulaManager pPfmgr, CFA pCFA) { BooleanFormula extendedBlockFormula = pBlock.getFormula(); PathFormula unprimedBlockContext = pBlock.getUnprimedContext(); PathFormula primedBlockContext = pBlock.getPrimedContext(); SSAMap unprimedSSAMap = unprimedBlockContext.getSsa(); SSAMap primedSSAMap = primedBlockContext.getSsa(); for (String varName : programVariableNames) { if (!primedSSAMap.containsVariable(varName)) { BooleanFormula correctionterm = pBvfmgr.equal( makeVar(pPfmgr, pFmgr, this.unprimedContext, varName, STANDARD_UNPRIMED_SSA), makeVar(pPfmgr, pFmgr, this.primedContext, varName, highestSSA)); extendedBlockFormula = pBfmgr.and(extendedBlockFormula, correctionterm); } else { if (unprimedSSAMap.containsVariable(varName) && unprimedSSAMap.getIndex(varName) > STANDARD_UNPRIMED_SSA) { BooleanFormula correctionterm = pBvfmgr.equal( makeVar(pPfmgr, pFmgr, unprimedBlockContext, varName, STANDARD_UNPRIMED_SSA), makeVar( pPfmgr, pFmgr, unprimedBlockContext, varName, unprimedSSAMap.getIndex(varName))); extendedBlockFormula = pBfmgr.and(extendedBlockFormula, correctionterm); } if (primedSSAMap.getIndex(varName) < highestSSA) { BooleanFormula correctionterm = pBvfmgr.equal( makeVar( pPfmgr, pFmgr, primedBlockContext, varName, primedSSAMap.getIndex(varName)), makeVar(pPfmgr, pFmgr, primedBlockContext, varName, highestSSA)); extendedBlockFormula = pBfmgr.and(extendedBlockFormula, correctionterm); } } } int predID = getID(pBlock.getPredecessorLocation()); int succID = getID(pBlock.getSuccessorLocation()); BooleanFormula pcBefore = pFmgr.instantiate( makeProgramcounterFormula(predID, pBvfmgr, pCFA), SSAMap.emptySSAMap().withDefault(STANDARD_UNPRIMED_SSA)); BooleanFormula pcAfter = pFmgr.instantiate( makeProgramcounterFormula(succID, pBvfmgr, pCFA), SSAMap.emptySSAMap().withDefault(PC_PRIMED_SSA)); extendedBlockFormula = pBfmgr.and(pcBefore, extendedBlockFormula, pcAfter); @SuppressWarnings("deprecation") PathFormula pathFormula = pPfmgr.makeNewPathFormula( primedBlockContext.updateFormula(extendedBlockFormula), this.primedContext.getSsa()); return pathFormula; }
private pathformula withcorrectiontermsandpc( block pblock, formulamanagerview pfmgr, booleanformulamanagerview pbfmgr, bitvectorformulamanagerview pbvfmgr, pathformulamanager ppfmgr, cfa pcfa) { booleanformula extendedblockformula = pblock.getformula(); pathformula unprimedblockcontext = pblock.getunprimedcontext(); pathformula primedblockcontext = pblock.getprimedcontext(); ssamap unprimedssamap = unprimedblockcontext.getssa(); ssamap primedssamap = primedblockcontext.getssa(); for (string varname : programvariablenames) { if (!primedssamap.containsvariable(varname)) { booleanformula correctionterm = pbvfmgr.equal( makevar(ppfmgr, pfmgr, this.unprimedcontext, varname, standard_unprimed_ssa), makevar(ppfmgr, pfmgr, this.primedcontext, varname, highestssa)); extendedblockformula = pbfmgr.and(extendedblockformula, correctionterm); } else { if (unprimedssamap.containsvariable(varname) && unprimedssamap.getindex(varname) > standard_unprimed_ssa) { booleanformula correctionterm = pbvfmgr.equal( makevar(ppfmgr, pfmgr, unprimedblockcontext, varname, standard_unprimed_ssa), makevar( ppfmgr, pfmgr, unprimedblockcontext, varname, unprimedssamap.getindex(varname))); extendedblockformula = pbfmgr.and(extendedblockformula, correctionterm); } if (primedssamap.getindex(varname) < highestssa) { booleanformula correctionterm = pbvfmgr.equal( makevar( ppfmgr, pfmgr, primedblockcontext, varname, primedssamap.getindex(varname)), makevar(ppfmgr, pfmgr, primedblockcontext, varname, highestssa)); extendedblockformula = pbfmgr.and(extendedblockformula, correctionterm); } } } int predid = getid(pblock.getpredecessorlocation()); int succid = getid(pblock.getsuccessorlocation()); booleanformula pcbefore = pfmgr.instantiate( makeprogramcounterformula(predid, pbvfmgr, pcfa), ssamap.emptyssamap().withdefault(standard_unprimed_ssa)); booleanformula pcafter = pfmgr.instantiate( makeprogramcounterformula(succid, pbvfmgr, pcfa), ssamap.emptyssamap().withdefault(pc_primed_ssa)); extendedblockformula = pbfmgr.and(pcbefore, extendedblockformula, pcafter); @suppresswarnings("deprecation") pathformula pathformula = ppfmgr.makenewpathformula( primedblockcontext.updateformula(extendedblockformula), this.primedcontext.getssa()); return pathformula; }
lembergerth/cpachecker
[ 0, 0, 1, 0 ]
1,459
@Test public void testPredicateTypeMismatch() { try (LocalQueryRunner queryRunner = createLocalQueryRunner( getMockApplyRedirectAfterPredicatePushdown(TYPE_MISMATCHED_REDIRECTION_MAPPING_BC, Optional.of(ImmutableSet.of(SOURCE_COLUMN_HANDLE_B))), Optional.of(this::mockApplyProjection), Optional.of(getMockApplyFilter(ImmutableSet.of(SOURCE_COLUMN_HANDLE_C))))) { // After 'source_col_c = 1' is pushed into source table scan, it's possible for 'source_col_c' table scan assignment to be pruned // Redirection results in Project('dest_col_b') -> Filter('dest_col_c = 1') -> TableScan for such case // but dest_col_a has mismatched type compared to source domain transaction(queryRunner.getTransactionManager(), queryRunner.getAccessControl()) .execute(MOCK_SESSION, session -> { assertThatThrownBy(() -> queryRunner.createPlan(session, "SELECT source_col_b FROM test_table WHERE source_col_c = 'foo'", WarningCollector.NOOP)) .isInstanceOf(TrinoException.class) // TODO report source column name instead of ColumnHandle toString .hasMessageMatching("Redirected column mock_catalog.target_schema.target_table.destination_col_a has type integer, " + "different from source column mock_catalog.test_schema.test_table.MockConnectorColumnHandle.*source_col_c.* type: varchar"); }); } }
@Test public void testPredicateTypeMismatch() { try (LocalQueryRunner queryRunner = createLocalQueryRunner( getMockApplyRedirectAfterPredicatePushdown(TYPE_MISMATCHED_REDIRECTION_MAPPING_BC, Optional.of(ImmutableSet.of(SOURCE_COLUMN_HANDLE_B))), Optional.of(this::mockApplyProjection), Optional.of(getMockApplyFilter(ImmutableSet.of(SOURCE_COLUMN_HANDLE_C))))) { transaction(queryRunner.getTransactionManager(), queryRunner.getAccessControl()) .execute(MOCK_SESSION, session -> { assertThatThrownBy(() -> queryRunner.createPlan(session, "SELECT source_col_b FROM test_table WHERE source_col_c = 'foo'", WarningCollector.NOOP)) .isInstanceOf(TrinoException.class) .hasMessageMatching("Redirected column mock_catalog.target_schema.target_table.destination_col_a has type integer, " + "different from source column mock_catalog.test_schema.test_table.MockConnectorColumnHandle.*source_col_c.* type: varchar"); }); } }
@test public void testpredicatetypemismatch() { try (localqueryrunner queryrunner = createlocalqueryrunner( getmockapplyredirectafterpredicatepushdown(type_mismatched_redirection_mapping_bc, optional.of(immutableset.of(source_column_handle_b))), optional.of(this::mockapplyprojection), optional.of(getmockapplyfilter(immutableset.of(source_column_handle_c))))) { transaction(queryrunner.gettransactionmanager(), queryrunner.getaccesscontrol()) .execute(mock_session, session -> { assertthatthrownby(() -> queryrunner.createplan(session, "select source_col_b from test_table where source_col_c = 'foo'", warningcollector.noop)) .isinstanceof(trinoexception.class) .hasmessagematching("redirected column mock_catalog.target_schema.target_table.destination_col_a has type integer, " + "different from source column mock_catalog.test_schema.test_table.mockconnectorcolumnhandle.*source_col_c.* type: varchar"); }); } }
liujiansxcd/trino
[ 1, 0, 0, 0 ]
34,339
private void createRowFactory(){ //Play selected song from playlist, to skip forward or back tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { //On double click of song, play it if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } //On right click open context menu if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } //Allow for removal of selected songs from playlist removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); //Allow for clearing entire playlist clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); //Show context menu at location of click playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } //Undo selection if user clicks away from focused row if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); //TODO: Add drag listener to move songs around as desired }
private void createRowFactory(){ tableView.setRowFactory( tv -> { TableRow<PlaylistSongDisplay> row = new TableRow<>(); row.setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (! row.isEmpty()) ) { playlist.playPlaylistSelection(songHashMap.get(row.getItem())); } if (event.getButton() == MouseButton.SECONDARY) { ObservableList<PlaylistSongDisplay> selectedItems = tableView.getSelectionModel().getSelectedItems(); ArrayList<Song> selectedIDs = new ArrayList<>(); for (PlaylistSongDisplay rowSelected : selectedItems) { selectedIDs.add(songHashMap.get(rowSelected)); } removeSelected.setOnAction((actionEvent -> { playlist.removePlaylistSelection(selectedIDs); for (Song s: selectedIDs){ playlistList.remove(songHashMapRev.get(s)); } })); clearPlaylist.setOnAction(actionEvent -> { playlist.clearPlaylist(); emptyTable(); }); playlistContextMenu.show(row, event.getScreenX(), event.getScreenY()); } if (event.getButton() == MouseButton.PRIMARY && (row.isEmpty())){ tableView.getSelectionModel().clearSelection(); } }); return row; }); }
private void createrowfactory(){ tableview.setrowfactory( tv -> { tablerow<playlistsongdisplay> row = new tablerow<>(); row.setonmouseclicked(event -> { if (event.getclickcount() == 2 && (! row.isempty()) ) { playlist.playplaylistselection(songhashmap.get(row.getitem())); } if (event.getbutton() == mousebutton.secondary) { observablelist<playlistsongdisplay> selecteditems = tableview.getselectionmodel().getselecteditems(); arraylist<song> selectedids = new arraylist<>(); for (playlistsongdisplay rowselected : selecteditems) { selectedids.add(songhashmap.get(rowselected)); } removeselected.setonaction((actionevent -> { playlist.removeplaylistselection(selectedids); for (song s: selectedids){ playlistlist.remove(songhashmaprev.get(s)); } })); clearplaylist.setonaction(actionevent -> { playlist.clearplaylist(); emptytable(); }); playlistcontextmenu.show(row, event.getscreenx(), event.getscreeny()); } if (event.getbutton() == mousebutton.primary && (row.isempty())){ tableview.getselectionmodel().clearselection(); } }); return row; }); }
justinlautner/Cassette
[ 0, 1, 0, 0 ]
34,410
@Override public void suspend() { // TODO unsubscribe from everything? And resubscribe on resume? super.suspend(); if (executor != null) executor.shutdownNow(); executorQueued.set(false); }
@Override public void suspend() { super.suspend(); if (executor != null) executor.shutdownNow(); executorQueued.set(false); }
@override public void suspend() { super.suspend(); if (executor != null) executor.shutdownnow(); executorqueued.set(false); }
kiuby88/incubator-brooklyn
[ 1, 0, 0, 0 ]
1,656
private void onSessionError(final int sessionId) { // TODO(qinmin): pass the error code to native. mHandler.post(new Runnable() { @Override public void run() { nativeOnSessionError(mNativeMediaDrmBridge, sessionId); } }); }
private void onSessionError(final int sessionId) { mHandler.post(new Runnable() { @Override public void run() { nativeOnSessionError(mNativeMediaDrmBridge, sessionId); } }); }
private void onsessionerror(final int sessionid) { mhandler.post(new runnable() { @override public void run() { nativeonsessionerror(mnativemediadrmbridge, sessionid); } }); }
kjthegod/chromium
[ 0, 1, 0, 0 ]
18,096
@SuppressWarnings("unchecked") public static void SetPageFacet(int facetType, String facetName, long delay) { FacesContext context = FacesContext.getCurrentInstance(); Map viewScope = context.getViewRoot().getViewMap(); String previousFacet = ""; String selectedFacet = ""; try { switch (facetType) { case 1:// Login previousFacet = "previousLoginFacet"; selectedFacet = "selectedLoginFacet"; break; case 2:// Home previousFacet = "previousHomeFacet"; selectedFacet = "selectedHomeFacet"; break; case 3:// FormPlaceholderFacet previousFacet = "previousFormPlaceholderFacet"; selectedFacet = "selectedFormPlaceholderFacet"; break; } if (facetName.equals("Previous")) { SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay); } else if (!facetName.equals(viewScope.get(selectedFacet))) { if (delay > 0) { Thread.currentThread(); Thread.sleep(delay); } viewScope.put(previousFacet, viewScope.get(selectedFacet)); viewScope.put(selectedFacet, facetName); } } catch (InterruptedException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") public static void SetPageFacet(int facetType, String facetName, long delay) { FacesContext context = FacesContext.getCurrentInstance(); Map viewScope = context.getViewRoot().getViewMap(); String previousFacet = ""; String selectedFacet = ""; try { switch (facetType) { case 1 previousFacet = "previousLoginFacet"; selectedFacet = "selectedLoginFacet"; break; case 2 previousFacet = "previousHomeFacet"; selectedFacet = "selectedHomeFacet"; break; case 3 previousFacet = "previousFormPlaceholderFacet"; selectedFacet = "selectedFormPlaceholderFacet"; break; } if (facetName.equals("Previous")) { SetPageFacet(facetType, viewScope.get(previousFacet).toString(), delay); } else if (!facetName.equals(viewScope.get(selectedFacet))) { if (delay > 0) { Thread.currentThread(); Thread.sleep(delay); } viewScope.put(previousFacet, viewScope.get(selectedFacet)); viewScope.put(selectedFacet, facetName); } } catch (InterruptedException e) { e.printStackTrace(); } }
@suppresswarnings("unchecked") public static void setpagefacet(int facettype, string facetname, long delay) { facescontext context = facescontext.getcurrentinstance(); map viewscope = context.getviewroot().getviewmap(); string previousfacet = ""; string selectedfacet = ""; try { switch (facettype) { case 1 previousfacet = "previousloginfacet"; selectedfacet = "selectedloginfacet"; break; case 2 previousfacet = "previoushomefacet"; selectedfacet = "selectedhomefacet"; break; case 3 previousfacet = "previousformplaceholderfacet"; selectedfacet = "selectedformplaceholderfacet"; break; } if (facetname.equals("previous")) { setpagefacet(facettype, viewscope.get(previousfacet).tostring(), delay); } else if (!facetname.equals(viewscope.get(selectedfacet))) { if (delay > 0) { thread.currentthread(); thread.sleep(delay); } viewscope.put(previousfacet, viewscope.get(selectedfacet)); viewscope.put(selectedfacet, facetname); } } catch (interruptedexception e) { e.printstacktrace(); } }
johnjardin/ukuvuma-xpages-boilerplate
[ 1, 0, 0, 0 ]
9,907
public static List<String> contentPrefixList(int flags) { final List<String> contentPrefixList = new ArrayList<String>(); if ((flags & JMF) != 0) { contentPrefixList.add("javax"); contentPrefixList.add("com.sun"); contentPrefixList.add("com.ibm"); } if ((flags & FMJ_NATIVE) != 0) { if (OSUtils.isMacOSX() || OSUtils.isWindows()) { // Quicktime: contentPrefixList.add("net.sf.fmj.qt"); } if (OSUtils.isWindows()) { // DirectShow: contentPrefixList.add("net.sf.fmj.ds"); } if (ENABLE_GSTREAMER && OSUtils.isLinux()) { // TODO: we could add these for other OS's, as gstreamer is cross-platform. // DirectShow: contentPrefixList.add("net.sf.fmj.gst"); } } if ((flags & FMJ) != 0) { contentPrefixList.add("net.sf.fmj"); } if ((flags & THIRD_PARTY) != 0) { // none to add } return contentPrefixList; }
public static List<String> contentPrefixList(int flags) { final List<String> contentPrefixList = new ArrayList<String>(); if ((flags & JMF) != 0) { contentPrefixList.add("javax"); contentPrefixList.add("com.sun"); contentPrefixList.add("com.ibm"); } if ((flags & FMJ_NATIVE) != 0) { if (OSUtils.isMacOSX() || OSUtils.isWindows()) { contentPrefixList.add("net.sf.fmj.qt"); } if (OSUtils.isWindows()) { contentPrefixList.add("net.sf.fmj.ds"); } if (ENABLE_GSTREAMER && OSUtils.isLinux()) { contentPrefixList.add("net.sf.fmj.gst"); } } if ((flags & FMJ) != 0) { contentPrefixList.add("net.sf.fmj"); } if ((flags & THIRD_PARTY) != 0) { } return contentPrefixList; }
public static list<string> contentprefixlist(int flags) { final list<string> contentprefixlist = new arraylist<string>(); if ((flags & jmf) != 0) { contentprefixlist.add("javax"); contentprefixlist.add("com.sun"); contentprefixlist.add("com.ibm"); } if ((flags & fmj_native) != 0) { if (osutils.ismacosx() || osutils.iswindows()) { contentprefixlist.add("net.sf.fmj.qt"); } if (osutils.iswindows()) { contentprefixlist.add("net.sf.fmj.ds"); } if (enable_gstreamer && osutils.islinux()) { contentprefixlist.add("net.sf.fmj.gst"); } } if ((flags & fmj) != 0) { contentprefixlist.add("net.sf.fmj"); } if ((flags & third_party) != 0) { } return contentprefixlist; }
licaon-kter/atalk-android
[ 0, 1, 0, 0 ]
26,295
@Test(groups = "slow", enabled = false) public void testOverdueStateAndWRITTEN_OFFTag() throws Exception { // TODO add/remove tag to invoice }
@Test(groups = "slow", enabled = false) public void testOverdueStateAndWRITTEN_OFFTag() throws Exception { }
@test(groups = "slow", enabled = false) public void testoverduestateandwritten_offtag() throws exception { }
kevinpostlewaite/killbill
[ 0, 1, 0, 0 ]
26,312
private String getServerUrl(OpenAPI openAPI, String pathInfo) { // TO-DO rethink how to manage multiple servers final String firstServer = openAPIUtils.mapServersToEndpoint(openAPI.getServers()).get(0); final String apiIdentifier = apiManagerService.getApiIdentifier(pathInfo); final String swaggerPath = pathInfo.substring(pathInfo.indexOf(apiIdentifier) + apiIdentifier.length(), pathInfo.length()); return firstServer + swaggerPath; }
private String getServerUrl(OpenAPI openAPI, String pathInfo) { final String firstServer = openAPIUtils.mapServersToEndpoint(openAPI.getServers()).get(0); final String apiIdentifier = apiManagerService.getApiIdentifier(pathInfo); final String swaggerPath = pathInfo.substring(pathInfo.indexOf(apiIdentifier) + apiIdentifier.length(), pathInfo.length()); return firstServer + swaggerPath; }
private string getserverurl(openapi openapi, string pathinfo) { final string firstserver = openapiutils.mapserverstoendpoint(openapi.getservers()).get(0); final string apiidentifier = apimanagerservice.getapiidentifier(pathinfo); final string swaggerpath = pathinfo.substring(pathinfo.indexof(apiidentifier) + apiidentifier.length(), pathinfo.length()); return firstserver + swaggerpath; }
marrmartin/onesaitplatform-cloud
[ 1, 0, 0, 0 ]
34,553
@PostConstruct public void setup(){ //Do not use getClass() here... a typical weld issue... endpointUrl=appConfiguration.getBaseEndpoint() + BulkWebService.class.getAnnotation(Path.class).value(); availableMethods= Arrays.asList(Verb.values()); usersEndpoint=userWS.getEndpointUrl(); groupsEndpoint=groupWS.getEndpointUrl(); fidodevicesEndpoint=fidoDeviceWS.getEndpointUrl(); commonWsEndpointPrefix=usersEndpoint.substring(0, usersEndpoint.lastIndexOf("/")); }
@PostConstruct public void setup(){ endpointUrl=appConfiguration.getBaseEndpoint() + BulkWebService.class.getAnnotation(Path.class).value(); availableMethods= Arrays.asList(Verb.values()); usersEndpoint=userWS.getEndpointUrl(); groupsEndpoint=groupWS.getEndpointUrl(); fidodevicesEndpoint=fidoDeviceWS.getEndpointUrl(); commonWsEndpointPrefix=usersEndpoint.substring(0, usersEndpoint.lastIndexOf("/")); }
@postconstruct public void setup(){ endpointurl=appconfiguration.getbaseendpoint() + bulkwebservice.class.getannotation(path.class).value(); availablemethods= arrays.aslist(verb.values()); usersendpoint=userws.getendpointurl(); groupsendpoint=groupws.getendpointurl(); fidodevicesendpoint=fidodevicews.getendpointurl(); commonwsendpointprefix=usersendpoint.substring(0, usersendpoint.lastindexof("/")); }
linosgian/oxTrust
[ 1, 0, 0, 0 ]
10,032
private void onNetBegin( BeginFW begin) { final long sequence = begin.sequence(); final long acknowledge = begin.acknowledge(); final int maximum = begin.maximum(); final long traceId = begin.traceId(); final long authorization = begin.authorization(); final long affinity = begin.affinity(); assert acknowledge <= sequence; assert sequence >= replySeq; assert acknowledge <= replyAck; replySeq = sequence; replyAck = acknowledge; assert replyAck == replySeq; assert maximum == 0; boolean handshakeHashOK = false; final OctetsFW extension = begin.extension(); if (extension.sizeof() != 0) { // TODO: need lightweight approach (start) final HttpBeginExFW httpBeginEx = extension.get(httpBeginExRO::wrap); final Map<String, String> headers = new LinkedHashMap<>(); httpBeginEx.headers().forEach(header -> { final String name = header.name().asString(); final String value = header.value().asString(); headers.merge(name, value, (v1, v2) -> String.format("%s, %s", v1, v2)); }); final String status = headers.get(":status"); final String upgrade = headers.get("upgrade"); final String hash = headers.get("sec-websocket-accept"); final String protocol = headers.get("sec-websocket-protocol"); // TODO: need lightweight approach (end) if (WEBSOCKET_STATUS.equals(status) && WEBSOCKET_UPGRADE.equals(upgrade) && Objects.equals(this.protocol, protocol)) { sha1.reset(); sha1.update(key.getBytes(US_ASCII)); final byte[] digest = sha1.digest(HANDSHAKE_GUID); final Encoder encoder = Base64.getEncoder(); final String handshakeHash = new String(encoder.encode(digest), US_ASCII); handshakeHashOK = handshakeHash.equals(hash); } } if (handshakeHashOK) { doAppBegin(maximum, traceId, authorization, affinity); } else { doAppReset(traceId, authorization); } }
private void onNetBegin( BeginFW begin) { final long sequence = begin.sequence(); final long acknowledge = begin.acknowledge(); final int maximum = begin.maximum(); final long traceId = begin.traceId(); final long authorization = begin.authorization(); final long affinity = begin.affinity(); assert acknowledge <= sequence; assert sequence >= replySeq; assert acknowledge <= replyAck; replySeq = sequence; replyAck = acknowledge; assert replyAck == replySeq; assert maximum == 0; boolean handshakeHashOK = false; final OctetsFW extension = begin.extension(); if (extension.sizeof() != 0) { final HttpBeginExFW httpBeginEx = extension.get(httpBeginExRO::wrap); final Map<String, String> headers = new LinkedHashMap<>(); httpBeginEx.headers().forEach(header -> { final String name = header.name().asString(); final String value = header.value().asString(); headers.merge(name, value, (v1, v2) -> String.format("%s, %s", v1, v2)); }); final String status = headers.get(":status"); final String upgrade = headers.get("upgrade"); final String hash = headers.get("sec-websocket-accept"); final String protocol = headers.get("sec-websocket-protocol"); if (WEBSOCKET_STATUS.equals(status) && WEBSOCKET_UPGRADE.equals(upgrade) && Objects.equals(this.protocol, protocol)) { sha1.reset(); sha1.update(key.getBytes(US_ASCII)); final byte[] digest = sha1.digest(HANDSHAKE_GUID); final Encoder encoder = Base64.getEncoder(); final String handshakeHash = new String(encoder.encode(digest), US_ASCII); handshakeHashOK = handshakeHash.equals(hash); } } if (handshakeHashOK) { doAppBegin(maximum, traceId, authorization, affinity); } else { doAppReset(traceId, authorization); } }
private void onnetbegin( beginfw begin) { final long sequence = begin.sequence(); final long acknowledge = begin.acknowledge(); final int maximum = begin.maximum(); final long traceid = begin.traceid(); final long authorization = begin.authorization(); final long affinity = begin.affinity(); assert acknowledge <= sequence; assert sequence >= replyseq; assert acknowledge <= replyack; replyseq = sequence; replyack = acknowledge; assert replyack == replyseq; assert maximum == 0; boolean handshakehashok = false; final octetsfw extension = begin.extension(); if (extension.sizeof() != 0) { final httpbeginexfw httpbeginex = extension.get(httpbeginexro::wrap); final map<string, string> headers = new linkedhashmap<>(); httpbeginex.headers().foreach(header -> { final string name = header.name().asstring(); final string value = header.value().asstring(); headers.merge(name, value, (v1, v2) -> string.format("%s, %s", v1, v2)); }); final string status = headers.get(":status"); final string upgrade = headers.get("upgrade"); final string hash = headers.get("sec-websocket-accept"); final string protocol = headers.get("sec-websocket-protocol"); if (websocket_status.equals(status) && websocket_upgrade.equals(upgrade) && objects.equals(this.protocol, protocol)) { sha1.reset(); sha1.update(key.getbytes(us_ascii)); final byte[] digest = sha1.digest(handshake_guid); final encoder encoder = base64.getencoder(); final string handshakehash = new string(encoder.encode(digest), us_ascii); handshakehashok = handshakehash.equals(hash); } } if (handshakehashok) { doappbegin(maximum, traceid, authorization, affinity); } else { doappreset(traceid, authorization); } }
lukefallows/zilla
[ 1, 0, 0, 0 ]
18,250
@Override public Value evaluate(Context context) { Value operand1 = get(0, context); Value operand2 = get(1, context); if (operand1.isNumber() && operand2.isList()) { BigDecimal value1 = operand1.getNumber(); List<Value> value2 = operand2.getList(); return value2.get(value1.intValue()); } else if (operand1.isNumber() && operand2.isString()) { BigDecimal value1 = operand1.getNumber(); String value2 = operand2.getString(); return Value.asString(String.valueOf(value2.charAt(value1.intValue()))); } // TODO: explain more throw new RuntimeException("Cannot perform operation '" + token.lexeme + "' at: [" + token.line + ", " + token.column + "]"); }
@Override public Value evaluate(Context context) { Value operand1 = get(0, context); Value operand2 = get(1, context); if (operand1.isNumber() && operand2.isList()) { BigDecimal value1 = operand1.getNumber(); List<Value> value2 = operand2.getList(); return value2.get(value1.intValue()); } else if (operand1.isNumber() && operand2.isString()) { BigDecimal value1 = operand1.getNumber(); String value2 = operand2.getString(); return Value.asString(String.valueOf(value2.charAt(value1.intValue()))); } throw new RuntimeException("Cannot perform operation '" + token.lexeme + "' at: [" + token.line + ", " + token.column + "]"); }
@override public value evaluate(context context) { value operand1 = get(0, context); value operand2 = get(1, context); if (operand1.isnumber() && operand2.islist()) { bigdecimal value1 = operand1.getnumber(); list<value> value2 = operand2.getlist(); return value2.get(value1.intvalue()); } else if (operand1.isnumber() && operand2.isstring()) { bigdecimal value1 = operand1.getnumber(); string value2 = operand2.getstring(); return value.asstring(string.valueof(value2.charat(value1.intvalue()))); } throw new runtimeexception("cannot perform operation '" + token.lexeme + "' at: [" + token.line + ", " + token.column + "]"); }
mauriciotogneri/prefix
[ 0, 0, 0, 0 ]
10,131
@Test public void test() throws Exception { // The generated main dex list should contain Main (which is a root) and A (which is a direct // dependency of Main). assertEquals(2, mainDexList.size()); assertEquals(A.class.getTypeName(), mainDexList.get(0).getTypeName()); assertEquals(Main.class.getTypeName(), mainDexList.get(1).getTypeName()); R8TestCompileResult compileResult = testForR8(parameters.getBackend()) .addInnerClasses(getClass()) .addInliningAnnotations() .addKeepClassAndMembersRules(Main.class) .addMainDexListClassReferences(mainDexList) .collectMainDexClasses() .enableInliningAnnotations() .enableNoHorizontalClassMergingAnnotations() .enableNoHorizontalClassMergingAnnotations() .setMinApi(parameters.getApiLevel()) .allowDiagnosticMessages() .compileWithExpectedDiagnostics( diagnostics -> diagnostics .assertOnlyWarnings() .assertWarningsMatch( diagnosticType(UnsupportedMainDexListUsageDiagnostic.class))); CodeInspector inspector = compileResult.inspector(); ClassSubject mainClassSubject = inspector.clazz(Main.class); assertThat(mainClassSubject, isPresent()); MethodSubject fooMethodSubject = mainClassSubject.uniqueMethodWithName("foo"); assertThat(fooMethodSubject, isPresent()); ClassSubject aClassSubject = inspector.clazz(A.class); assertThat(aClassSubject, isPresent()); MethodSubject barMethodSubject = aClassSubject.uniqueMethodWithName("bar"); assertThat(barMethodSubject, isPresent()); ClassSubject bClassSubject = inspector.clazz(B.class); assertThat(bClassSubject, isPresent()); MethodSubject bazMethodSubject = bClassSubject.uniqueMethodWithName("baz"); assertThat(bazMethodSubject, isPresent()); assertThat(fooMethodSubject, invokesMethod(barMethodSubject)); assertThat(barMethodSubject, invokesMethod(bazMethodSubject)); // The main dex classes should be the same as the input main dex list. assertEquals( ImmutableSet.of(mainClassSubject.getFinalName(), aClassSubject.getFinalName()), compileResult.getMainDexClasses()); }
@Test public void test() throws Exception { assertEquals(2, mainDexList.size()); assertEquals(A.class.getTypeName(), mainDexList.get(0).getTypeName()); assertEquals(Main.class.getTypeName(), mainDexList.get(1).getTypeName()); R8TestCompileResult compileResult = testForR8(parameters.getBackend()) .addInnerClasses(getClass()) .addInliningAnnotations() .addKeepClassAndMembersRules(Main.class) .addMainDexListClassReferences(mainDexList) .collectMainDexClasses() .enableInliningAnnotations() .enableNoHorizontalClassMergingAnnotations() .enableNoHorizontalClassMergingAnnotations() .setMinApi(parameters.getApiLevel()) .allowDiagnosticMessages() .compileWithExpectedDiagnostics( diagnostics -> diagnostics .assertOnlyWarnings() .assertWarningsMatch( diagnosticType(UnsupportedMainDexListUsageDiagnostic.class))); CodeInspector inspector = compileResult.inspector(); ClassSubject mainClassSubject = inspector.clazz(Main.class); assertThat(mainClassSubject, isPresent()); MethodSubject fooMethodSubject = mainClassSubject.uniqueMethodWithName("foo"); assertThat(fooMethodSubject, isPresent()); ClassSubject aClassSubject = inspector.clazz(A.class); assertThat(aClassSubject, isPresent()); MethodSubject barMethodSubject = aClassSubject.uniqueMethodWithName("bar"); assertThat(barMethodSubject, isPresent()); ClassSubject bClassSubject = inspector.clazz(B.class); assertThat(bClassSubject, isPresent()); MethodSubject bazMethodSubject = bClassSubject.uniqueMethodWithName("baz"); assertThat(bazMethodSubject, isPresent()); assertThat(fooMethodSubject, invokesMethod(barMethodSubject)); assertThat(barMethodSubject, invokesMethod(bazMethodSubject)); assertEquals( ImmutableSet.of(mainClassSubject.getFinalName(), aClassSubject.getFinalName()), compileResult.getMainDexClasses()); }
@test public void test() throws exception { assertequals(2, maindexlist.size()); assertequals(a.class.gettypename(), maindexlist.get(0).gettypename()); assertequals(main.class.gettypename(), maindexlist.get(1).gettypename()); r8testcompileresult compileresult = testforr8(parameters.getbackend()) .addinnerclasses(getclass()) .addinliningannotations() .addkeepclassandmembersrules(main.class) .addmaindexlistclassreferences(maindexlist) .collectmaindexclasses() .enableinliningannotations() .enablenohorizontalclassmergingannotations() .enablenohorizontalclassmergingannotations() .setminapi(parameters.getapilevel()) .allowdiagnosticmessages() .compilewithexpecteddiagnostics( diagnostics -> diagnostics .assertonlywarnings() .assertwarningsmatch( diagnostictype(unsupportedmaindexlistusagediagnostic.class))); codeinspector inspector = compileresult.inspector(); classsubject mainclasssubject = inspector.clazz(main.class); assertthat(mainclasssubject, ispresent()); methodsubject foomethodsubject = mainclasssubject.uniquemethodwithname("foo"); assertthat(foomethodsubject, ispresent()); classsubject aclasssubject = inspector.clazz(a.class); assertthat(aclasssubject, ispresent()); methodsubject barmethodsubject = aclasssubject.uniquemethodwithname("bar"); assertthat(barmethodsubject, ispresent()); classsubject bclasssubject = inspector.clazz(b.class); assertthat(bclasssubject, ispresent()); methodsubject bazmethodsubject = bclasssubject.uniquemethodwithname("baz"); assertthat(bazmethodsubject, ispresent()); assertthat(foomethodsubject, invokesmethod(barmethodsubject)); assertthat(barmethodsubject, invokesmethod(bazmethodsubject)); assertequals( immutableset.of(mainclasssubject.getfinalname(), aclasssubject.getfinalname()), compileresult.getmaindexclasses()); }
kami-lang/madex-r8
[ 0, 0, 0, 1 ]
18,378
public T getAbstractOption() { // WARNING!! Do not rename this method to getOption(). It breaks // BeanUtils, which will silently not call setOption. Very annoying! return abstractOption; }
public T getAbstractOption() { return abstractOption; }
public t getabstractoption() { return abstractoption; }
kupl/starlab-benchmarks
[ 0, 0, 1, 0 ]
18,390
@Override public brooklyn.management.internal.UsageListener apply(String input) { // TODO Want to use classLoader = mgmt.getCatalog().getRootClassLoader(); ClassLoader classLoader = LocalUsageManager.class.getClassLoader(); Optional<Object> result = Reflections.invokeConstructorWithArgs(classLoader, input); if (result.isPresent()) { if (result.get() instanceof brooklyn.management.internal.UsageManager.UsageListener) { return new brooklyn.management.internal.UsageManager.UsageListener.UsageListenerAdapter((brooklyn.management.internal.UsageManager.UsageListener) result.get()); } else { return (brooklyn.management.internal.UsageListener) result.get(); } } else { throw new IllegalStateException("Failed to create UsageListener from class name '"+input+"' using no-arg constructor"); } }
@Override public brooklyn.management.internal.UsageListener apply(String input) { ClassLoader classLoader = LocalUsageManager.class.getClassLoader(); Optional<Object> result = Reflections.invokeConstructorWithArgs(classLoader, input); if (result.isPresent()) { if (result.get() instanceof brooklyn.management.internal.UsageManager.UsageListener) { return new brooklyn.management.internal.UsageManager.UsageListener.UsageListenerAdapter((brooklyn.management.internal.UsageManager.UsageListener) result.get()); } else { return (brooklyn.management.internal.UsageListener) result.get(); } } else { throw new IllegalStateException("Failed to create UsageListener from class name '"+input+"' using no-arg constructor"); } }
@override public brooklyn.management.internal.usagelistener apply(string input) { classloader classloader = localusagemanager.class.getclassloader(); optional<object> result = reflections.invokeconstructorwithargs(classloader, input); if (result.ispresent()) { if (result.get() instanceof brooklyn.management.internal.usagemanager.usagelistener) { return new brooklyn.management.internal.usagemanager.usagelistener.usagelisteneradapter((brooklyn.management.internal.usagemanager.usagelistener) result.get()); } else { return (brooklyn.management.internal.usagelistener) result.get(); } } else { throw new illegalstateexception("failed to create usagelistener from class name '"+input+"' using no-arg constructor"); } }
kiuby88/incubator-brooklyn
[ 1, 0, 0, 0 ]
2,022
@Test public void testUpgradeTables() throws Exception { TestRMTxStore store = new TestRMTxStore(); store.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); // workaround for the db file deletion problem during the tests store.setUrl(MessageFormat.format("jdbc:derby:{0};create=true", TEST_DB_NAME)); // use the old db definitions to create the tables store.init(); // verify the absence of the new columns in the tables verifyColumns(store, "CXF_RM_SRC_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, true); verifyColumns(store, "CXF_RM_DEST_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, true); verifyColumns(store, INBOUND_MSGS_TABLE_NAME, new String[]{}, true); verifyColumns(store, OUTBOUND_MSGS_TABLE_NAME, new String[]{}, true); // upgrade the tables and add new columns to the old tables store.upgrade(); store.init(); // verify the presence of the new columns in the upgraded tables verifyColumns(store, "CXF_RM_SRC_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, false); verifyColumns(store, "CXF_RM_DEST_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, false); verifyColumns(store, INBOUND_MSGS_TABLE_NAME, new String[]{}, false); verifyColumns(store, OUTBOUND_MSGS_TABLE_NAME, new String[]{}, false); }
@Test public void testUpgradeTables() throws Exception { TestRMTxStore store = new TestRMTxStore(); store.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver"); store.setUrl(MessageFormat.format("jdbc:derby:{0};create=true", TEST_DB_NAME)); store.init(); verifyColumns(store, "CXF_RM_SRC_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, true); verifyColumns(store, "CXF_RM_DEST_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, true); verifyColumns(store, INBOUND_MSGS_TABLE_NAME, new String[]{}, true); verifyColumns(store, OUTBOUND_MSGS_TABLE_NAME, new String[]{}, true); store.upgrade(); store.init(); verifyColumns(store, "CXF_RM_SRC_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, false); verifyColumns(store, "CXF_RM_DEST_SEQUENCES", new String[]{"PROTOCOL_VERSION"}, false); verifyColumns(store, INBOUND_MSGS_TABLE_NAME, new String[]{}, false); verifyColumns(store, OUTBOUND_MSGS_TABLE_NAME, new String[]{}, false); }
@test public void testupgradetables() throws exception { testrmtxstore store = new testrmtxstore(); store.setdriverclassname("org.apache.derby.jdbc.embeddeddriver"); store.seturl(messageformat.format("jdbc:derby:{0};create=true", test_db_name)); store.init(); verifycolumns(store, "cxf_rm_src_sequences", new string[]{"protocol_version"}, true); verifycolumns(store, "cxf_rm_dest_sequences", new string[]{"protocol_version"}, true); verifycolumns(store, inbound_msgs_table_name, new string[]{}, true); verifycolumns(store, outbound_msgs_table_name, new string[]{}, true); store.upgrade(); store.init(); verifycolumns(store, "cxf_rm_src_sequences", new string[]{"protocol_version"}, false); verifycolumns(store, "cxf_rm_dest_sequences", new string[]{"protocol_version"}, false); verifycolumns(store, inbound_msgs_table_name, new string[]{}, false); verifycolumns(store, outbound_msgs_table_name, new string[]{}, false); }
kimjand/cxf
[ 1, 0, 0, 0 ]
2,048
@VisibleForTesting HeaderCacheElement getHeader() throws ExecutionException, InterruptedException, TimeoutException { final Future<HeaderCacheElement> deferredResult; // Optimize for the common case: do a volatile read to peek for a Good cache value HeaderCacheElement headerCacheUnsync = this.headerCache; if (headerCacheUnsync.getCacheState() == CacheState.Good) { return headerCacheUnsync; } // TODO(igorbernstein2): figure out how to make this work with appengine request scoped threads synchronized (lock) { CacheState state = headerCache.getCacheState(); switch (state) { case Good: return headerCache; case Stale: asyncRefresh(); return headerCache; case Expired: case Exception: // defer the future resolution (asyncRefresh will spin up a thread that will try to acquire the lock) deferredResult = asyncRefresh(); break; default: return new HeaderCacheElement( Status.UNAUTHENTICATED .withCause(new IllegalStateException("Could not process state: " + state)) ); } } return deferredResult.get(5, TimeUnit.SECONDS); }
@VisibleForTesting HeaderCacheElement getHeader() throws ExecutionException, InterruptedException, TimeoutException { final Future<HeaderCacheElement> deferredResult; HeaderCacheElement headerCacheUnsync = this.headerCache; if (headerCacheUnsync.getCacheState() == CacheState.Good) { return headerCacheUnsync; } synchronized (lock) { CacheState state = headerCache.getCacheState(); switch (state) { case Good: return headerCache; case Stale: asyncRefresh(); return headerCache; case Expired: case Exception: deferredResult = asyncRefresh(); break; default: return new HeaderCacheElement( Status.UNAUTHENTICATED .withCause(new IllegalStateException("Could not process state: " + state)) ); } } return deferredResult.get(5, TimeUnit.SECONDS); }
@visiblefortesting headercacheelement getheader() throws executionexception, interruptedexception, timeoutexception { final future<headercacheelement> deferredresult; headercacheelement headercacheunsync = this.headercache; if (headercacheunsync.getcachestate() == cachestate.good) { return headercacheunsync; } synchronized (lock) { cachestate state = headercache.getcachestate(); switch (state) { case good: return headercache; case stale: asyncrefresh(); return headercache; case expired: case exception: deferredresult = asyncrefresh(); break; default: return new headercacheelement( status.unauthenticated .withcause(new illegalstateexception("could not process state: " + state)) ); } } return deferredresult.get(5, timeunit.seconds); }
mbrukman/java-bigtable-hbase
[ 1, 0, 0, 0 ]
10,315
static private List<EventStripe> mergeClustersToStripes(Period timeUnitLength, List<EventCluster> preMergedEvents) { //effectively map from type to (map from description to events) Map<EventType, SetMultimap< String, EventCluster>> typeMap = new HashMap<>(); for (EventCluster aggregateEvent : preMergedEvents) { typeMap.computeIfAbsent(aggregateEvent.getEventType(), eventType -> HashMultimap.create()) .put(aggregateEvent.getDescription(), aggregateEvent); } //result list to return ArrayList<EventCluster> aggEvents = new ArrayList<>(); //For each (type, description) key, merge agg events for (SetMultimap<String, EventCluster> descrMap : typeMap.values()) { //for each description ... for (String descr : descrMap.keySet()) { //run through the sorted events, merging together adjacent events Iterator<EventCluster> iterator = descrMap.get(descr).stream() .sorted(Comparator.comparing(event -> event.getSpan().getStartMillis())) .iterator(); EventCluster current = iterator.next(); while (iterator.hasNext()) { EventCluster next = iterator.next(); Interval gap = current.getSpan().gap(next.getSpan()); //if they overlap or gap is less one quarter timeUnitLength //TODO: 1/4 factor is arbitrary. review! -jm if (gap == null || gap.toDuration().getMillis() <= timeUnitLength.toDurationFrom(gap.getStart()).getMillis() / 4) { //merge them current = EventCluster.merge(current, next); } else { //done merging into current, set next as new current aggEvents.add(current); current = next; } } aggEvents.add(current); } } //merge clusters to stripes Map<ImmutablePair<EventType, String>, EventStripe> stripeDescMap = new HashMap<>(); for (EventCluster eventCluster : aggEvents) { stripeDescMap.merge(ImmutablePair.of(eventCluster.getEventType(), eventCluster.getDescription()), new EventStripe(eventCluster, null), EventStripe::merge); } return stripeDescMap.values().stream().sorted(Comparator.comparing(EventStripe::getStartMillis)).collect(Collectors.toList()); }
static private List<EventStripe> mergeClustersToStripes(Period timeUnitLength, List<EventCluster> preMergedEvents) { Map<EventType, SetMultimap< String, EventCluster>> typeMap = new HashMap<>(); for (EventCluster aggregateEvent : preMergedEvents) { typeMap.computeIfAbsent(aggregateEvent.getEventType(), eventType -> HashMultimap.create()) .put(aggregateEvent.getDescription(), aggregateEvent); } ArrayList<EventCluster> aggEvents = new ArrayList<>(); for (SetMultimap<String, EventCluster> descrMap : typeMap.values()) { for (String descr : descrMap.keySet()) { Iterator<EventCluster> iterator = descrMap.get(descr).stream() .sorted(Comparator.comparing(event -> event.getSpan().getStartMillis())) .iterator(); EventCluster current = iterator.next(); while (iterator.hasNext()) { EventCluster next = iterator.next(); Interval gap = current.getSpan().gap(next.getSpan()); if (gap == null || gap.toDuration().getMillis() <= timeUnitLength.toDurationFrom(gap.getStart()).getMillis() / 4) { current = EventCluster.merge(current, next); } else { aggEvents.add(current); current = next; } } aggEvents.add(current); } } Map<ImmutablePair<EventType, String>, EventStripe> stripeDescMap = new HashMap<>(); for (EventCluster eventCluster : aggEvents) { stripeDescMap.merge(ImmutablePair.of(eventCluster.getEventType(), eventCluster.getDescription()), new EventStripe(eventCluster, null), EventStripe::merge); } return stripeDescMap.values().stream().sorted(Comparator.comparing(EventStripe::getStartMillis)).collect(Collectors.toList()); }
static private list<eventstripe> mergeclusterstostripes(period timeunitlength, list<eventcluster> premergedevents) { map<eventtype, setmultimap< string, eventcluster>> typemap = new hashmap<>(); for (eventcluster aggregateevent : premergedevents) { typemap.computeifabsent(aggregateevent.geteventtype(), eventtype -> hashmultimap.create()) .put(aggregateevent.getdescription(), aggregateevent); } arraylist<eventcluster> aggevents = new arraylist<>(); for (setmultimap<string, eventcluster> descrmap : typemap.values()) { for (string descr : descrmap.keyset()) { iterator<eventcluster> iterator = descrmap.get(descr).stream() .sorted(comparator.comparing(event -> event.getspan().getstartmillis())) .iterator(); eventcluster current = iterator.next(); while (iterator.hasnext()) { eventcluster next = iterator.next(); interval gap = current.getspan().gap(next.getspan()); if (gap == null || gap.toduration().getmillis() <= timeunitlength.todurationfrom(gap.getstart()).getmillis() / 4) { current = eventcluster.merge(current, next); } else { aggevents.add(current); current = next; } } aggevents.add(current); } } map<immutablepair<eventtype, string>, eventstripe> stripedescmap = new hashmap<>(); for (eventcluster eventcluster : aggevents) { stripedescmap.merge(immutablepair.of(eventcluster.geteventtype(), eventcluster.getdescription()), new eventstripe(eventcluster, null), eventstripe::merge); } return stripedescmap.values().stream().sorted(comparator.comparing(eventstripe::getstartmillis)).collect(collectors.tolist()); }
karlmortensen/autopsy
[ 1, 0, 0, 0 ]
2,162
public void storeObjectField(int fieldNumber, Object value) { if (value == null) { return; // No value so nothing to do } ExecutionContext ec = op.getExecutionContext(); ClassLoaderResolver clr = ec.getClassLoaderResolver(); AbstractMemberMetaData mmd = op.getClassMetaData().getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber); if (mmd != null) { DatastoreClass table = rdbmsMgr.getDatastoreClass(op.getObject().getClass().getName(), clr); JavaTypeMapping fieldMapping = table.getMemberMapping(mmd); if (fieldMapping != null) { if (fieldMapping instanceof InterfaceMapping) { // 1-1 Interface field InterfaceMapping intfMapping = (InterfaceMapping)fieldMapping; if (mmd.getFieldTypes() != null || mmd.hasExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES)) { // Field is defined to not accept this type so just return return; } processInterfaceMappingForValue(intfMapping, value, mmd, ec); } else if (mmd.hasCollection() || mmd.hasArray()) { boolean hasJoin = false; if (mmd.getJoinMetaData() != null) { hasJoin = true; } else { AbstractMemberMetaData[] relMmds = mmd.getRelatedMemberMetaData(clr); if (relMmds != null && relMmds[0].getJoinMetaData() != null) { hasJoin = true; } } if (!hasJoin) { // Not join table so no supported schema updates return; } Table joinTbl = fieldMapping.getStoreManager().getTable(mmd); ElementContainerTable collTbl = (ElementContainerTable)joinTbl; JavaTypeMapping elemMapping = collTbl.getElementMapping(); if (elemMapping instanceof InterfaceMapping) { InterfaceMapping intfMapping = (InterfaceMapping)elemMapping; if (mmd.hasCollection()) { Collection coll = (Collection)value; if (coll.isEmpty()) { return; } // Update value mapping using first element. Maybe we should do the same for all elements? Object elementValue = coll.iterator().next(); processInterfaceMappingForValue(intfMapping, elementValue, mmd, ec); } else if (mmd.hasArray()) { if (Array.getLength(value) == 0) { return; } // Update value mapping using first element. Maybe we should do the same for all elements? Object elementValue = Array.get(value, 0); processInterfaceMappingForValue(intfMapping, elementValue, mmd, ec); } } } else if (mmd.hasMap()) { boolean hasJoin = false; if (mmd.getJoinMetaData() != null) { hasJoin = true; } else { AbstractMemberMetaData[] relMmds = mmd.getRelatedMemberMetaData(clr); if (relMmds != null && relMmds[0].getJoinMetaData() != null) { hasJoin = true; } } if (!hasJoin) { // Not join table so no supported schema updates return; } Map map = (Map)value; if (map.isEmpty()) { return; } Table joinTbl = fieldMapping.getStoreManager().getTable(mmd); MapTable mapTbl = (MapTable)joinTbl; JavaTypeMapping keyMapping = mapTbl.getKeyMapping(); if (keyMapping instanceof InterfaceMapping) { // Update key mapping using first key. Maybe we should do the same for all keys? InterfaceMapping intfMapping = (InterfaceMapping)keyMapping; Object keyValue = map.keySet().iterator().next(); processInterfaceMappingForValue(intfMapping, keyValue, mmd, ec); } JavaTypeMapping valMapping = mapTbl.getValueMapping(); if (valMapping instanceof InterfaceMapping) { // Update value mapping using first value. Maybe we should do the same for all values? InterfaceMapping intfMapping = (InterfaceMapping)valMapping; Object valValue = map.values().iterator().next(); processInterfaceMappingForValue(intfMapping, valValue, mmd, ec); } } } } }
public void storeObjectField(int fieldNumber, Object value) { if (value == null) { return; } ExecutionContext ec = op.getExecutionContext(); ClassLoaderResolver clr = ec.getClassLoaderResolver(); AbstractMemberMetaData mmd = op.getClassMetaData().getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber); if (mmd != null) { DatastoreClass table = rdbmsMgr.getDatastoreClass(op.getObject().getClass().getName(), clr); JavaTypeMapping fieldMapping = table.getMemberMapping(mmd); if (fieldMapping != null) { if (fieldMapping instanceof InterfaceMapping) { InterfaceMapping intfMapping = (InterfaceMapping)fieldMapping; if (mmd.getFieldTypes() != null || mmd.hasExtension(MetaData.EXTENSION_MEMBER_IMPLEMENTATION_CLASSES)) { return; } processInterfaceMappingForValue(intfMapping, value, mmd, ec); } else if (mmd.hasCollection() || mmd.hasArray()) { boolean hasJoin = false; if (mmd.getJoinMetaData() != null) { hasJoin = true; } else { AbstractMemberMetaData[] relMmds = mmd.getRelatedMemberMetaData(clr); if (relMmds != null && relMmds[0].getJoinMetaData() != null) { hasJoin = true; } } if (!hasJoin) { return; } Table joinTbl = fieldMapping.getStoreManager().getTable(mmd); ElementContainerTable collTbl = (ElementContainerTable)joinTbl; JavaTypeMapping elemMapping = collTbl.getElementMapping(); if (elemMapping instanceof InterfaceMapping) { InterfaceMapping intfMapping = (InterfaceMapping)elemMapping; if (mmd.hasCollection()) { Collection coll = (Collection)value; if (coll.isEmpty()) { return; } Object elementValue = coll.iterator().next(); processInterfaceMappingForValue(intfMapping, elementValue, mmd, ec); } else if (mmd.hasArray()) { if (Array.getLength(value) == 0) { return; } Object elementValue = Array.get(value, 0); processInterfaceMappingForValue(intfMapping, elementValue, mmd, ec); } } } else if (mmd.hasMap()) { boolean hasJoin = false; if (mmd.getJoinMetaData() != null) { hasJoin = true; } else { AbstractMemberMetaData[] relMmds = mmd.getRelatedMemberMetaData(clr); if (relMmds != null && relMmds[0].getJoinMetaData() != null) { hasJoin = true; } } if (!hasJoin) { return; } Map map = (Map)value; if (map.isEmpty()) { return; } Table joinTbl = fieldMapping.getStoreManager().getTable(mmd); MapTable mapTbl = (MapTable)joinTbl; JavaTypeMapping keyMapping = mapTbl.getKeyMapping(); if (keyMapping instanceof InterfaceMapping) { InterfaceMapping intfMapping = (InterfaceMapping)keyMapping; Object keyValue = map.keySet().iterator().next(); processInterfaceMappingForValue(intfMapping, keyValue, mmd, ec); } JavaTypeMapping valMapping = mapTbl.getValueMapping(); if (valMapping instanceof InterfaceMapping) { InterfaceMapping intfMapping = (InterfaceMapping)valMapping; Object valValue = map.values().iterator().next(); processInterfaceMappingForValue(intfMapping, valValue, mmd, ec); } } } } }
public void storeobjectfield(int fieldnumber, object value) { if (value == null) { return; } executioncontext ec = op.getexecutioncontext(); classloaderresolver clr = ec.getclassloaderresolver(); abstractmembermetadata mmd = op.getclassmetadata().getmetadataformanagedmemberatabsoluteposition(fieldnumber); if (mmd != null) { datastoreclass table = rdbmsmgr.getdatastoreclass(op.getobject().getclass().getname(), clr); javatypemapping fieldmapping = table.getmembermapping(mmd); if (fieldmapping != null) { if (fieldmapping instanceof interfacemapping) { interfacemapping intfmapping = (interfacemapping)fieldmapping; if (mmd.getfieldtypes() != null || mmd.hasextension(metadata.extension_member_implementation_classes)) { return; } processinterfacemappingforvalue(intfmapping, value, mmd, ec); } else if (mmd.hascollection() || mmd.hasarray()) { boolean hasjoin = false; if (mmd.getjoinmetadata() != null) { hasjoin = true; } else { abstractmembermetadata[] relmmds = mmd.getrelatedmembermetadata(clr); if (relmmds != null && relmmds[0].getjoinmetadata() != null) { hasjoin = true; } } if (!hasjoin) { return; } table jointbl = fieldmapping.getstoremanager().gettable(mmd); elementcontainertable colltbl = (elementcontainertable)jointbl; javatypemapping elemmapping = colltbl.getelementmapping(); if (elemmapping instanceof interfacemapping) { interfacemapping intfmapping = (interfacemapping)elemmapping; if (mmd.hascollection()) { collection coll = (collection)value; if (coll.isempty()) { return; } object elementvalue = coll.iterator().next(); processinterfacemappingforvalue(intfmapping, elementvalue, mmd, ec); } else if (mmd.hasarray()) { if (array.getlength(value) == 0) { return; } object elementvalue = array.get(value, 0); processinterfacemappingforvalue(intfmapping, elementvalue, mmd, ec); } } } else if (mmd.hasmap()) { boolean hasjoin = false; if (mmd.getjoinmetadata() != null) { hasjoin = true; } else { abstractmembermetadata[] relmmds = mmd.getrelatedmembermetadata(clr); if (relmmds != null && relmmds[0].getjoinmetadata() != null) { hasjoin = true; } } if (!hasjoin) { return; } map map = (map)value; if (map.isempty()) { return; } table jointbl = fieldmapping.getstoremanager().gettable(mmd); maptable maptbl = (maptable)jointbl; javatypemapping keymapping = maptbl.getkeymapping(); if (keymapping instanceof interfacemapping) { interfacemapping intfmapping = (interfacemapping)keymapping; object keyvalue = map.keyset().iterator().next(); processinterfacemappingforvalue(intfmapping, keyvalue, mmd, ec); } javatypemapping valmapping = maptbl.getvaluemapping(); if (valmapping instanceof interfacemapping) { interfacemapping intfmapping = (interfacemapping)valmapping; object valvalue = map.values().iterator().next(); processinterfacemappingforvalue(intfmapping, valvalue, mmd, ec); } } } } }
meysam/datanucleus-rdbms
[ 1, 0, 0, 0 ]
2,180
public void R_Init (Wad wad, int screenBlocks, boolean detailLevel) { //MenuManager menu = MenuManager.getInstance(); logger.config("R_InitData"); data.R_InitData (wad); //UNUSED - gets points from a table. //logger.config("\nR_InitPointToAngle"); //R_InitPointToAngle (); //UNUSED - gets points from a table. //logger.config("\nR_InitTables"); //R_InitTables (); // viewwidth / viewheight / detailLevel are set by the defaults R_SetViewSize (screenBlocks, detailLevel); logger.config("R_InitPlanes"); plane.R_InitPlanes (); //todo Handled in r_planes.c logger.config("R_InitLightTables"); R_InitLightTables (); logger.config("R_InitSkyMap"); R_InitSkyMap (wad); //todo handled in r_sky.c logger.config("R_InitTranslationTables"); draw.R_InitTranslationTables (); //todo handled in r_draw.c framecount = 0; }
public void R_Init (Wad wad, int screenBlocks, boolean detailLevel) { logger.config("R_InitData"); data.R_InitData (wad); R_SetViewSize (screenBlocks, detailLevel); logger.config("R_InitPlanes"); plane.R_InitPlanes (); logger.config("R_InitLightTables"); R_InitLightTables (); logger.config("R_InitSkyMap"); R_InitSkyMap (wad); logger.config("R_InitTranslationTables"); draw.R_InitTranslationTables (); framecount = 0; }
public void r_init (wad wad, int screenblocks, boolean detaillevel) { logger.config("r_initdata"); data.r_initdata (wad); r_setviewsize (screenblocks, detaillevel); logger.config("r_initplanes"); plane.r_initplanes (); logger.config("r_initlighttables"); r_initlighttables (); logger.config("r_initskymap"); r_initskymap (wad); logger.config("r_inittranslationtables"); draw.r_inittranslationtables (); framecount = 0; }
maehem/Thump
[ 1, 0, 0, 0 ]
2,227
public static void validateInstance(Document d, LSResourceResolver iepdResourceResolver, List<String> schemaPathList) throws SAXException, Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(iepdResourceResolver); List<Source> sourceList = new ArrayList<Source>(); for (String schemaPath : schemaPathList) { InputStream schemaInStream = XmlUtils.class.getClassLoader().getResourceAsStream(schemaPath); StreamSource schemaStreamSource = new StreamSource(schemaInStream); sourceList.add(schemaStreamSource); } Source[] schemaSourcesArray = sourceList.toArray(new Source[]{}); try { Schema schema = schemaFactory.newSchema(schemaSourcesArray); Validator validator = schema.newValidator(); validator.validate(new DOMSource(d)); } catch (Exception e) { try { e.printStackTrace(); System.err.println("Input document:"); XmlUtils.printNode(d); } catch (Exception e1) { e1.printStackTrace(); } throw e; } }
public static void validateInstance(Document d, LSResourceResolver iepdResourceResolver, List<String> schemaPathList) throws SAXException, Exception { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); schemaFactory.setResourceResolver(iepdResourceResolver); List<Source> sourceList = new ArrayList<Source>(); for (String schemaPath : schemaPathList) { InputStream schemaInStream = XmlUtils.class.getClassLoader().getResourceAsStream(schemaPath); StreamSource schemaStreamSource = new StreamSource(schemaInStream); sourceList.add(schemaStreamSource); } Source[] schemaSourcesArray = sourceList.toArray(new Source[]{}); try { Schema schema = schemaFactory.newSchema(schemaSourcesArray); Validator validator = schema.newValidator(); validator.validate(new DOMSource(d)); } catch (Exception e) { try { e.printStackTrace(); System.err.println("Input document:"); XmlUtils.printNode(d); } catch (Exception e1) { e1.printStackTrace(); } throw e; } }
public static void validateinstance(document d, lsresourceresolver iepdresourceresolver, list<string> schemapathlist) throws saxexception, exception { schemafactory schemafactory = schemafactory.newinstance(xmlconstants.w3c_xml_schema_ns_uri); schemafactory.setresourceresolver(iepdresourceresolver); list<source> sourcelist = new arraylist<source>(); for (string schemapath : schemapathlist) { inputstream schemainstream = xmlutils.class.getclassloader().getresourceasstream(schemapath); streamsource schemastreamsource = new streamsource(schemainstream); sourcelist.add(schemastreamsource); } source[] schemasourcesarray = sourcelist.toarray(new source[]{}); try { schema schema = schemafactory.newschema(schemasourcesarray); validator validator = schema.newvalidator(); validator.validate(new domsource(d)); } catch (exception e) { try { e.printstacktrace(); system.err.println("input document:"); xmlutils.printnode(d); } catch (exception e1) { e1.printstacktrace(); } throw e; } }
mark43/nibrs
[ 0, 0, 0, 0 ]
18,713
@Test /** TODO this test works if we assume most recent version wins, but semantics TBC */ public void testMoreEntityV2ThenV1GivesV1() throws Exception { TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-more-entities_0.1.0.jar"); TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-more-entities_0.2.0.jar"); TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-entities.jar"); addCatalogItems(getLocalResource("more-entity-v2-osgi-catalog.yaml")); forceCatalogUpdate(); addCatalogItems(getLocalResource("more-entity-v1-osgi-catalog.yaml")); Entity app = createAndStartApplication("services: [ { type: 'more-entity:1.0' } ]"); Entity moreEntity = Iterables.getOnlyElement(app.getChildren()); OsgiVersionMoreEntityTest.assertV1EffectorCall(moreEntity); OsgiVersionMoreEntityTest.assertV1MethodCall(moreEntity); }
@Test public void testMoreEntityV2ThenV1GivesV1() throws Exception { TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-more-entities_0.1.0.jar"); TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-more-entities_0.2.0.jar"); TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), "/brooklyn/osgi/brooklyn-test-osgi-entities.jar"); addCatalogItems(getLocalResource("more-entity-v2-osgi-catalog.yaml")); forceCatalogUpdate(); addCatalogItems(getLocalResource("more-entity-v1-osgi-catalog.yaml")); Entity app = createAndStartApplication("services: [ { type: 'more-entity:1.0' } ]"); Entity moreEntity = Iterables.getOnlyElement(app.getChildren()); OsgiVersionMoreEntityTest.assertV1EffectorCall(moreEntity); OsgiVersionMoreEntityTest.assertV1MethodCall(moreEntity); }
@test public void testmoreentityv2thenv1givesv1() throws exception { testresourceunavailableexception.throwifresourceunavailable(getclass(), "/brooklyn/osgi/brooklyn-test-osgi-more-entities_0.1.0.jar"); testresourceunavailableexception.throwifresourceunavailable(getclass(), "/brooklyn/osgi/brooklyn-test-osgi-more-entities_0.2.0.jar"); testresourceunavailableexception.throwifresourceunavailable(getclass(), "/brooklyn/osgi/brooklyn-test-osgi-entities.jar"); addcatalogitems(getlocalresource("more-entity-v2-osgi-catalog.yaml")); forcecatalogupdate(); addcatalogitems(getlocalresource("more-entity-v1-osgi-catalog.yaml")); entity app = createandstartapplication("services: [ { type: 'more-entity:1.0' } ]"); entity moreentity = iterables.getonlyelement(app.getchildren()); osgiversionmoreentitytest.assertv1effectorcall(moreentity); osgiversionmoreentitytest.assertv1methodcall(moreentity); }
kiuby88/incubator-brooklyn
[ 0, 0, 1, 0 ]
10,580
public synchronized boolean markTaskCompleted (int taskId) { Job job = getJobForTask(taskId); if (job == null) { LOG.error("Could not find a job containing task {}, and therefore could not mark the task as completed.", taskId); return false; } job.completedTasks.add(taskId); return true; }
public synchronized boolean markTaskCompleted (int taskId) { Job job = getJobForTask(taskId); if (job == null) { LOG.error("Could not find a job containing task {}, and therefore could not mark the task as completed.", taskId); return false; } job.completedTasks.add(taskId); return true; }
public synchronized boolean marktaskcompleted (int taskid) { job job = getjobfortask(taskid); if (job == null) { log.error("could not find a job containing task {}, and therefore could not mark the task as completed.", taskid); return false; } job.completedtasks.add(taskid); return true; }
mcheung610/r5
[ 1, 0, 0, 0 ]
10,625
private int translateChannel(Channel input, int inputIndex, FlinkVertex targetVertex, TezTaskConfig targetVertexConfig, boolean isBroadcast) throws Exception { final PlanNode inputPlanNode = input.getSource(); final Iterator<Channel> allInChannels; allInChannels = Collections.singletonList(input).iterator(); // check that the type serializer is consistent TypeSerializerFactory<?> typeSerFact = null; while (allInChannels.hasNext()) { final Channel inConn = allInChannels.next(); if (typeSerFact == null) { typeSerFact = inConn.getSerializer(); } else if (!typeSerFact.equals(inConn.getSerializer())) { throw new CompilerException("Conflicting types in union operator."); } final PlanNode sourceNode = inConn.getSource(); FlinkVertex sourceVertex = this.vertices.get(sourceNode); TezTaskConfig sourceVertexConfig = sourceVertex.getConfig(); //TODO ??? need to create a new TezConfig ??? connectJobVertices( inConn, inputIndex, sourceVertex, sourceVertexConfig, targetVertex, targetVertexConfig, isBroadcast); } // the local strategy is added only once. in non-union case that is the actual edge, // in the union case, it is the edge between union and the target node addLocalInfoFromChannelToConfig(input, targetVertexConfig, inputIndex, isBroadcast); return 1; }
private int translateChannel(Channel input, int inputIndex, FlinkVertex targetVertex, TezTaskConfig targetVertexConfig, boolean isBroadcast) throws Exception { final PlanNode inputPlanNode = input.getSource(); final Iterator<Channel> allInChannels; allInChannels = Collections.singletonList(input).iterator(); TypeSerializerFactory<?> typeSerFact = null; while (allInChannels.hasNext()) { final Channel inConn = allInChannels.next(); if (typeSerFact == null) { typeSerFact = inConn.getSerializer(); } else if (!typeSerFact.equals(inConn.getSerializer())) { throw new CompilerException("Conflicting types in union operator."); } final PlanNode sourceNode = inConn.getSource(); FlinkVertex sourceVertex = this.vertices.get(sourceNode); TezTaskConfig sourceVertexConfig = sourceVertex.getConfig(); connectJobVertices( inConn, inputIndex, sourceVertex, sourceVertexConfig, targetVertex, targetVertexConfig, isBroadcast); } addLocalInfoFromChannelToConfig(input, targetVertexConfig, inputIndex, isBroadcast); return 1; }
private int translatechannel(channel input, int inputindex, flinkvertex targetvertex, teztaskconfig targetvertexconfig, boolean isbroadcast) throws exception { final plannode inputplannode = input.getsource(); final iterator<channel> allinchannels; allinchannels = collections.singletonlist(input).iterator(); typeserializerfactory<?> typeserfact = null; while (allinchannels.hasnext()) { final channel inconn = allinchannels.next(); if (typeserfact == null) { typeserfact = inconn.getserializer(); } else if (!typeserfact.equals(inconn.getserializer())) { throw new compilerexception("conflicting types in union operator."); } final plannode sourcenode = inconn.getsource(); flinkvertex sourcevertex = this.vertices.get(sourcenode); teztaskconfig sourcevertexconfig = sourcevertex.getconfig(); connectjobvertices( inconn, inputindex, sourcevertex, sourcevertexconfig, targetvertex, targetvertexconfig, isbroadcast); } addlocalinfofromchanneltoconfig(input, targetvertexconfig, inputindex, isbroadcast); return 1; }
ljzzju/incubator-flink
[ 1, 0, 0, 0 ]
10,626
private void connectJobVertices(Channel channel, int inputNumber, final FlinkVertex sourceVertex, final TezTaskConfig sourceConfig, final FlinkVertex targetVertex, final TezTaskConfig targetConfig, boolean isBroadcast) throws CompilerException { // -------------- configure the source task's ship strategy strategies in task config -------------- final int outputIndex = sourceConfig.getNumOutputs(); sourceConfig.addOutputShipStrategy(channel.getShipStrategy()); if (outputIndex == 0) { sourceConfig.setOutputSerializer(channel.getSerializer()); } if (channel.getShipStrategyComparator() != null) { sourceConfig.setOutputComparator(channel.getShipStrategyComparator(), outputIndex); } if (channel.getShipStrategy() == ShipStrategyType.PARTITION_RANGE) { final DataDistribution dataDistribution = channel.getDataDistribution(); if(dataDistribution != null) { sourceConfig.setOutputDataDistribution(dataDistribution, outputIndex); } else { throw new RuntimeException("Range partitioning requires data distribution"); // TODO: inject code and configuration for automatic histogram generation } } // ---------------- configure the receiver ------------------- if (isBroadcast) { targetConfig.addBroadcastInputToGroup(inputNumber); } else { targetConfig.addInputToGroup(inputNumber); } //----------------- connect source and target with edge ------------------------------ FlinkEdge edge; ShipStrategyType shipStrategy = channel.getShipStrategy(); TypeSerializer<?> serializer = channel.getSerializer().getSerializer(); if ((shipStrategy == ShipStrategyType.FORWARD) || (shipStrategy == ShipStrategyType.NONE)) { edge = new FlinkForwardEdge(sourceVertex, targetVertex, serializer); // For forward edges, create as many tasks in upstream operator as in source operator targetVertex.setParallelism(sourceVertex.getParallelism()); } else if (shipStrategy == ShipStrategyType.BROADCAST) { edge = new FlinkBroadcastEdge(sourceVertex, targetVertex, serializer); } else if (shipStrategy == ShipStrategyType.PARTITION_HASH) { edge = new FlinkPartitionEdge(sourceVertex, targetVertex, serializer); } else { throw new CompilerException("Ship strategy between nodes " + sourceVertex.getVertex().getName() + " and " + targetVertex.getVertex().getName() + " currently not supported"); } // Tez-specific bookkeeping // TODO: This probably will not work for vertices with multiple outputs sourceVertex.addNumberOfSubTasksInOutput(targetVertex.getParallelism(), outputIndex); targetVertex.addInput(sourceVertex, inputNumber); edges.add(edge); }
private void connectJobVertices(Channel channel, int inputNumber, final FlinkVertex sourceVertex, final TezTaskConfig sourceConfig, final FlinkVertex targetVertex, final TezTaskConfig targetConfig, boolean isBroadcast) throws CompilerException { final int outputIndex = sourceConfig.getNumOutputs(); sourceConfig.addOutputShipStrategy(channel.getShipStrategy()); if (outputIndex == 0) { sourceConfig.setOutputSerializer(channel.getSerializer()); } if (channel.getShipStrategyComparator() != null) { sourceConfig.setOutputComparator(channel.getShipStrategyComparator(), outputIndex); } if (channel.getShipStrategy() == ShipStrategyType.PARTITION_RANGE) { final DataDistribution dataDistribution = channel.getDataDistribution(); if(dataDistribution != null) { sourceConfig.setOutputDataDistribution(dataDistribution, outputIndex); } else { throw new RuntimeException("Range partitioning requires data distribution"); } } if (isBroadcast) { targetConfig.addBroadcastInputToGroup(inputNumber); } else { targetConfig.addInputToGroup(inputNumber); } FlinkEdge edge; ShipStrategyType shipStrategy = channel.getShipStrategy(); TypeSerializer<?> serializer = channel.getSerializer().getSerializer(); if ((shipStrategy == ShipStrategyType.FORWARD) || (shipStrategy == ShipStrategyType.NONE)) { edge = new FlinkForwardEdge(sourceVertex, targetVertex, serializer); targetVertex.setParallelism(sourceVertex.getParallelism()); } else if (shipStrategy == ShipStrategyType.BROADCAST) { edge = new FlinkBroadcastEdge(sourceVertex, targetVertex, serializer); } else if (shipStrategy == ShipStrategyType.PARTITION_HASH) { edge = new FlinkPartitionEdge(sourceVertex, targetVertex, serializer); } else { throw new CompilerException("Ship strategy between nodes " + sourceVertex.getVertex().getName() + " and " + targetVertex.getVertex().getName() + " currently not supported"); } sourceVertex.addNumberOfSubTasksInOutput(targetVertex.getParallelism(), outputIndex); targetVertex.addInput(sourceVertex, inputNumber); edges.add(edge); }
private void connectjobvertices(channel channel, int inputnumber, final flinkvertex sourcevertex, final teztaskconfig sourceconfig, final flinkvertex targetvertex, final teztaskconfig targetconfig, boolean isbroadcast) throws compilerexception { final int outputindex = sourceconfig.getnumoutputs(); sourceconfig.addoutputshipstrategy(channel.getshipstrategy()); if (outputindex == 0) { sourceconfig.setoutputserializer(channel.getserializer()); } if (channel.getshipstrategycomparator() != null) { sourceconfig.setoutputcomparator(channel.getshipstrategycomparator(), outputindex); } if (channel.getshipstrategy() == shipstrategytype.partition_range) { final datadistribution datadistribution = channel.getdatadistribution(); if(datadistribution != null) { sourceconfig.setoutputdatadistribution(datadistribution, outputindex); } else { throw new runtimeexception("range partitioning requires data distribution"); } } if (isbroadcast) { targetconfig.addbroadcastinputtogroup(inputnumber); } else { targetconfig.addinputtogroup(inputnumber); } flinkedge edge; shipstrategytype shipstrategy = channel.getshipstrategy(); typeserializer<?> serializer = channel.getserializer().getserializer(); if ((shipstrategy == shipstrategytype.forward) || (shipstrategy == shipstrategytype.none)) { edge = new flinkforwardedge(sourcevertex, targetvertex, serializer); targetvertex.setparallelism(sourcevertex.getparallelism()); } else if (shipstrategy == shipstrategytype.broadcast) { edge = new flinkbroadcastedge(sourcevertex, targetvertex, serializer); } else if (shipstrategy == shipstrategytype.partition_hash) { edge = new flinkpartitionedge(sourcevertex, targetvertex, serializer); } else { throw new compilerexception("ship strategy between nodes " + sourcevertex.getvertex().getname() + " and " + targetvertex.getvertex().getname() + " currently not supported"); } sourcevertex.addnumberofsubtasksinoutput(targetvertex.getparallelism(), outputindex); targetvertex.addinput(sourcevertex, inputnumber); edges.add(edge); }
ljzzju/incubator-flink
[ 1, 1, 0, 0 ]
10,732
@Handler(op = InHeader.USER_TRANSFER_FIELD_REQUEST) public static void handleUserTransferFieldRequest(Client c, InPacket inPacket) { Char chr = c.getChr(); if (inPacket.getUnreadAmount() == 0) { // Coming back from the cash shop // chr.warp(chr.getOrCreateFieldByCurrentInstanceType(chr.getFieldID())); c.getChannelInstance().addClientInTransfer(c.getChannel(), chr.getId(), c); c.write(ClientSocket.migrateCommand(true, (short) c.getChannelInstance().getPort())); return; } byte fieldKey = inPacket.decodeByte(); int targetField = inPacket.decodeInt(); if (targetField == 106020100 || targetField == 106020400) { // same issue as below, its in mushroom kingdom so maybe the maps are just outdated or w/e targetField = 106020403; } else if (targetField == 106020402) { // warping from portal in 106020403 is unable to find defined portal (not a scripted portal) targetField = 106020000; } int x = inPacket.decodeShort(); int y = inPacket.decodeShort(); String portalName = inPacket.decodeString(); if (portalName != null && !"".equals(portalName)) { Field field = chr.getField(); Portal portal = field.getPortalByName(portalName); if (portal.getScript() != null && !portal.getScript().equals("")) { chr.getScriptManager().startScript(portal.getId(), portal.getScript(), ScriptType.Portal); } else { Field toField = chr.getOrCreateFieldByCurrentInstanceType(portal.getTargetMapId()); if (toField == null) { return; } Portal toPortal = toField.getPortalByName(portal.getTargetPortalName()); if (toPortal == null) { toPortal = toField.getPortalByName("sp"); } chr.warp(toField, toPortal); } } else if (chr.getHP() <= 0) { if (InGameEventManager.getInstance().charInEventMap(chr.getId())) { InGameEventManager.getInstance().getActiveEvent().onMigrateDeath(chr); chr.heal(chr.getMaxHP()); chr.healMP(chr.getMaxMP()); return; } // Character is dead, respawn request inPacket.decodeByte(); // always 0 byte tarfield = inPacket.decodeByte(); // ? byte reviveType = inPacket.decodeByte(); int returnMap = chr.getField().getReturnMap() == 999999999 ? chr.getPreviousFieldID() : chr.getField().getReturnMap(); switch (reviveType) { // so far only got 0? } if (!chr.hasBuffProtector()) { chr.getTemporaryStatManager().removeAllStats(); } int deathcount = chr.getDeathCount(); if (deathcount != 0) { if (deathcount > 0) { deathcount--; chr.setDeathCount(deathcount); chr.write(UserLocal.deathCountInfo(deathcount)); } chr.setNearestReturnPortal(); // attempt to respawn them where they died.. maybe portal 0 is better tho? chr.warp(chr.getFieldID(), chr.getPreviousPortalID(), false); chr.healHPMP(); return; } else if (chr.getInstance() != null) { chr.getInstance().removeChar(chr); } else if (chr.getTransferField() == targetField && chr.getTransferFieldReq() == chr.getField().getId()) { Field toField = chr.getOrCreateFieldByCurrentInstanceType(chr.getTransferField()); if (toField != null && chr.getTransferField() > 0) { chr.warp(toField); } chr.setTransferField(0); return; } else { chr.warp(chr.getOrCreateFieldByCurrentInstanceType(chr.getField().getForcedReturn())); } chr.healHPMP(); chr.setBuffProtector(false); } else if (chr.getTransferField() == targetField && chr.getTransferFieldReq() == chr.getField().getId()) { Field toField = chr.getOrCreateFieldByCurrentInstanceType(chr.getTransferField()); if (toField != null && chr.getTransferField() > 0) { chr.warp(toField); } chr.setTransferField(0); } }
@Handler(op = InHeader.USER_TRANSFER_FIELD_REQUEST) public static void handleUserTransferFieldRequest(Client c, InPacket inPacket) { Char chr = c.getChr(); if (inPacket.getUnreadAmount() == 0) { c.getChannelInstance().addClientInTransfer(c.getChannel(), chr.getId(), c); c.write(ClientSocket.migrateCommand(true, (short) c.getChannelInstance().getPort())); return; } byte fieldKey = inPacket.decodeByte(); int targetField = inPacket.decodeInt(); if (targetField == 106020100 || targetField == 106020400) { targetField = 106020403; } else if (targetField == 106020402) { targetField = 106020000; } int x = inPacket.decodeShort(); int y = inPacket.decodeShort(); String portalName = inPacket.decodeString(); if (portalName != null && !"".equals(portalName)) { Field field = chr.getField(); Portal portal = field.getPortalByName(portalName); if (portal.getScript() != null && !portal.getScript().equals("")) { chr.getScriptManager().startScript(portal.getId(), portal.getScript(), ScriptType.Portal); } else { Field toField = chr.getOrCreateFieldByCurrentInstanceType(portal.getTargetMapId()); if (toField == null) { return; } Portal toPortal = toField.getPortalByName(portal.getTargetPortalName()); if (toPortal == null) { toPortal = toField.getPortalByName("sp"); } chr.warp(toField, toPortal); } } else if (chr.getHP() <= 0) { if (InGameEventManager.getInstance().charInEventMap(chr.getId())) { InGameEventManager.getInstance().getActiveEvent().onMigrateDeath(chr); chr.heal(chr.getMaxHP()); chr.healMP(chr.getMaxMP()); return; } inPacket.decodeByte(); byte tarfield = inPacket.decodeByte(); byte reviveType = inPacket.decodeByte(); int returnMap = chr.getField().getReturnMap() == 999999999 ? chr.getPreviousFieldID() : chr.getField().getReturnMap(); switch (reviveType) { } if (!chr.hasBuffProtector()) { chr.getTemporaryStatManager().removeAllStats(); } int deathcount = chr.getDeathCount(); if (deathcount != 0) { if (deathcount > 0) { deathcount--; chr.setDeathCount(deathcount); chr.write(UserLocal.deathCountInfo(deathcount)); } chr.setNearestReturnPortal(); chr.warp(chr.getFieldID(), chr.getPreviousPortalID(), false); chr.healHPMP(); return; } else if (chr.getInstance() != null) { chr.getInstance().removeChar(chr); } else if (chr.getTransferField() == targetField && chr.getTransferFieldReq() == chr.getField().getId()) { Field toField = chr.getOrCreateFieldByCurrentInstanceType(chr.getTransferField()); if (toField != null && chr.getTransferField() > 0) { chr.warp(toField); } chr.setTransferField(0); return; } else { chr.warp(chr.getOrCreateFieldByCurrentInstanceType(chr.getField().getForcedReturn())); } chr.healHPMP(); chr.setBuffProtector(false); } else if (chr.getTransferField() == targetField && chr.getTransferFieldReq() == chr.getField().getId()) { Field toField = chr.getOrCreateFieldByCurrentInstanceType(chr.getTransferField()); if (toField != null && chr.getTransferField() > 0) { chr.warp(toField); } chr.setTransferField(0); } }
@handler(op = inheader.user_transfer_field_request) public static void handleusertransferfieldrequest(client c, inpacket inpacket) { char chr = c.getchr(); if (inpacket.getunreadamount() == 0) { c.getchannelinstance().addclientintransfer(c.getchannel(), chr.getid(), c); c.write(clientsocket.migratecommand(true, (short) c.getchannelinstance().getport())); return; } byte fieldkey = inpacket.decodebyte(); int targetfield = inpacket.decodeint(); if (targetfield == 106020100 || targetfield == 106020400) { targetfield = 106020403; } else if (targetfield == 106020402) { targetfield = 106020000; } int x = inpacket.decodeshort(); int y = inpacket.decodeshort(); string portalname = inpacket.decodestring(); if (portalname != null && !"".equals(portalname)) { field field = chr.getfield(); portal portal = field.getportalbyname(portalname); if (portal.getscript() != null && !portal.getscript().equals("")) { chr.getscriptmanager().startscript(portal.getid(), portal.getscript(), scripttype.portal); } else { field tofield = chr.getorcreatefieldbycurrentinstancetype(portal.gettargetmapid()); if (tofield == null) { return; } portal toportal = tofield.getportalbyname(portal.gettargetportalname()); if (toportal == null) { toportal = tofield.getportalbyname("sp"); } chr.warp(tofield, toportal); } } else if (chr.gethp() <= 0) { if (ingameeventmanager.getinstance().charineventmap(chr.getid())) { ingameeventmanager.getinstance().getactiveevent().onmigratedeath(chr); chr.heal(chr.getmaxhp()); chr.healmp(chr.getmaxmp()); return; } inpacket.decodebyte(); byte tarfield = inpacket.decodebyte(); byte revivetype = inpacket.decodebyte(); int returnmap = chr.getfield().getreturnmap() == 999999999 ? chr.getpreviousfieldid() : chr.getfield().getreturnmap(); switch (revivetype) { } if (!chr.hasbuffprotector()) { chr.gettemporarystatmanager().removeallstats(); } int deathcount = chr.getdeathcount(); if (deathcount != 0) { if (deathcount > 0) { deathcount--; chr.setdeathcount(deathcount); chr.write(userlocal.deathcountinfo(deathcount)); } chr.setnearestreturnportal(); chr.warp(chr.getfieldid(), chr.getpreviousportalid(), false); chr.healhpmp(); return; } else if (chr.getinstance() != null) { chr.getinstance().removechar(chr); } else if (chr.gettransferfield() == targetfield && chr.gettransferfieldreq() == chr.getfield().getid()) { field tofield = chr.getorcreatefieldbycurrentinstancetype(chr.gettransferfield()); if (tofield != null && chr.gettransferfield() > 0) { chr.warp(tofield); } chr.settransferfield(0); return; } else { chr.warp(chr.getorcreatefieldbycurrentinstancetype(chr.getfield().getforcedreturn())); } chr.healhpmp(); chr.setbuffprotector(false); } else if (chr.gettransferfield() == targetfield && chr.gettransferfieldreq() == chr.getfield().getid()) { field tofield = chr.getorcreatefieldbycurrentinstancetype(chr.gettransferfield()); if (tofield != null && chr.gettransferfield() > 0) { chr.warp(tofield); } chr.settransferfield(0); } }
lynsone/swordie
[ 1, 0, 1, 0 ]
18,957
private <T extends Serializable> void sendObject(CommunicationPatternAgent agent, Connection connection, String logMessageName, T obj) throws FatalErrorHalt, AbortRound { byte[] data = null; data = agent.serialize(obj); logJson(LogFlag.serialization, "mica-serialize-bytes-" + logMessageName, data.length); byte[] lengthBytes = serializeInteger(data.length); try { connection.getOutputStream().write(lengthBytes); connection.getOutputStream().write(data); } catch (SocketException se) { // FIXME: check that handleError is aborting on GOSSIP_IO_ERROR // handleError(GOSSIP_IO_ERROR, se); handleError(GOSSIP_IO_ERROR, new AbortRound()); } catch (IOException e) { // FIXME: check that handleError is aborting on GOSSIP_IO_ERROR // handleError(GOSSIP_IO_ERROR, e); handleError(GOSSIP_IO_ERROR, new AbortRound()); } }
private <T extends Serializable> void sendObject(CommunicationPatternAgent agent, Connection connection, String logMessageName, T obj) throws FatalErrorHalt, AbortRound { byte[] data = null; data = agent.serialize(obj); logJson(LogFlag.serialization, "mica-serialize-bytes-" + logMessageName, data.length); byte[] lengthBytes = serializeInteger(data.length); try { connection.getOutputStream().write(lengthBytes); connection.getOutputStream().write(data); } catch (SocketException se) { handleError(GOSSIP_IO_ERROR, new AbortRound()); } catch (IOException e) { handleError(GOSSIP_IO_ERROR, new AbortRound()); } }
private <t extends serializable> void sendobject(communicationpatternagent agent, connection connection, string logmessagename, t obj) throws fatalerrorhalt, abortround { byte[] data = null; data = agent.serialize(obj); logjson(logflag.serialization, "mica-serialize-bytes-" + logmessagename, data.length); byte[] lengthbytes = serializeinteger(data.length); try { connection.getoutputstream().write(lengthbytes); connection.getoutputstream().write(data); } catch (socketexception se) { handleerror(gossip_io_error, new abortround()); } catch (ioexception e) { handleerror(gossip_io_error, new abortround()); } }
mica-gossip/MiCA
[ 0, 0, 1, 0 ]
2,602
@Test public void testUnionType() throws Exception { String sql ="SELECT typeof(a) AS t, modeof(a) AS m, drilltypeof(a) AS dt\n" + "FROM cp.`jsoninput/union/c.json`"; try { testBuilder() .optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true") .sqlQuery(sql) .ordered() .baselineColumns("t", "m", "dt") .baselineValues( "VARCHAR", "NULLABLE", "UNION") .baselineValues( "BIGINT", "NULLABLE", "UNION") .baselineValues( "FLOAT8", "NULLABLE", "UNION") // The following should probably provide the type of the list, // and report cardinality as ARRAY. .baselineValues( "LIST", "NULLABLE", "UNION") .baselineValues( "NULL", "NULLABLE", "UNION") .go(); } finally { client.resetSession(ExecConstants.ENABLE_UNION_TYPE_KEY); } }
@Test public void testUnionType() throws Exception { String sql ="SELECT typeof(a) AS t, modeof(a) AS m, drilltypeof(a) AS dt\n" + "FROM cp.`jsoninput/union/c.json`"; try { testBuilder() .optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true") .sqlQuery(sql) .ordered() .baselineColumns("t", "m", "dt") .baselineValues( "VARCHAR", "NULLABLE", "UNION") .baselineValues( "BIGINT", "NULLABLE", "UNION") .baselineValues( "FLOAT8", "NULLABLE", "UNION") .baselineValues( "LIST", "NULLABLE", "UNION") .baselineValues( "NULL", "NULLABLE", "UNION") .go(); } finally { client.resetSession(ExecConstants.ENABLE_UNION_TYPE_KEY); } }
@test public void testuniontype() throws exception { string sql ="select typeof(a) as t, modeof(a) as m, drilltypeof(a) as dt\n" + "from cp.`jsoninput/union/c.json`"; try { testbuilder() .optionsettingqueriesfortestquery("alter session set `exec.enable_union_type` = true") .sqlquery(sql) .ordered() .baselinecolumns("t", "m", "dt") .baselinevalues( "varchar", "nullable", "union") .baselinevalues( "bigint", "nullable", "union") .baselinevalues( "float8", "nullable", "union") .baselinevalues( "list", "nullable", "union") .baselinevalues( "null", "nullable", "union") .go(); } finally { client.resetsession(execconstants.enable_union_type_key); } }
julien-faye/drill
[ 1, 0, 0, 0 ]
10,862
@Test public void test20046() throws Throwable { if (debug) System.out.format("%n%s%n", "RegressionTest40.test20046"); org.jsoup.helper.HttpConnection.Response response0 = null; org.jsoup.helper.HttpConnection.Response response1 = new org.jsoup.helper.HttpConnection.Response(response0); org.jsoup.Connection.Request request2 = null; response1.req = request2; java.util.Map.Entry<java.lang.String, java.lang.String> strEntry5 = response1.scanHeaders("hi!"); response1.charset = "hi!"; int int8 = response1.numRedirects; response1.contentType = "hi!"; java.nio.ByteBuffer byteBuffer11 = response1.byteData; java.util.Map.Entry<java.lang.String, java.lang.String> strEntry13 = response1.scanHeaders(""); response1.numRedirects = (short) 10; response1.contentType = ""; boolean boolean19 = response1.hasCookie("hi!"); java.lang.String str20 = response1.statusMessage(); int int21 = response1.statusCode(); // The following exception was thrown during execution in test generation try { org.jsoup.helper.HttpConnection.Response response22 = new org.jsoup.helper.HttpConnection.Response(response1); // flaky: org.junit.Assert.fail("Expected exception of type java.io.IOException; message: Too many redirects occurred trying to load URL null"); } catch (java.io.IOException e) { // Expected exception. } org.junit.Assert.assertNull(strEntry5); org.junit.Assert.assertTrue("'" + int8 + "' != '" + 0 + "'", int8 == 0); org.junit.Assert.assertNull(byteBuffer11); org.junit.Assert.assertNull(strEntry13); org.junit.Assert.assertTrue("'" + boolean19 + "' != '" + false + "'", boolean19 == false); org.junit.Assert.assertNull(str20); org.junit.Assert.assertTrue("'" + int21 + "' != '" + 0 + "'", int21 == 0); }
@Test public void test20046() throws Throwable { if (debug) System.out.format("%n%s%n", "RegressionTest40.test20046"); org.jsoup.helper.HttpConnection.Response response0 = null; org.jsoup.helper.HttpConnection.Response response1 = new org.jsoup.helper.HttpConnection.Response(response0); org.jsoup.Connection.Request request2 = null; response1.req = request2; java.util.Map.Entry<java.lang.String, java.lang.String> strEntry5 = response1.scanHeaders("hi!"); response1.charset = "hi!"; int int8 = response1.numRedirects; response1.contentType = "hi!"; java.nio.ByteBuffer byteBuffer11 = response1.byteData; java.util.Map.Entry<java.lang.String, java.lang.String> strEntry13 = response1.scanHeaders(""); response1.numRedirects = (short) 10; response1.contentType = ""; boolean boolean19 = response1.hasCookie("hi!"); java.lang.String str20 = response1.statusMessage(); int int21 = response1.statusCode(); try { org.jsoup.helper.HttpConnection.Response response22 = new org.jsoup.helper.HttpConnection.Response(response1); } catch (java.io.IOException e) { } org.junit.Assert.assertNull(strEntry5); org.junit.Assert.assertTrue("'" + int8 + "' != '" + 0 + "'", int8 == 0); org.junit.Assert.assertNull(byteBuffer11); org.junit.Assert.assertNull(strEntry13); org.junit.Assert.assertTrue("'" + boolean19 + "' != '" + false + "'", boolean19 == false); org.junit.Assert.assertNull(str20); org.junit.Assert.assertTrue("'" + int21 + "' != '" + 0 + "'", int21 == 0); }
@test public void test20046() throws throwable { if (debug) system.out.format("%n%s%n", "regressiontest40.test20046"); org.jsoup.helper.httpconnection.response response0 = null; org.jsoup.helper.httpconnection.response response1 = new org.jsoup.helper.httpconnection.response(response0); org.jsoup.connection.request request2 = null; response1.req = request2; java.util.map.entry<java.lang.string, java.lang.string> strentry5 = response1.scanheaders("hi!"); response1.charset = "hi!"; int int8 = response1.numredirects; response1.contenttype = "hi!"; java.nio.bytebuffer bytebuffer11 = response1.bytedata; java.util.map.entry<java.lang.string, java.lang.string> strentry13 = response1.scanheaders(""); response1.numredirects = (short) 10; response1.contenttype = ""; boolean boolean19 = response1.hascookie("hi!"); java.lang.string str20 = response1.statusmessage(); int int21 = response1.statuscode(); try { org.jsoup.helper.httpconnection.response response22 = new org.jsoup.helper.httpconnection.response(response1); } catch (java.io.ioexception e) { } org.junit.assert.assertnull(strentry5); org.junit.assert.asserttrue("'" + int8 + "' != '" + 0 + "'", int8 == 0); org.junit.assert.assertnull(bytebuffer11); org.junit.assert.assertnull(strentry13); org.junit.assert.asserttrue("'" + boolean19 + "' != '" + false + "'", boolean19 == false); org.junit.assert.assertnull(str20); org.junit.assert.asserttrue("'" + int21 + "' != '" + 0 + "'", int21 == 0); }
leusonmario/2022PhDThesis
[ 0, 0, 1, 0 ]
10,871
private void checkNullable() { if (ConfigurationAnnotations.getNullableType(element).isPresent()) { report.addWarning("@Nullable on @Produces methods does not do anything"); } }
private void checkNullable() { if (ConfigurationAnnotations.getNullableType(element).isPresent()) { report.addWarning("@Nullable on @Produces methods does not do anything"); } }
private void checknullable() { if (configurationannotations.getnullabletype(element).ispresent()) { report.addwarning("@nullable on @produces methods does not do anything"); } }
lynnfield/dagger
[ 0, 1, 0, 0 ]
19,094
private IMRIValueListener createValueListener() { return new IMRIValueListener() { @Override public void valueChanged(MRIValueEvent event) { if (event.getValue() instanceof CompositeData) { // FIXME: change to a better test of containment? dispose(); m_repository.movePossibleChildSubscriptions(UnavailableChildSubscriptions.this); } } }; }
private IMRIValueListener createValueListener() { return new IMRIValueListener() { @Override public void valueChanged(MRIValueEvent event) { if (event.getValue() instanceof CompositeData) { dispose(); m_repository.movePossibleChildSubscriptions(UnavailableChildSubscriptions.this); } } }; }
private imrivaluelistener createvaluelistener() { return new imrivaluelistener() { @override public void valuechanged(mrivalueevent event) { if (event.getvalue() instanceof compositedata) { dispose(); m_repository.movepossiblechildsubscriptions(unavailablechildsubscriptions.this); } } }; }
meghasfdc/jmc
[ 1, 0, 0, 0 ]
19,169
private boolean ruleMatches(String text, String pattern) { int patternPos = 0; int textPos = 0; int patternEnd = pattern.length(); int textEnd = text.length(); boolean containsEndChar = pattern.endsWith("$"); if (containsEndChar) { patternEnd -= 1; } while ((patternPos < patternEnd) && (textPos < textEnd)) { // Find next wildcard in the pattern. int wildcardPos = pattern.indexOf('*', patternPos); if (wildcardPos == -1) { wildcardPos = patternEnd; } // If we're at a wildcard in the pattern, find the place in the text // where the character(s) after the wildcard match up with what's in // the text. if (wildcardPos == patternPos) { patternPos += 1; if (patternPos >= patternEnd) { // Pattern ends with '*', we're all good. return true; } // TODO - don't worry about having two '*' in a row? // Find the end of the pattern piece we need to match. int patternPieceEnd = pattern.indexOf('*', patternPos); if (patternPieceEnd == -1) { patternPieceEnd = patternEnd; } boolean matched = false; int patternPieceLen = patternPieceEnd - patternPos; while ((textPos + patternPieceLen <= textEnd) && !matched) { // See if patternPieceLen chars from text at textPos match // chars from pattern at patternPos matched = true; for (int i = 0; i < patternPieceLen && matched; i++) { if (text.charAt(textPos + i) != pattern.charAt(patternPos + i)) { matched = false; } } // If we matched, we're all set, otherwise we have to // advance textPos if (!matched) { textPos += 1; } } // If we matched, we're all set, otherwise we failed if (!matched) { return false; } } else { // See if the pattern from patternPos to wildcardPos matches the // text starting at textPos while ((patternPos < wildcardPos) && (textPos < textEnd)) { if (text.charAt(textPos++) != pattern.charAt(patternPos++)) { return false; } } } } // If we didn't reach the end of the pattern, make sure we're not at a // wildcard, that's a 0 or more match, so then we're still OK. while ((patternPos < patternEnd) && (pattern.charAt(patternPos) == '*')) { patternPos += 1; } // We're at the end, so we have a match if the pattern was completely // consumed, and either we consumed all the text or we didn't have to // match it all (no '$' at end of the pattern) return (patternPos == patternEnd) && ((textPos == textEnd) || !containsEndChar); }
private boolean ruleMatches(String text, String pattern) { int patternPos = 0; int textPos = 0; int patternEnd = pattern.length(); int textEnd = text.length(); boolean containsEndChar = pattern.endsWith("$"); if (containsEndChar) { patternEnd -= 1; } while ((patternPos < patternEnd) && (textPos < textEnd)) { int wildcardPos = pattern.indexOf('*', patternPos); if (wildcardPos == -1) { wildcardPos = patternEnd; } if (wildcardPos == patternPos) { patternPos += 1; if (patternPos >= patternEnd) { return true; } int patternPieceEnd = pattern.indexOf('*', patternPos); if (patternPieceEnd == -1) { patternPieceEnd = patternEnd; } boolean matched = false; int patternPieceLen = patternPieceEnd - patternPos; while ((textPos + patternPieceLen <= textEnd) && !matched) { matched = true; for (int i = 0; i < patternPieceLen && matched; i++) { if (text.charAt(textPos + i) != pattern.charAt(patternPos + i)) { matched = false; } } if (!matched) { textPos += 1; } } if (!matched) { return false; } } else { while ((patternPos < wildcardPos) && (textPos < textEnd)) { if (text.charAt(textPos++) != pattern.charAt(patternPos++)) { return false; } } } } while ((patternPos < patternEnd) && (pattern.charAt(patternPos) == '*')) { patternPos += 1; } return (patternPos == patternEnd) && ((textPos == textEnd) || !containsEndChar); }
private boolean rulematches(string text, string pattern) { int patternpos = 0; int textpos = 0; int patternend = pattern.length(); int textend = text.length(); boolean containsendchar = pattern.endswith("$"); if (containsendchar) { patternend -= 1; } while ((patternpos < patternend) && (textpos < textend)) { int wildcardpos = pattern.indexof('*', patternpos); if (wildcardpos == -1) { wildcardpos = patternend; } if (wildcardpos == patternpos) { patternpos += 1; if (patternpos >= patternend) { return true; } int patternpieceend = pattern.indexof('*', patternpos); if (patternpieceend == -1) { patternpieceend = patternend; } boolean matched = false; int patternpiecelen = patternpieceend - patternpos; while ((textpos + patternpiecelen <= textend) && !matched) { matched = true; for (int i = 0; i < patternpiecelen && matched; i++) { if (text.charat(textpos + i) != pattern.charat(patternpos + i)) { matched = false; } } if (!matched) { textpos += 1; } } if (!matched) { return false; } } else { while ((patternpos < wildcardpos) && (textpos < textend)) { if (text.charat(textpos++) != pattern.charat(patternpos++)) { return false; } } } } while ((patternpos < patternend) && (pattern.charat(patternpos) == '*')) { patternpos += 1; } return (patternpos == patternend) && ((textpos == textend) || !containsendchar); }
kovyrin/crawler-commons
[ 1, 0, 0, 0 ]
11,110
private void validateImportPackage(IProgressMonitor monitor) { IHeader header = getHeader(Constants.IMPORT_PACKAGE); if (header == null) return; BundleDescription desc = fModel.getBundleDescription(); if (desc == null) { ManifestElement[] elements = header.getElements(); for (int i = 0; i < elements.length; i++) { validateSpecificationVersionAttribute(header, elements[i]); validateImportPackageVersion(header, elements[i]); } return; } boolean hasUnresolved = false; VersionConstraint[] constraints = desc.getContainingState().getStateHelper().getUnsatisfiedConstraints(desc); for (int i = 0; i < constraints.length; i++) { if (constraints[i] instanceof ImportPackageSpecification) { hasUnresolved = true; break; } } HashMap<String, ExportPackageDescription> exported = getAvailableExportedPackages(desc.getContainingState()); ImportPackageSpecification[] imports = desc.getImportPackages(); if (desc.hasDynamicImports()) { List<ImportPackageSpecification> staticImportsList = new ArrayList(); for (int i = 0; i < imports.length; ++i) { if (!imports[i].getDirective(Constants.RESOLUTION_DIRECTIVE).equals(ImportPackageSpecification.RESOLUTION_DYNAMIC)) staticImportsList.add(imports[i]); } imports = staticImportsList.toArray(new ImportPackageSpecification[staticImportsList.size()]); } ManifestElement[] elements = header.getElements(); int index = 0; for (int i = 0; i < elements.length; i++) { checkCanceled(monitor); validateSpecificationVersionAttribute(header, elements[i]); validateResolutionDirective(header, elements[i]); // TODO we should only validate versions that we have a match validateImportPackageVersion(header, elements[i]); if (!hasUnresolved) continue; int length = elements[i].getValueComponents().length; for (int j = 0; j < length; j++) { ImportPackageSpecification importSpec = imports[index++]; String name = importSpec.getName(); if (//$NON-NLS-1$ //$NON-NLS-2$ name.equals("java") || name.startsWith("java.")) { IHeader jreHeader = getHeader(ICoreConstants.ECLIPSE_JREBUNDLE); if (jreHeader == null || !"true".equals(//$NON-NLS-1$ jreHeader.getValue())) { report(PDECoreMessages.BundleErrorReporter_importNoJRE, getPackageLine(header, elements[i]), CompilerFlags.ERROR, PDEMarkerFactory.M_JAVA_PACKAGE__PORTED, PDEMarkerFactory.CAT_FATAL); continue; } } if (importSpec.isResolved() || !isCheckUnresolvedImports()) continue; boolean optional = isOptional(elements[i]); int severity = getRequireBundleSeverity(elements[i], optional); ExportPackageDescription export = exported.get(name); if (export != null) { if (export.getSupplier().isResolved()) { Version version = export.getVersion(); org.eclipse.osgi.service.resolver.VersionRange range = importSpec.getVersionRange(); if (range != null && !range.isIncluded(version)) { report(NLS.bind(PDECoreMessages.BundleErrorReporter_unsatisfiedConstraint, importSpec.toString()), getPackageLine(header, elements[i]), severity, PDEMarkerFactory.CAT_FATAL); } } else { report(NLS.bind(PDECoreMessages.BundleErrorReporter_unresolvedExporter, new String[] { export.getSupplier().getSymbolicName(), name }), getPackageLine(header, elements[i]), severity, PDEMarkerFactory.CAT_OTHER); } } else { IMarker marker = report(NLS.bind(PDECoreMessages.BundleErrorReporter_PackageNotExported, name), getPackageLine(header, elements[i]), severity, PDEMarkerFactory.M_IMPORT_PKG_NOT_AVAILABLE, PDEMarkerFactory.CAT_FATAL); try { if (marker != null) { //$NON-NLS-1$ marker.setAttribute(//$NON-NLS-1$ "packageName", //$NON-NLS-1$ name); if (optional) //$NON-NLS-1$ marker.setAttribute(//$NON-NLS-1$ "optional", //$NON-NLS-1$ true); } } catch (CoreException e) { } } } } }
private void validateImportPackage(IProgressMonitor monitor) { IHeader header = getHeader(Constants.IMPORT_PACKAGE); if (header == null) return; BundleDescription desc = fModel.getBundleDescription(); if (desc == null) { ManifestElement[] elements = header.getElements(); for (int i = 0; i < elements.length; i++) { validateSpecificationVersionAttribute(header, elements[i]); validateImportPackageVersion(header, elements[i]); } return; } boolean hasUnresolved = false; VersionConstraint[] constraints = desc.getContainingState().getStateHelper().getUnsatisfiedConstraints(desc); for (int i = 0; i < constraints.length; i++) { if (constraints[i] instanceof ImportPackageSpecification) { hasUnresolved = true; break; } } HashMap<String, ExportPackageDescription> exported = getAvailableExportedPackages(desc.getContainingState()); ImportPackageSpecification[] imports = desc.getImportPackages(); if (desc.hasDynamicImports()) { List<ImportPackageSpecification> staticImportsList = new ArrayList(); for (int i = 0; i < imports.length; ++i) { if (!imports[i].getDirective(Constants.RESOLUTION_DIRECTIVE).equals(ImportPackageSpecification.RESOLUTION_DYNAMIC)) staticImportsList.add(imports[i]); } imports = staticImportsList.toArray(new ImportPackageSpecification[staticImportsList.size()]); } ManifestElement[] elements = header.getElements(); int index = 0; for (int i = 0; i < elements.length; i++) { checkCanceled(monitor); validateSpecificationVersionAttribute(header, elements[i]); validateResolutionDirective(header, elements[i]); validateImportPackageVersion(header, elements[i]); if (!hasUnresolved) continue; int length = elements[i].getValueComponents().length; for (int j = 0; j < length; j++) { ImportPackageSpecification importSpec = imports[index++]; String name = importSpec.getName(); if name.equals("java") || name.startsWith("java.")) { IHeader jreHeader = getHeader(ICoreConstants.ECLIPSE_JREBUNDLE); if (jreHeader == null || !"true".equals jreHeader.getValue())) { report(PDECoreMessages.BundleErrorReporter_importNoJRE, getPackageLine(header, elements[i]), CompilerFlags.ERROR, PDEMarkerFactory.M_JAVA_PACKAGE__PORTED, PDEMarkerFactory.CAT_FATAL); continue; } } if (importSpec.isResolved() || !isCheckUnresolvedImports()) continue; boolean optional = isOptional(elements[i]); int severity = getRequireBundleSeverity(elements[i], optional); ExportPackageDescription export = exported.get(name); if (export != null) { if (export.getSupplier().isResolved()) { Version version = export.getVersion(); org.eclipse.osgi.service.resolver.VersionRange range = importSpec.getVersionRange(); if (range != null && !range.isIncluded(version)) { report(NLS.bind(PDECoreMessages.BundleErrorReporter_unsatisfiedConstraint, importSpec.toString()), getPackageLine(header, elements[i]), severity, PDEMarkerFactory.CAT_FATAL); } } else { report(NLS.bind(PDECoreMessages.BundleErrorReporter_unresolvedExporter, new String[] { export.getSupplier().getSymbolicName(), name }), getPackageLine(header, elements[i]), severity, PDEMarkerFactory.CAT_OTHER); } } else { IMarker marker = report(NLS.bind(PDECoreMessages.BundleErrorReporter_PackageNotExported, name), getPackageLine(header, elements[i]), severity, PDEMarkerFactory.M_IMPORT_PKG_NOT_AVAILABLE, PDEMarkerFactory.CAT_FATAL); try { if (marker != null) { marker.setAttribute "packageName", name); if (optional) marker.setAttribute "optional", true); } } catch (CoreException e) { } } } } }
private void validateimportpackage(iprogressmonitor monitor) { iheader header = getheader(constants.import_package); if (header == null) return; bundledescription desc = fmodel.getbundledescription(); if (desc == null) { manifestelement[] elements = header.getelements(); for (int i = 0; i < elements.length; i++) { validatespecificationversionattribute(header, elements[i]); validateimportpackageversion(header, elements[i]); } return; } boolean hasunresolved = false; versionconstraint[] constraints = desc.getcontainingstate().getstatehelper().getunsatisfiedconstraints(desc); for (int i = 0; i < constraints.length; i++) { if (constraints[i] instanceof importpackagespecification) { hasunresolved = true; break; } } hashmap<string, exportpackagedescription> exported = getavailableexportedpackages(desc.getcontainingstate()); importpackagespecification[] imports = desc.getimportpackages(); if (desc.hasdynamicimports()) { list<importpackagespecification> staticimportslist = new arraylist(); for (int i = 0; i < imports.length; ++i) { if (!imports[i].getdirective(constants.resolution_directive).equals(importpackagespecification.resolution_dynamic)) staticimportslist.add(imports[i]); } imports = staticimportslist.toarray(new importpackagespecification[staticimportslist.size()]); } manifestelement[] elements = header.getelements(); int index = 0; for (int i = 0; i < elements.length; i++) { checkcanceled(monitor); validatespecificationversionattribute(header, elements[i]); validateresolutiondirective(header, elements[i]); validateimportpackageversion(header, elements[i]); if (!hasunresolved) continue; int length = elements[i].getvaluecomponents().length; for (int j = 0; j < length; j++) { importpackagespecification importspec = imports[index++]; string name = importspec.getname(); if name.equals("java") || name.startswith("java.")) { iheader jreheader = getheader(icoreconstants.eclipse_jrebundle); if (jreheader == null || !"true".equals jreheader.getvalue())) { report(pdecoremessages.bundleerrorreporter_importnojre, getpackageline(header, elements[i]), compilerflags.error, pdemarkerfactory.m_java_package__ported, pdemarkerfactory.cat_fatal); continue; } } if (importspec.isresolved() || !ischeckunresolvedimports()) continue; boolean optional = isoptional(elements[i]); int severity = getrequirebundleseverity(elements[i], optional); exportpackagedescription export = exported.get(name); if (export != null) { if (export.getsupplier().isresolved()) { version version = export.getversion(); org.eclipse.osgi.service.resolver.versionrange range = importspec.getversionrange(); if (range != null && !range.isincluded(version)) { report(nls.bind(pdecoremessages.bundleerrorreporter_unsatisfiedconstraint, importspec.tostring()), getpackageline(header, elements[i]), severity, pdemarkerfactory.cat_fatal); } } else { report(nls.bind(pdecoremessages.bundleerrorreporter_unresolvedexporter, new string[] { export.getsupplier().getsymbolicname(), name }), getpackageline(header, elements[i]), severity, pdemarkerfactory.cat_other); } } else { imarker marker = report(nls.bind(pdecoremessages.bundleerrorreporter_packagenotexported, name), getpackageline(header, elements[i]), severity, pdemarkerfactory.m_import_pkg_not_available, pdemarkerfactory.cat_fatal); try { if (marker != null) { marker.setattribute "packagename", name); if (optional) marker.setattribute "optional", true); } } catch (coreexception e) { } } } } }
masud-technope/BLIZZARD-Replication-Package-ESEC-FSE2018
[ 1, 0, 0, 0 ]
3,341
@Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.clean_all: db.open(); db.drop(); db.close(); break; case R.id.manage_backup: db.Backup(); break; case R.id.manage_funds: startActivityForResult(new Intent(BilansView.this, BilansStatusSetting.class), 1); break; /* TODO: check for possibility to chain/join/combine xml menus TODO: manage recurring funds (ie set monthly incomes/payments) */ default: Log.e (TAG, "MENU = WTF?"); } return super.onOptionsItemSelected(item); }
@Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.clean_all: db.open(); db.drop(); db.close(); break; case R.id.manage_backup: db.Backup(); break; case R.id.manage_funds: startActivityForResult(new Intent(BilansView.this, BilansStatusSetting.class), 1); break; default: Log.e (TAG, "MENU = WTF?"); } return super.onOptionsItemSelected(item); }
@override public boolean onoptionsitemselected(menuitem item) { switch(item.getitemid()) { case r.id.clean_all: db.open(); db.drop(); db.close(); break; case r.id.manage_backup: db.backup(); break; case r.id.manage_funds: startactivityforresult(new intent(bilansview.this, bilansstatussetting.class), 1); break; default: log.e (tag, "menu = wtf?"); } return super.onoptionsitemselected(item); }
kkrolczyk/Schowek
[ 0, 1, 0, 0 ]
3,342
private void updateSingleAccount(double amount, String account_name) { // ok nasty hack here. Currently account have no idea which direction money flows. // so for now - hardcoded for backwards compatiblility if (account_name.equals("bankomat")){ status_disp.transfer_resources("karta konto 1", "gotowka", (float) amount); // TODO: remove hardcoded account names...crashes if names dont match } else { status_disp.reduce_wealth(account_name, (float) amount); Log.e(TAG, account_name + " " + amount); } }
private void updateSingleAccount(double amount, String account_name) { if (account_name.equals("bankomat")){ status_disp.transfer_resources("karta konto 1", "gotowka", (float) amount); } else { status_disp.reduce_wealth(account_name, (float) amount); Log.e(TAG, account_name + " " + amount); } }
private void updatesingleaccount(double amount, string account_name) { if (account_name.equals("bankomat")){ status_disp.transfer_resources("karta konto 1", "gotowka", (float) amount); } else { status_disp.reduce_wealth(account_name, (float) amount); log.e(tag, account_name + " " + amount); } }
kkrolczyk/Schowek
[ 1, 0, 1, 0 ]
19,798
protected void onDragonDeath(EnderDragon dragon) { log("The dragon died."); if (_stageNumber != 11) { log("But we're not in stage 11, so it doesn't count."); return; } if (DragonFight.CONFIG.FIGHT_OWNER == null) { log("But nobody owns the fight, so it doesn't count."); return; } // Bukkit.getOfflinePlayer() NEVER returns null, even for non-existent. OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(DragonFight.CONFIG.FIGHT_OWNER); getNearbyPlayers().forEach(p -> p.sendMessage(ChatColor.LIGHT_PURPLE + offlinePlayer.getName() + ChatColor.DARK_PURPLE + " was awarded the prize for defeating the dragon.")); Player player = offlinePlayer.getPlayer(); if (player == null) { // Fight owner is offline. Record an unclaimed prize. log("An unclaimed prize was added to offline fight owner " + offlinePlayer.getName() + "."); getNearbyPlayers().forEach(p -> p.sendMessage(ChatColor.DARK_PURPLE + "They can claim it when they log in.")); DragonFight.CONFIG.incUnclaimedPrizes(offlinePlayer.getUniqueId(), 1); } else { // Select a single drop from the `df-dragon-drops` loot set. // TODO: actually, multiple drops should be supported, once // BeastMaster supports deferred item drops. log("Generating dragon prizes for " + player.getName()); List<ItemStack> prizes = generatePrizes(); if (!givePrizes(player, prizes)) { // The item(s) did not fit, so player must claim with command. DragonFight.CONFIG.incUnclaimedPrizes(offlinePlayer.getUniqueId(), 1); String slots = ChatColor.LIGHT_PURPLE + Integer.toString(prizes.size()) + ChatColor.DARK_PURPLE + " inventory slot" + (prizes.size() > 1 ? "s" : ""); player.sendMessage(ChatColor.DARK_PURPLE + "You need at least " + slots + " empty."); player.sendMessage(ChatColor.DARK_PURPLE + "Run " + ChatColor.LIGHT_PURPLE + "/dragon prize" + ChatColor.DARK_PURPLE + " to claim your prize."); } } // Clear the fight owner once prizes have been given or unclaimed prizes // recorded, to prevent extra prizes if spurious dragons spawn. DragonFight.CONFIG.FIGHT_OWNER = null; DragonFight.CONFIG.save(); }
protected void onDragonDeath(EnderDragon dragon) { log("The dragon died."); if (_stageNumber != 11) { log("But we're not in stage 11, so it doesn't count."); return; } if (DragonFight.CONFIG.FIGHT_OWNER == null) { log("But nobody owns the fight, so it doesn't count."); return; } OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(DragonFight.CONFIG.FIGHT_OWNER); getNearbyPlayers().forEach(p -> p.sendMessage(ChatColor.LIGHT_PURPLE + offlinePlayer.getName() + ChatColor.DARK_PURPLE + " was awarded the prize for defeating the dragon.")); Player player = offlinePlayer.getPlayer(); if (player == null) { log("An unclaimed prize was added to offline fight owner " + offlinePlayer.getName() + "."); getNearbyPlayers().forEach(p -> p.sendMessage(ChatColor.DARK_PURPLE + "They can claim it when they log in.")); DragonFight.CONFIG.incUnclaimedPrizes(offlinePlayer.getUniqueId(), 1); } else { log("Generating dragon prizes for " + player.getName()); List<ItemStack> prizes = generatePrizes(); if (!givePrizes(player, prizes)) { DragonFight.CONFIG.incUnclaimedPrizes(offlinePlayer.getUniqueId(), 1); String slots = ChatColor.LIGHT_PURPLE + Integer.toString(prizes.size()) + ChatColor.DARK_PURPLE + " inventory slot" + (prizes.size() > 1 ? "s" : ""); player.sendMessage(ChatColor.DARK_PURPLE + "You need at least " + slots + " empty."); player.sendMessage(ChatColor.DARK_PURPLE + "Run " + ChatColor.LIGHT_PURPLE + "/dragon prize" + ChatColor.DARK_PURPLE + " to claim your prize."); } } DragonFight.CONFIG.FIGHT_OWNER = null; DragonFight.CONFIG.save(); }
protected void ondragondeath(enderdragon dragon) { log("the dragon died."); if (_stagenumber != 11) { log("but we're not in stage 11, so it doesn't count."); return; } if (dragonfight.config.fight_owner == null) { log("but nobody owns the fight, so it doesn't count."); return; } offlineplayer offlineplayer = bukkit.getofflineplayer(dragonfight.config.fight_owner); getnearbyplayers().foreach(p -> p.sendmessage(chatcolor.light_purple + offlineplayer.getname() + chatcolor.dark_purple + " was awarded the prize for defeating the dragon.")); player player = offlineplayer.getplayer(); if (player == null) { log("an unclaimed prize was added to offline fight owner " + offlineplayer.getname() + "."); getnearbyplayers().foreach(p -> p.sendmessage(chatcolor.dark_purple + "they can claim it when they log in.")); dragonfight.config.incunclaimedprizes(offlineplayer.getuniqueid(), 1); } else { log("generating dragon prizes for " + player.getname()); list<itemstack> prizes = generateprizes(); if (!giveprizes(player, prizes)) { dragonfight.config.incunclaimedprizes(offlineplayer.getuniqueid(), 1); string slots = chatcolor.light_purple + integer.tostring(prizes.size()) + chatcolor.dark_purple + " inventory slot" + (prizes.size() > 1 ? "s" : ""); player.sendmessage(chatcolor.dark_purple + "you need at least " + slots + " empty."); player.sendmessage(chatcolor.dark_purple + "run " + chatcolor.light_purple + "/dragon prize" + chatcolor.dark_purple + " to claim your prize."); } } dragonfight.config.fight_owner = null; dragonfight.config.save(); }
kadenscott/DragonFight
[ 1, 0, 0, 0 ]
11,718
@Override protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { try { Map<String, String> authenticatorProperties = context.getAuthenticatorProperties(); String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID); String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET); String tokenEndPoint = getTokenEndpoint(authenticatorProperties); if (tokenEndPoint == null) { tokenEndPoint = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_TOKEN_URL); } String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL); log.debug("callBackUrl : " + callBackUrl); if (callBackUrl == null) { callBackUrl = CarbonUIUtil.getAdminConsoleURL(request); callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth"); } @SuppressWarnings({"unchecked"}) Map<String, String> paramValueMap = (Map<String, String>) context.getProperty("oidc:param.map"); if (paramValueMap != null && paramValueMap.containsKey("redirect_uri")) { callBackUrl = paramValueMap.get("redirect_uri"); } OAuthAuthzResponse authzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request); String code = authzResponse.getCode(); OAuthClientRequest accessRequest; try { accessRequest = OAuthClientRequest.tokenLocation(tokenEndPoint) .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret) .setRedirectURI(callBackUrl).setCode(code).buildBodyMessage(); } catch (OAuthSystemException e) { throw new AuthenticationFailedException("Exception while building request for request access token", e); } // create OAuth client that uses custom http client under the hood OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthClientResponse oAuthResponse; try { oAuthResponse = oAuthClient.accessToken(accessRequest); } catch (OAuthSystemException e) { if (log.isDebugEnabled()) { log.debug("Exception while requesting access token", e); } throw new AuthenticationFailedException("Exception while requesting access token", e); } // TODO : return access token and id token to framework String accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN); String idToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ID_TOKEN); if (accessToken != null && (idToken != null || !requiredIDToken(authenticatorProperties))) { context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken); if (idToken != null) { context.setProperty(OIDCAuthenticatorConstants.ID_TOKEN, idToken); String base64Body = idToken.split("\\.")[1]; byte[] decoded = Base64.decodeBase64(base64Body.getBytes()); String json = new String(decoded); if (log.isDebugEnabled()) { log.debug("Id token json string : " + json); } Map<String, Object> jsonObject = JSONUtils.parseJSON(json); if (jsonObject != null) { Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse); String authenticatedUser = (String) jsonObject.get(OIDCAuthenticatorConstants.Claim.EMAIL); AuthenticatedUser authenticatedUserObj = AuthenticatedUser .createFederateAuthenticatedUserFromSubjectIdentifier(authenticatedUser); authenticatedUserObj.setUserAttributes(claims); context.setSubject(authenticatedUserObj); } else { if (log.isDebugEnabled()) { log.debug("Decoded json object is null"); } throw new AuthenticationFailedException("Decoded json object is null"); } } else { if (log.isDebugEnabled()) { log.debug("Authentication Failed"); } throw new AuthenticationFailedException("Authentication Failed"); } } else { throw new AuthenticationFailedException("Authentication Failed"); } } catch (OAuthProblemException e) { throw new AuthenticationFailedException("Error occurred while acquiring access token", e); } catch (JSONException e) { throw new AuthenticationFailedException("Error occurred while parsing json object", e); } }
@Override protected void processAuthenticationResponse(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { try { Map<String, String> authenticatorProperties = context.getAuthenticatorProperties(); String clientId = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_ID); String clientSecret = authenticatorProperties.get(OIDCAuthenticatorConstants.CLIENT_SECRET); String tokenEndPoint = getTokenEndpoint(authenticatorProperties); if (tokenEndPoint == null) { tokenEndPoint = authenticatorProperties.get(OIDCAuthenticatorConstants.OAUTH2_TOKEN_URL); } String callBackUrl = authenticatorProperties.get(GoogleOAuth2AuthenticationConstant.CALLBACK_URL); log.debug("callBackUrl : " + callBackUrl); if (callBackUrl == null) { callBackUrl = CarbonUIUtil.getAdminConsoleURL(request); callBackUrl = callBackUrl.replace("commonauth/carbon/", "commonauth"); } @SuppressWarnings({"unchecked"}) Map<String, String> paramValueMap = (Map<String, String>) context.getProperty("oidc:param.map"); if (paramValueMap != null && paramValueMap.containsKey("redirect_uri")) { callBackUrl = paramValueMap.get("redirect_uri"); } OAuthAuthzResponse authzResponse = OAuthAuthzResponse.oauthCodeAuthzResponse(request); String code = authzResponse.getCode(); OAuthClientRequest accessRequest; try { accessRequest = OAuthClientRequest.tokenLocation(tokenEndPoint) .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret) .setRedirectURI(callBackUrl).setCode(code).buildBodyMessage(); } catch (OAuthSystemException e) { throw new AuthenticationFailedException("Exception while building request for request access token", e); } OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); OAuthClientResponse oAuthResponse; try { oAuthResponse = oAuthClient.accessToken(accessRequest); } catch (OAuthSystemException e) { if (log.isDebugEnabled()) { log.debug("Exception while requesting access token", e); } throw new AuthenticationFailedException("Exception while requesting access token", e); } String accessToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ACCESS_TOKEN); String idToken = oAuthResponse.getParam(OIDCAuthenticatorConstants.ID_TOKEN); if (accessToken != null && (idToken != null || !requiredIDToken(authenticatorProperties))) { context.setProperty(OIDCAuthenticatorConstants.ACCESS_TOKEN, accessToken); if (idToken != null) { context.setProperty(OIDCAuthenticatorConstants.ID_TOKEN, idToken); String base64Body = idToken.split("\\.")[1]; byte[] decoded = Base64.decodeBase64(base64Body.getBytes()); String json = new String(decoded); if (log.isDebugEnabled()) { log.debug("Id token json string : " + json); } Map<String, Object> jsonObject = JSONUtils.parseJSON(json); if (jsonObject != null) { Map<ClaimMapping, String> claims = getSubjectAttributes(oAuthResponse); String authenticatedUser = (String) jsonObject.get(OIDCAuthenticatorConstants.Claim.EMAIL); AuthenticatedUser authenticatedUserObj = AuthenticatedUser .createFederateAuthenticatedUserFromSubjectIdentifier(authenticatedUser); authenticatedUserObj.setUserAttributes(claims); context.setSubject(authenticatedUserObj); } else { if (log.isDebugEnabled()) { log.debug("Decoded json object is null"); } throw new AuthenticationFailedException("Decoded json object is null"); } } else { if (log.isDebugEnabled()) { log.debug("Authentication Failed"); } throw new AuthenticationFailedException("Authentication Failed"); } } else { throw new AuthenticationFailedException("Authentication Failed"); } } catch (OAuthProblemException e) { throw new AuthenticationFailedException("Error occurred while acquiring access token", e); } catch (JSONException e) { throw new AuthenticationFailedException("Error occurred while parsing json object", e); } }
@override protected void processauthenticationresponse(httpservletrequest request, httpservletresponse response, authenticationcontext context) throws authenticationfailedexception { try { map<string, string> authenticatorproperties = context.getauthenticatorproperties(); string clientid = authenticatorproperties.get(oidcauthenticatorconstants.client_id); string clientsecret = authenticatorproperties.get(oidcauthenticatorconstants.client_secret); string tokenendpoint = gettokenendpoint(authenticatorproperties); if (tokenendpoint == null) { tokenendpoint = authenticatorproperties.get(oidcauthenticatorconstants.oauth2_token_url); } string callbackurl = authenticatorproperties.get(googleoauth2authenticationconstant.callback_url); log.debug("callbackurl : " + callbackurl); if (callbackurl == null) { callbackurl = carbonuiutil.getadminconsoleurl(request); callbackurl = callbackurl.replace("commonauth/carbon/", "commonauth"); } @suppresswarnings({"unchecked"}) map<string, string> paramvaluemap = (map<string, string>) context.getproperty("oidc:param.map"); if (paramvaluemap != null && paramvaluemap.containskey("redirect_uri")) { callbackurl = paramvaluemap.get("redirect_uri"); } oauthauthzresponse authzresponse = oauthauthzresponse.oauthcodeauthzresponse(request); string code = authzresponse.getcode(); oauthclientrequest accessrequest; try { accessrequest = oauthclientrequest.tokenlocation(tokenendpoint) .setgranttype(granttype.authorization_code).setclientid(clientid).setclientsecret(clientsecret) .setredirecturi(callbackurl).setcode(code).buildbodymessage(); } catch (oauthsystemexception e) { throw new authenticationfailedexception("exception while building request for request access token", e); } oauthclient oauthclient = new oauthclient(new urlconnectionclient()); oauthclientresponse oauthresponse; try { oauthresponse = oauthclient.accesstoken(accessrequest); } catch (oauthsystemexception e) { if (log.isdebugenabled()) { log.debug("exception while requesting access token", e); } throw new authenticationfailedexception("exception while requesting access token", e); } string accesstoken = oauthresponse.getparam(oidcauthenticatorconstants.access_token); string idtoken = oauthresponse.getparam(oidcauthenticatorconstants.id_token); if (accesstoken != null && (idtoken != null || !requiredidtoken(authenticatorproperties))) { context.setproperty(oidcauthenticatorconstants.access_token, accesstoken); if (idtoken != null) { context.setproperty(oidcauthenticatorconstants.id_token, idtoken); string base64body = idtoken.split("\\.")[1]; byte[] decoded = base64.decodebase64(base64body.getbytes()); string json = new string(decoded); if (log.isdebugenabled()) { log.debug("id token json string : " + json); } map<string, object> jsonobject = jsonutils.parsejson(json); if (jsonobject != null) { map<claimmapping, string> claims = getsubjectattributes(oauthresponse); string authenticateduser = (string) jsonobject.get(oidcauthenticatorconstants.claim.email); authenticateduser authenticateduserobj = authenticateduser .createfederateauthenticateduserfromsubjectidentifier(authenticateduser); authenticateduserobj.setuserattributes(claims); context.setsubject(authenticateduserobj); } else { if (log.isdebugenabled()) { log.debug("decoded json object is null"); } throw new authenticationfailedexception("decoded json object is null"); } } else { if (log.isdebugenabled()) { log.debug("authentication failed"); } throw new authenticationfailedexception("authentication failed"); } } else { throw new authenticationfailedexception("authentication failed"); } } catch (oauthproblemexception e) { throw new authenticationfailedexception("error occurred while acquiring access token", e); } catch (jsonexception e) { throw new authenticationfailedexception("error occurred while parsing json object", e); } }
manjulaRathnayaka/carbon-identity
[ 0, 1, 0, 0 ]
11,781
public void displayStructure(QueryControl q_cntl, int index, HttpUtils h, XView xv, String cntl) throws MetadataValidationException, MetadataException { System.out.println("Related QueryContents"); this.displayStructureHeader(index, xv); Metadata m = getMetadata(); boolean object_refs = m.isObjectRefsOnly(); if (m.getWrapper() == null) { return; } xv.getMetadata().addMetadata(m); if (object_refs) { // no idea what to do here } else { String ref_id = this.getReferenceId(); h.indent1(xv.build_details_link(ref_id, cntl) + " (" + xv.build_xml_link(ref_id, cntl) + " " + ((m.isRetrievable_a(ref_id)) ? xv.build_ret_a_link(ref_id) + " " : "") + ((m.isRetrievable_b(ref_id)) ? xv.build_ret_b_link(ref_id) + " " : "") + ")"); // AMS 04/24/2009 - FIXME - Refactor this - 'else-if' and 'else' are pretty similar for (OMElement a_ele : m.getAssociations()) { String src_id = m.getAssocSource(a_ele); String a_type = m.getAssocType(a_ele); String a_id = m.getId(a_ele); String tgt_id = m.getAssocTarget(a_ele); if (src_id == null) { } else if (src_id != null && !src_id.equals(this.getReferenceId())) { if (MetadataSupport.xdsB_ihe_assoc_type_rplc.equals(a_type)) { a_type = "replaced by"; } else if (MetadataSupport.xdsB_ihe_assoc_type_apnd.equals(a_type)) { a_type = "has appended"; } else if (MetadataSupport.xdsB_ihe_assoc_type_xfrm.equals(a_type)) { a_type = "transformed to"; } else if (MetadataSupport.xdsB_ihe_assoc_type_issnapshotof.equals(a_type)) { a_type = "is snapshot of"; } else { a_type = a_type + " by"; } h.indent2(xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(src_id, cntl) + " (" + xv.build_xml_link(src_id, cntl) + " " + ((m.isRetrievable_a(tgt_id)) ? xv.build_ret_a_link(tgt_id) + " " : "") + ((m.isRetrievable_b(tgt_id)) ? xv.build_ret_b_link(tgt_id) + " " : "") + ") " + " [" + ((q_cntl.hasEndpoint()) ? xv.build_related_link(src_id) : "") + "]"); } else { if (MetadataSupport.xdsB_ihe_assoc_type_rplc.equals(a_type)) { a_type = "replaces"; } else if (MetadataSupport.xdsB_ihe_assoc_type_apnd.equals(a_type)) { a_type = "appended to"; } else if (MetadataSupport.xdsB_ihe_assoc_type_xfrm.equals(a_type)) { a_type = "transform of"; } h.indent2(xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(tgt_id, cntl) + " (" + xv.build_xml_link(tgt_id, cntl) + " " + ((m.isRetrievable_a(tgt_id)) ? xv.build_ret_a_link(tgt_id) + " " : "") + ((m.isRetrievable_b(tgt_id)) ? xv.build_ret_b_link(tgt_id) + " " : "") + ") " + " [" + ((q_cntl.hasEndpoint()) ? xv.build_related_link(tgt_id) : "") + "]"); } } } }
public void displayStructure(QueryControl q_cntl, int index, HttpUtils h, XView xv, String cntl) throws MetadataValidationException, MetadataException { System.out.println("Related QueryContents"); this.displayStructureHeader(index, xv); Metadata m = getMetadata(); boolean object_refs = m.isObjectRefsOnly(); if (m.getWrapper() == null) { return; } xv.getMetadata().addMetadata(m); if (object_refs) { } else { String ref_id = this.getReferenceId(); h.indent1(xv.build_details_link(ref_id, cntl) + " (" + xv.build_xml_link(ref_id, cntl) + " " + ((m.isRetrievable_a(ref_id)) ? xv.build_ret_a_link(ref_id) + " " : "") + ((m.isRetrievable_b(ref_id)) ? xv.build_ret_b_link(ref_id) + " " : "") + ")"); for (OMElement a_ele : m.getAssociations()) { String src_id = m.getAssocSource(a_ele); String a_type = m.getAssocType(a_ele); String a_id = m.getId(a_ele); String tgt_id = m.getAssocTarget(a_ele); if (src_id == null) { } else if (src_id != null && !src_id.equals(this.getReferenceId())) { if (MetadataSupport.xdsB_ihe_assoc_type_rplc.equals(a_type)) { a_type = "replaced by"; } else if (MetadataSupport.xdsB_ihe_assoc_type_apnd.equals(a_type)) { a_type = "has appended"; } else if (MetadataSupport.xdsB_ihe_assoc_type_xfrm.equals(a_type)) { a_type = "transformed to"; } else if (MetadataSupport.xdsB_ihe_assoc_type_issnapshotof.equals(a_type)) { a_type = "is snapshot of"; } else { a_type = a_type + " by"; } h.indent2(xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(src_id, cntl) + " (" + xv.build_xml_link(src_id, cntl) + " " + ((m.isRetrievable_a(tgt_id)) ? xv.build_ret_a_link(tgt_id) + " " : "") + ((m.isRetrievable_b(tgt_id)) ? xv.build_ret_b_link(tgt_id) + " " : "") + ") " + " [" + ((q_cntl.hasEndpoint()) ? xv.build_related_link(src_id) : "") + "]"); } else { if (MetadataSupport.xdsB_ihe_assoc_type_rplc.equals(a_type)) { a_type = "replaces"; } else if (MetadataSupport.xdsB_ihe_assoc_type_apnd.equals(a_type)) { a_type = "appended to"; } else if (MetadataSupport.xdsB_ihe_assoc_type_xfrm.equals(a_type)) { a_type = "transform of"; } h.indent2(xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(tgt_id, cntl) + " (" + xv.build_xml_link(tgt_id, cntl) + " " + ((m.isRetrievable_a(tgt_id)) ? xv.build_ret_a_link(tgt_id) + " " : "") + ((m.isRetrievable_b(tgt_id)) ? xv.build_ret_b_link(tgt_id) + " " : "") + ") " + " [" + ((q_cntl.hasEndpoint()) ? xv.build_related_link(tgt_id) : "") + "]"); } } } }
public void displaystructure(querycontrol q_cntl, int index, httputils h, xview xv, string cntl) throws metadatavalidationexception, metadataexception { system.out.println("related querycontents"); this.displaystructureheader(index, xv); metadata m = getmetadata(); boolean object_refs = m.isobjectrefsonly(); if (m.getwrapper() == null) { return; } xv.getmetadata().addmetadata(m); if (object_refs) { } else { string ref_id = this.getreferenceid(); h.indent1(xv.build_details_link(ref_id, cntl) + " (" + xv.build_xml_link(ref_id, cntl) + " " + ((m.isretrievable_a(ref_id)) ? xv.build_ret_a_link(ref_id) + " " : "") + ((m.isretrievable_b(ref_id)) ? xv.build_ret_b_link(ref_id) + " " : "") + ")"); for (omelement a_ele : m.getassociations()) { string src_id = m.getassocsource(a_ele); string a_type = m.getassoctype(a_ele); string a_id = m.getid(a_ele); string tgt_id = m.getassoctarget(a_ele); if (src_id == null) { } else if (src_id != null && !src_id.equals(this.getreferenceid())) { if (metadatasupport.xdsb_ihe_assoc_type_rplc.equals(a_type)) { a_type = "replaced by"; } else if (metadatasupport.xdsb_ihe_assoc_type_apnd.equals(a_type)) { a_type = "has appended"; } else if (metadatasupport.xdsb_ihe_assoc_type_xfrm.equals(a_type)) { a_type = "transformed to"; } else if (metadatasupport.xdsb_ihe_assoc_type_issnapshotof.equals(a_type)) { a_type = "is snapshot of"; } else { a_type = a_type + " by"; } h.indent2(xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(src_id, cntl) + " (" + xv.build_xml_link(src_id, cntl) + " " + ((m.isretrievable_a(tgt_id)) ? xv.build_ret_a_link(tgt_id) + " " : "") + ((m.isretrievable_b(tgt_id)) ? xv.build_ret_b_link(tgt_id) + " " : "") + ") " + " [" + ((q_cntl.hasendpoint()) ? xv.build_related_link(src_id) : "") + "]"); } else { if (metadatasupport.xdsb_ihe_assoc_type_rplc.equals(a_type)) { a_type = "replaces"; } else if (metadatasupport.xdsb_ihe_assoc_type_apnd.equals(a_type)) { a_type = "appended to"; } else if (metadatasupport.xdsb_ihe_assoc_type_xfrm.equals(a_type)) { a_type = "transform of"; } h.indent2(xv.build_assoc_link(a_id, a_type, cntl) + " " + xv.build_details_link(tgt_id, cntl) + " (" + xv.build_xml_link(tgt_id, cntl) + " " + ((m.isretrievable_a(tgt_id)) ? xv.build_ret_a_link(tgt_id) + " " : "") + ((m.isretrievable_b(tgt_id)) ? xv.build_ret_b_link(tgt_id) + " " : "") + ") " + " [" + ((q_cntl.hasendpoint()) ? xv.build_related_link(tgt_id) : "") + "]"); } } } }
kef/hieos
[ 1, 1, 0, 0 ]
3,600
public RemoteEventData[] readAhead(int maxEvents) throws IOException, ClassNotFoundException { boolean IOExceptionCaught = false; stateCheck(); if (debugState) { assertInvariants(); } // Check if empty if (isEmpty()) throw new NoSuchElementException(); long readCount = rcount; long readPosition = rpos; long logNum = getLogNum(readCount); File log = getLogFile(logNum); RemoteEvent evt = null; ArrayList rData = new ArrayList(); int i = 0; LogInputStream in = null; boolean done = false; printControlData(persistenceLogger, "Before read::readAhead"); if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() maxEvents = {0}", new Object[] {Integer.valueOf(maxEvents)}); } while ((readCount < wcount) && (rData.size() < maxEvents) && !done) { if (logNum != getLogNum(readCount)) { logNum = getLogNum(readCount); log = getLogFile(logNum); readPosition = 0; } try { // get the input stream in = streamPool.getLogInputStream(log, readPosition); // read the event evt = eventReader.read(in); // update readCount and readPosition readCount++; readPosition = in.getOffset(); // offset to next unread event //Generate new entry rData.add(new RemoteEventData( evt, new RemoteEventDataCursor(readCount, readPosition))); } catch (IOException ie) { // We'll get interrupted when asked to shutdown. // In this case, we can skip the call to nextReadAheadLog. if (ie instanceof InterruptedIOException) { if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() interrupted "); } // Stop processing events done = true; } else { if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() received IOException " + "... skipping to next read log"); } readCount = nextReadAheadLog(readCount); // TODO - rcount = readCount; // TODO - if bump rcount you need to bump wcount too // TODO - if bump counts then you need to persist them readPosition = 0; IOExceptionCaught = true; if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() new readCount is {0}", Long.valueOf(readCount)); } } if (persistenceLogger.isLoggable(Levels.HANDLED)) { persistenceLogger.log(Levels.HANDLED, "Exception: ", ie); } } catch (ClassNotFoundException cnfe) { // Note that the read offset is still valid since the // MarshalledObject extraction should always succeed. // It's just that the RemoteEvent within it could not // be reconstituted. Therefore, just skip to the next // MarshalledObject in the stream. readCount++; readPosition = in.getOffset(); //Generate new entry rData.add(new RemoteEventData( null, new RemoteEventDataCursor(readCount, readPosition))); if (persistenceLogger.isLoggable(Levels.HANDLED)) { persistenceLogger.log(Levels.HANDLED, "Exception: ", cnfe); } } finally { // If an IOException occurs then the eventReader is in // a bad state. Therefore, we get rid of our existing // reference and create a fresh one. The underlying // stream is also removed from from the pool, forcing // a fresh copy to be returned on the next "get" request. if (IOExceptionCaught) { //TODO (FCS) add close to interface //eventReader.close(); eventReader = new EventReader(); if (in != null) { streamPool.removeLogStream(in); in = null; } } else { if (in != null) streamPool.releaseLogStream(in); /* Shouldn't have to release since we have exclusive * access, but the next getLogInputStream assumes things * are on the freelist. */ } } } printControlData(persistenceLogger, "After Event::readAhead"); if (debugState) { assertInvariants(); } return (RemoteEventData[]) rData.toArray(new RemoteEventData[0]); }
public RemoteEventData[] readAhead(int maxEvents) throws IOException, ClassNotFoundException { boolean IOExceptionCaught = false; stateCheck(); if (debugState) { assertInvariants(); } if (isEmpty()) throw new NoSuchElementException(); long readCount = rcount; long readPosition = rpos; long logNum = getLogNum(readCount); File log = getLogFile(logNum); RemoteEvent evt = null; ArrayList rData = new ArrayList(); int i = 0; LogInputStream in = null; boolean done = false; printControlData(persistenceLogger, "Before read::readAhead"); if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() maxEvents = {0}", new Object[] {Integer.valueOf(maxEvents)}); } while ((readCount < wcount) && (rData.size() < maxEvents) && !done) { if (logNum != getLogNum(readCount)) { logNum = getLogNum(readCount); log = getLogFile(logNum); readPosition = 0; } try { in = streamPool.getLogInputStream(log, readPosition); evt = eventReader.read(in); readCount++; readPosition = in.getOffset(); rData.add(new RemoteEventData( evt, new RemoteEventDataCursor(readCount, readPosition))); } catch (IOException ie) { if (ie instanceof InterruptedIOException) { if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() interrupted "); } done = true; } else { if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() received IOException " + "... skipping to next read log"); } readCount = nextReadAheadLog(readCount); readPosition = 0; IOExceptionCaught = true; if (persistenceLogger.isLoggable(Level.FINEST)) { persistenceLogger.log(Level.FINEST, "EventLog::readAhead() new readCount is {0}", Long.valueOf(readCount)); } } if (persistenceLogger.isLoggable(Levels.HANDLED)) { persistenceLogger.log(Levels.HANDLED, "Exception: ", ie); } } catch (ClassNotFoundException cnfe) { readCount++; readPosition = in.getOffset(); rData.add(new RemoteEventData( null, new RemoteEventDataCursor(readCount, readPosition))); if (persistenceLogger.isLoggable(Levels.HANDLED)) { persistenceLogger.log(Levels.HANDLED, "Exception: ", cnfe); } } finally { if (IOExceptionCaught) { eventReader = new EventReader(); if (in != null) { streamPool.removeLogStream(in); in = null; } } else { if (in != null) streamPool.releaseLogStream(in); } } } printControlData(persistenceLogger, "After Event::readAhead"); if (debugState) { assertInvariants(); } return (RemoteEventData[]) rData.toArray(new RemoteEventData[0]); }
public remoteeventdata[] readahead(int maxevents) throws ioexception, classnotfoundexception { boolean ioexceptioncaught = false; statecheck(); if (debugstate) { assertinvariants(); } if (isempty()) throw new nosuchelementexception(); long readcount = rcount; long readposition = rpos; long lognum = getlognum(readcount); file log = getlogfile(lognum); remoteevent evt = null; arraylist rdata = new arraylist(); int i = 0; loginputstream in = null; boolean done = false; printcontroldata(persistencelogger, "before read::readahead"); if (persistencelogger.isloggable(level.finest)) { persistencelogger.log(level.finest, "eventlog::readahead() maxevents = {0}", new object[] {integer.valueof(maxevents)}); } while ((readcount < wcount) && (rdata.size() < maxevents) && !done) { if (lognum != getlognum(readcount)) { lognum = getlognum(readcount); log = getlogfile(lognum); readposition = 0; } try { in = streampool.getloginputstream(log, readposition); evt = eventreader.read(in); readcount++; readposition = in.getoffset(); rdata.add(new remoteeventdata( evt, new remoteeventdatacursor(readcount, readposition))); } catch (ioexception ie) { if (ie instanceof interruptedioexception) { if (persistencelogger.isloggable(level.finest)) { persistencelogger.log(level.finest, "eventlog::readahead() interrupted "); } done = true; } else { if (persistencelogger.isloggable(level.finest)) { persistencelogger.log(level.finest, "eventlog::readahead() received ioexception " + "... skipping to next read log"); } readcount = nextreadaheadlog(readcount); readposition = 0; ioexceptioncaught = true; if (persistencelogger.isloggable(level.finest)) { persistencelogger.log(level.finest, "eventlog::readahead() new readcount is {0}", long.valueof(readcount)); } } if (persistencelogger.isloggable(levels.handled)) { persistencelogger.log(levels.handled, "exception: ", ie); } } catch (classnotfoundexception cnfe) { readcount++; readposition = in.getoffset(); rdata.add(new remoteeventdata( null, new remoteeventdatacursor(readcount, readposition))); if (persistencelogger.isloggable(levels.handled)) { persistencelogger.log(levels.handled, "exception: ", cnfe); } } finally { if (ioexceptioncaught) { eventreader = new eventreader(); if (in != null) { streampool.removelogstream(in); in = null; } } else { if (in != null) streampool.releaselogstream(in); } } } printcontroldata(persistencelogger, "after event::readahead"); if (debugstate) { assertinvariants(); } return (remoteeventdata[]) rdata.toarray(new remoteeventdata[0]); }
mkleczek/river
[ 0, 1, 0, 0 ]
11,842
public LoginContext authenticate(String user, char[] password, String realm) { // consider modules: Krb5LoginModule, LdapLoginModule, NTLoginModule, // JndiLoginModule // ...sun... PassiveCallbackHandler cbh = new PassiveCallbackHandler(user, password); LoginContext lc; try { lc = new LoginContext(realm, cbh); // referenced in jaas.conf } catch (LoginException e) { LOG.error("Exception during new LoginContext()", e); return null; } try { // call callback to retrieve credentials, and checks that // Authentication fails lc.login(); } catch (LoginException e) { // FIXME. LoginException may happen either because authentication // failed, or for many other reasons. // We should ignore the first, and LOG the latter. LOG.error("Exception while loggin-in", e); return null; } finally { Arrays.fill(password, '\u0000'); } return lc; }
public LoginContext authenticate(String user, char[] password, String realm) { PassiveCallbackHandler cbh = new PassiveCallbackHandler(user, password); LoginContext lc; try { lc = new LoginContext(realm, cbh); } catch (LoginException e) { LOG.error("Exception during new LoginContext()", e); return null; } try { lc.login(); } catch (LoginException e) { LOG.error("Exception while loggin-in", e); return null; } finally { Arrays.fill(password, '\u0000'); } return lc; }
public logincontext authenticate(string user, char[] password, string realm) { passivecallbackhandler cbh = new passivecallbackhandler(user, password); logincontext lc; try { lc = new logincontext(realm, cbh); } catch (loginexception e) { log.error("exception during new logincontext()", e); return null; } try { lc.login(); } catch (loginexception e) { log.error("exception while loggin-in", e); return null; } finally { arrays.fill(password, '\u0000'); } return lc; }
luca-vercelli/java-web-template
[ 0, 0, 1, 0 ]