How do I solve this error: "source/MainMenuState.hx:25: characters 7-21 : Unexpected selectedOption" - haxe

I'm fairly new to HaxeFlixel and I wanted to see selectedOption change to see if there were any mistakes. But I was met with this error:
This is the file that had the error (MainMenuState.hx):
package;
import flixel.FlxState;
import flixel.FlxG;
import flixel.*;
import flixel.text.*;
import flixel.ui.*;
class MainMenuState extends FlxState
{
var optionsPre:Array<String> = ["New Game", "Settings", "Quit Game"];
var options:Array<String> = ["Continue Game", "Create New Game", "Settings", "Quit Game"];
var debugSelOpt:FlxText = FlxText.new(8, 8, 0, "Debug field", 8, false);
var selectedOption = 0;
override public function create()
{
super.create();
}
override public function update(elapsed:Float)
{
super.update(elapsed);
if (FlxG.keys.justPressed.UP) {
if selectedOption == optionsPre.length { // line with the supposed error
selectedOption = 0;
}
}
if (FlxG.keys.justPressed.DOWN) {
if selectedOption == 0 {
selectedOption = optionsPre.length;
}
}
}
debugSelOpt.text = "selectedOption value: " + selectedOption;
}
I'm quite unsure what's wrong in this script. Can someone help me here?

You need parentheses in your if statements.
if (selectedOption == ... )

Related

How to replace <w:sdt> Xml in Word Doc using Apache POI as XWPFSDT and XWPFSDTContent object is read-only

In previous code we would use XWPFSParagraph and Runs to find Merge Tokens that we would replace with data in our database. However, now we need to use Content Controls and do the same thing. The problem with Paragraph and Runs is that Content controls do not appear as a single run, like a Merge Token would. And we need to get the content control title to act like a Merge Token name would be so we know where to find the data in the database, and then replace it in the document. In Content Controls we wouldn't be replacing the Content Control with the data from the db, but we would have to set the Text value in the <w:sdtContentControl> with that data.
I thought about converting the <x:sdt> object into the xml text, but then it is now removed from the Poi object because it is now a string on its own.
So I was thinking of finding the <x:sdt> and fully replacing it with a new one where each part of it would be the same except the part in the <w:sdtContentControl> section. Is this possible? Any recommendations on how to use Poi to "modify" the sdt we get from the Word doc?
XWPFSDT as well as XWPFSDTCell are in experimental state up to now. They don't even have access to their underlying CTSdtBlock, CTSdtRun and CTSdtCell classes. I don't know why. So extending them to provide writing into the CTSdtBlock, CTSdtRun or CTSdtCell is not possible. If that is the need, then a new class is needed which can be created from any kind of Word SDT content control object. This class SDTContentControl could look like so:
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.values.XmlObjectBase;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class SDTContentControl {
private XmlObject object = null;
public SDTContentControl(XmlObject object) {
this.object = object;
}
public String getTitle() {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetAlias()) {
return ctSdtBlock.getSdtPr().getAlias().getVal();
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetAlias()) {
return ctSdtRun.getSdtPr().getAlias().getVal();
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetAlias()) {
return ctSdtCell.getSdtPr().getAlias().getVal();
}
}
}
return null;
}
public String getTag() {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetTag()) {
return ctSdtBlock.getSdtPr().getTag().getVal();
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetTag()) {
return ctSdtRun.getSdtPr().getTag().getVal();
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetTag()) {
return ctSdtCell.getSdtPr().getTag().getVal();
}
}
}
return null;
}
public String getContentText() {
XmlObject[] sdtContents = this.object.selectPath(
"declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' "
+".//w:sdtContent");
for (XmlObject sdtContent : sdtContents) {
if (sdtContent instanceof XmlObjectBase) {
return ((XmlObjectBase)sdtContent).getStringValue();
}
}
return null;
}
public void setContent(String text) {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtContent()) {
CTSdtContentBlock sdtContentBlock = ctSdtBlock.getSdtContent();
CTP ctP = sdtContentBlock.getPArray(0); if (ctP == null) ctP = CTP.Factory.newInstance();
for (int r = ctP.getRList().size()-1; r >= 0 ; r--) ctP.removeR(r);
CTR ctR = ctP.addNewR();
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtBlock.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
sdtContentBlock.setPArray(new CTP[]{ctP});
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtContent()) {
CTSdtContentRun sdtContentRun = ctSdtRun.getSdtContent();
CTR ctR = CTR.Factory.newInstance();
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtRun.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
sdtContentRun.setRArray(new CTR[]{ctR});
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtContent()) {
CTSdtContentCell sdtContentCell = ctSdtCell.getSdtContent();
for (int c = 0; c < sdtContentCell.getTcList().size(); c++) {
CTTc ctTc = sdtContentCell.getTcList().get(c);
CTP ctP = ctTc.getPArray(0); if (ctP == null) ctP = CTP.Factory.newInstance();
for (int r = ctP.getRList().size()-1; r >= 0 ; r--) ctP.removeR(r);
CTR ctR = ctP.addNewR();
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtCell.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
ctTc.setPArray(new CTP[]{ctP});
}
}
}
}
public void setContent(Calendar calendar) {
String dateFormat = "yyyy-MM-dd";
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetDate()) {
if (ctSdtBlock.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtBlock.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtBlock.getSdtPr().getDate().setFullDate(calendar);
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetDate()) {
if (ctSdtRun.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtRun.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtRun.getSdtPr().getDate().setFullDate(calendar);
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetDate()) {
if (ctSdtCell.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtCell.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtCell.getSdtPr().getDate().setFullDate(calendar);
}
}
}
SimpleDateFormat simpledDateFormat = new SimpleDateFormat(dateFormat);
String text = simpledDateFormat.format(calendar.getTime());
this.setContent(text);
}
public void setContent(BigDecimal value) {
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
String text = decimalFormat.format(value.doubleValue());
this.setContent(text);
}
public void setContent(Object content) {
if (content instanceof String) {
this.setContent((String)content);
} else if (content instanceof Calendar) {
this.setContent((Calendar)content);
} else if (content instanceof BigDecimal) {
this.setContent((BigDecimal)content);
//} else if (content instanceof ...) {
//ToDo
} else {
this.setContent(String.valueOf(content));
}
}
}
A list of all SDT content control objects can be created from a XWPFDocument like so:
...
/*modifiers*/ List<SDTContentControl> extractSDTsFromBody(XWPFDocument document) {
SDTContentControl sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<SDTContentControl> allsdts = new ArrayList<SDTContentControl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof XmlObject) {
sdt = new SDTContentControl((XmlObject)xmlcursor.getObject());
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
...
The SDTContentControl provides methods to get the content control title, the content control tag and the content control text content. It also provides a method to set the content control content from any kind of Object.
Complete example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import java.util.List;
import java.util.ArrayList;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import javax.xml.namespace.QName;
import java.util.GregorianCalendar;
import java.math.BigDecimal;
public class WordFillContentControls {
private static List<SDTContentControl> extractSDTsFromBody(XWPFDocument document) {
SDTContentControl sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<SDTContentControl> allsdts = new ArrayList<SDTContentControl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof XmlObject) {
sdt = new SDTContentControl((XmlObject)xmlcursor.getObject());
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
public static void main(String[] args) throws Exception {
String[] contentControlTags = new String[]{
"NameTag", "GenderTag", "DateTag", "AmountTag",
"DescriptionTag", "Col1Tag", "Col2Tag",
"Col1DateTag", "Col2ChooseTag"
};
Object[] contents = new Object[]{
"Axel Richter", "male", new GregorianCalendar(2022, 0, 1), BigDecimal.valueOf(1234.56),
"Lorem ipsum semit dolor ... dolor semit ...", "Blah blah", "Blubb blubb",
new GregorianCalendar(1964, 11, 21), "My choice"
};
XWPFDocument document = new XWPFDocument(new FileInputStream("./WordFormContentControl.docx"));
List<SDTContentControl> allsdts = extractSDTsFromBody(document);
for (SDTContentControl sdt : allsdts) {
//System.out.println(sdt);
String title = sdt.getTitle();
String tag = sdt.getTag();
String content = sdt.getContentText();
System.out.println(title + ": " + tag + ": " + content);
for (int i = 0; i < contentControlTags.length; i++) {
String tagToReplace = contentControlTags[i];
if (tagToReplace.equals(tag)) {
Object contentO = contents[i];
sdt.setContent(contentO);
}
}
}
allsdts = extractSDTsFromBody(document);
for (SDTContentControl sdt : allsdts) {
String title = sdt.getTitle();
String tag = sdt.getTag();
String content = sdt.getContentText();
System.out.println(title + ": " + tag + ": " + content);
}
FileOutputStream out = new FileOutputStream("./WordFormContentControlResult.docx");
document.write(out);
out.close();
document.close();
}
}

Using functions as map keys in Haxe

I want to use functions as keys in a Map like this:
var timers : Map<Void->Void, snow.api.Timer>;
But Haxe won't compile:
Abstract Map has no #:to function that accepts IMap<Void -> Void, snow.api.Timer>
Is there a way to do this ?
It's easy to write a custom implementation:
import haxe.Constraints;
class FunctionMap<K:Function,V> implements IMap<K,V> {
private var _keys : Array<K>;
private var _values : Array<V>;
public function new () {
_keys = [];
_values = [];
}
public function get(k:K):Null<V> {
var keyIndex = index(k);
if (keyIndex < 0) {
return null;
} else {
return _values[keyIndex];
}
}
public function set(k:K, v:V):Void {
var keyIndex = index(k);
if (keyIndex < 0) {
_keys.push(k);
_values.push(v);
} else {
_values[keyIndex] = v;
}
}
public function exists(k:K):Bool {
return index(k) >= 0;
}
public function remove(k:K):Bool {
var keyIndex = index(k);
if (keyIndex < 0) {
return false;
} else {
_keys.splice(keyIndex, 1);
_values.splice(keyIndex, 1);
return true;
}
}
public function keys():Iterator<K> {
return _keys.iterator();
}
public function iterator():Iterator<V> {
return _values
.iterator();
}
public function toString():String {
var s = new StringBuf();
s.add("{");
for( i in 0..._keys.length ) {
s.add('<function>');
s.add(" => ");
s.add(Std.string(_values[i]));
if( i < _keys.length - 1 )
s.add(", ");
}
s.add("}");
return s.toString();
}
private function index(key:K) : Int {
for (i in 0..._keys.length) {
if (Reflect.compareMethods(key, _keys[i])) {
return i;
}
}
return -1;
}}
http://try.haxe.org/#DdF31
I just tried this in try.haxe.org, and the compiler doesn't seem to like it, so I'm guessing the answer is "no."
You could get around this with some cleverness:
class Test {
static function main() {
var map:Map<VoidVoid,String>;
map = new Map<VoidVoid,String>();
var thing = {func:foo};
map.set(thing,"bar");
trace(map.get({func:foo})); //fails
trace(map.get(thing)); //succeeds;
}
static function foo():Void
{
}
}
typedef VoidVoid = {
var func:Void->Void;
}
But that's not an ideal solution because wrapping it in a typedef like that will make it fail if it's not the exact same instance, even if the value inside is the same.
I also tried making a Map<Dynamic,String> since you can stuff function references in those, but that didn't work either.
At this point I should ask, what problem are you trying to solve this way? Perhaps it could be better solved some other way.

Adobe security setting popup not showing remember option

Adobe security setting popups
I am using flash player for audio recording purpose. I want 1st popup but may program showing 2nd popup. How get I get first popup
My Action Script Code is given below.
package
{
import fr.kikko.lab.ShineMP3Encoder;
import flash.events.ErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.display.Sprite;
import flash.media.Microphone;
import flash.system.Security;
import org.bytearray.micrecorder.*;
import org.bytearray.micrecorder.events.RecordingEvent;
import org.bytearray.micrecorder.encoder.WaveEncoder;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.ActivityEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.display.LoaderInfo;
import flash.external.ExternalInterface;
import flash.media.Sound;
import org.as3wavsound.WavSound;
import org.as3wavsound.WavSoundChannel;
public class Main extends Sprite
{
// private var recBar:RecBar = new RecBar();
private var mic:Microphone;
private var waveEncoder:WaveEncoder = new WaveEncoder();
private var recorder:MicRecorder = new MicRecorder(waveEncoder);
private var maxTime:Number = 30; // default time to record in seconds
private var tts:WavSound;
private var playingChannel:WavSoundChannel;
private var mp3Encoder:ShineMP3Encoder;
private var mp3done:Boolean = false; // if we done converting to mp3
private var wasRecorded:Boolean = false; // if we done recording
private var isPreviewing:Boolean = false; // if we are in previewing state now?
private var isConverting:Boolean = false; // if we are in converting state now?
public function Main():void
{
mic = Microphone.getMicrophone();
mic.setSilenceLevel(mic.activityLevel);
mic.gain = 50;
mic.setLoopBack(false);
mic.setUseEchoSuppression(true);
recorder.addEventListener(RecordingEvent.RECORDING, recording);
addCommands();
}
public function jStartRecording(max_time:Number):void
{
if (mic != null) {
mp3done = false;
wasRecorded = false;
maxTime = max_time;
recorder.record();
// recorder.microphone.addEventListener(StatusEvent.STATUS, onMicStatus);
ExternalInterface.call("justrec.recordingStarted");
}
else
{
ExternalInterface.call("justrec.recordingError");
}
}
public function jStopRecording():void
{
recorder.stop();
wasRecorded = true;
mic.setLoopBack(false);
ExternalInterface.call("justrec.recordingStopped");
}
public function jPreview():void
{
if(wasRecorded) {
previewRecording();
}
}
public function jStopPreview():void
{
if(isPreviewing) {
stopPreviewRecording();
}
}
// convert WAV to MP3
public function jConvert2MP3():void
{
if(wasRecorded) {
convert2mp3();
}
}
public function jSendFileToServer():void
{
// do nothing if we have not converted our record
if(mp3done) {
sendRecording();
}
else {
ExternalInterface.call("justrec.mp3ConvertingError");
}
}
/* ************ */
/* Private area */
/* ************ */
private function recording(e:RecordingEvent):void
{
var currentTime:int = Math.floor(e.time / 1000);
ExternalInterface.call("justrec.recordingActivity", String(currentTime), mic.activityLevel);
if(currentTime >= maxTime )
{
// force stop recording
jStopRecording();
}
}
private function previewRecording():void
{
if(isConverting) {
return;
}
if(isPreviewing) {
stopPreviewRecording();
}
isPreviewing = true; // force into previewing mode
tts = new WavSound(recorder.output);
playingChannel = tts.play();
// ?? ExternalInterface.call("justrec.previewStarted");
}
private function stopPreviewRecording():void
{
playingChannel.stop();
isPreviewing = false;
// ?? ExternalInterface.call("justrec.previewStopped");
}
// convert to mp3 using ShineMP3Encoder
private function convert2mp3():void {
if(isConverting) {
return;
}
if(isPreviewing) {
stopPreviewRecording();
}
// set position of ByteArray with WAV data to 0
// either converting sticks if previewing is done
recorder.output.position = 0;
isConverting = true;
mp3Encoder = new ShineMP3Encoder(recorder.output);
mp3Encoder.addEventListener(Event.COMPLETE, mp3EncodeComplete);
mp3Encoder.addEventListener(ProgressEvent.PROGRESS, mp3EncodeProgress);
mp3Encoder.addEventListener(ErrorEvent.ERROR, mp3EncodeError);
mp3Encoder.start();
}
private function mp3EncodeProgress(event: ProgressEvent) : void {
var percent:int = Math.round(event.bytesLoaded / event.bytesTotal * 100);
ExternalInterface.call("justrec.mp3Converting", String(percent));
}
private function mp3EncodeError(event: ErrorEvent) : void {
isConverting = false;
ExternalInterface.call("justrec.mp3ConvertingError");
}
private function mp3EncodeComplete(event: Event) : void {
mp3done = true; // converting flag
isConverting = false;
ExternalInterface.call("justrec.mp3Converted");
}
// send data to server
private function sendRecording():void
{
var _var1:String = '';
var globalParam:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (var element:String in globalParam) {
if (element == 'host'){
_var1 = globalParam[element];
}
}
if(_var1 != '') {
var req:URLRequest = new URLRequest(_var1);
req.contentType = 'application/octet-stream';
req.method = URLRequestMethod.POST;
// req.data = recorder.output; -- for WAV data
req.data = mp3Encoder.mp3Data; // for MP3 data
var loader:URLLoader = new URLLoader(req);
loader.addEventListener(Event.COMPLETE, sendComplete);
loader.addEventListener(ProgressEvent.PROGRESS, sendProgress);
}
}
private function sendProgress(event: ProgressEvent) : void {
var percent:int = Math.round(event.bytesLoaded / event.bytesTotal * 100);
ExternalInterface.call("justrec.sendingProgress", String(percent));
}
// done sending record
private function sendComplete(event: Event) : void {
ExternalInterface.call("justrec.sendingFinished");
}
/* ***************** */
// helper functions //
/* *************** */
private function addCommands():void
{
ExternalInterface.addCallback("jStartRecording", jStartRecording);
ExternalInterface.addCallback("jStopRecording", jStopRecording);
ExternalInterface.addCallback("jPreview", jPreview);
ExternalInterface.addCallback("jStopPreview", jStopPreview);
ExternalInterface.addCallback("jConvert2MP3", jConvert2MP3);
ExternalInterface.addCallback("jSendFileToServer", jSendFileToServer);
}
// dispatches on allowing/denying access to Camera/Microphone
/*
private function onMicStatus(event:StatusEvent):void
{
ExternalInterface.call("justrec.micStatus");
if (event.code == "Microphone.Muted")
{
ExternalInterface.call("justrec.recordingError");
// trace("Microphone access was denied.");
}
}
*/
} // class Main
} // package

download XSD with all imports

I use gml (3.1.1) XSDs in XSD for my application. I want to download all gml XSDs in version 3.1.1 in for example zip file. In other words: base xsd is here and I want to download this XSD with all imports in zip file or something like zip file. Is there any application which supports that?
I've found this downloader but it doesn't works for me (I think that this application is not supporting relative paths in imports which occurs in gml.xsd 3.1.1). Any ideas?
QTAssistant's XSR (I am associated with it) has an easy to use function that allows one to automatically import and refactor XSD content as local files from all sorts of sources. In the process it'll update schema location references, etc.
I've made a simple screen capture of the steps involved in achieving a task like this which should demonstrate its usability.
Based on the solution of mschwehl, I made an improved class to achieve the fetch. It suited well with the question. See https://github.com/mfalaize/schema-fetcher
You can achieve this using SOAP UI.
Follow these steps :
Create a project using the WSDL.
Choose your interface and open in interface viewer.
Navigate to the tab 'WSDL Content'.
Use the last icon under the tab 'WSDL Content' : 'Export the entire WSDL and included/imported files to a local directory'.
select the folder where you want the XSDs to be exported to.
Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder.
I have written a simple java-main that does the job and change to relative url's
package dl;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class SchemaPersister {
private static final String EXPORT_FILESYSTEM_ROOT = "C:/export/xsd";
// some caching of the http-responses
private static Map<String,String> _httpContentCache = new HashMap<String,String>();
public static void main(String[] args) {
try {
new SchemaPersister().doIt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void doIt() throws Exception {
// // if you need an inouse-Proxy
// final String authUser = "xxxxx";
// final String authPassword = "xxxx"
//
// System.setProperty("http.proxyHost", "xxxxx");
// System.setProperty("http.proxyPort", "xxxx");
// System.setProperty("http.proxyUser", authUser);
// System.setProperty("http.proxyPassword", authPassword);
//
// Authenticator.setDefault(
// new Authenticator() {
// public PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(authUser, authPassword.toCharArray());
// }
// }
// );
//
Set <SchemaElement> allElements = new HashSet<SchemaElement>() ;
// URL url = new URL("file:/C:/xauslaender-nachrichten-administration.xsd");
URL url = new URL("http://www.osci.de/xauslaender141/xauslaender-nachrichten-bamf-abh.xsd");
allElements.add ( new SchemaElement(url));
for (SchemaElement e: allElements) {
System.out.println("processing " + e);
e.doAll();
}
System.out.println("done!");
}
class SchemaElement {
private URL _url;
private String _content;
public List <SchemaElement> _imports ;
public List <SchemaElement> _includes ;
public SchemaElement(URL url) {
this._url = url;
}
public void checkIncludesAndImportsRecursive() throws Exception {
InputStream in = new ByteArrayInputStream(downloadContent() .getBytes("UTF-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(in);
List<Node> includeNodeList = null;
List<Node> importNodeList = null;
includeNodeList = getXpathAttribute(doc,"/*[local-name()='schema']/*[local-name()='include']");
_includes = new ArrayList <SchemaElement> ();
for ( Node element: includeNodeList) {
Node sl = element.getAttributes().getNamedItem("schemaLocation");
if (sl == null) {
System.out.println(_url + " defines one import but no schemaLocation");
continue;
}
String asStringAttribute = sl.getNodeValue();
URL url = buildUrl(asStringAttribute,_url);
SchemaElement tmp = new SchemaElement(url);
tmp.setSchemaLocation(asStringAttribute);
tmp.checkIncludesAndImportsRecursive();
_includes.add(tmp);
}
importNodeList = getXpathAttribute(doc,"/*[local-name()='schema']/*[local-name()='import']");
_imports = new ArrayList <SchemaElement> ();
for ( Node element: importNodeList) {
Node sl = element.getAttributes().getNamedItem("schemaLocation");
if (sl == null) {
System.out.println(_url + " defines one import but no schemaLocation");
continue;
}
String asStringAttribute = sl.getNodeValue();
URL url = buildUrl(asStringAttribute,_url);
SchemaElement tmp = new SchemaElement(url);
tmp.setSchemaLocation(asStringAttribute);
tmp.checkIncludesAndImportsRecursive();
_imports.add(tmp);
}
in.close();
}
private String schemaLocation;
private void setSchemaLocation(String schemaLocation) {
this.schemaLocation = schemaLocation;
}
// http://stackoverflow.com/questions/10159186/how-to-get-parent-url-in-java
private URL buildUrl(String asStringAttribute, URL parent) throws Exception {
if (asStringAttribute.startsWith("http")) {
return new URL(asStringAttribute);
}
if (asStringAttribute.startsWith("file")) {
return new URL(asStringAttribute);
}
// relative URL
URI parentUri = parent.toURI().getPath().endsWith("/") ? parent.toURI().resolve("..") : parent.toURI().resolve(".");
return new URL(parentUri.toURL().toString() + asStringAttribute );
}
public void doAll() throws Exception {
System.out.println("READ ELEMENTS");
checkIncludesAndImportsRecursive();
System.out.println("PRINTING DEPENDENCYS");
printRecursive(0);
System.out.println("GENERATE OUTPUT");
patchAndPersistRecursive(0);
}
public void patchAndPersistRecursive(int level) throws Exception {
File f = new File(EXPORT_FILESYSTEM_ROOT + File.separator + this.getXDSName() );
System.out.println("FILENAME: " + f.getAbsolutePath());
if (_imports.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("IMPORTS");
for (SchemaElement kid : _imports) {
kid.patchAndPersistRecursive(level+1);
}
}
if (_includes.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("INCLUDES");
for (SchemaElement kid : _includes) {
kid.patchAndPersistRecursive(level+1);
}
}
String contentTemp = downloadContent();
for (SchemaElement i : _imports ) {
if (i.isHTTP()) {
contentTemp = contentTemp.replace(
"<xs:import schemaLocation=\"" + i.getSchemaLocation() ,
"<xs:import schemaLocation=\"" + i.getXDSName() );
}
}
for (SchemaElement i : _includes ) {
if (i.isHTTP()) {
contentTemp = contentTemp.replace(
"<xs:include schemaLocation=\"" + i.getSchemaLocation(),
"<xs:include schemaLocation=\"" + i.getXDSName() );
}
}
FileOutputStream fos = new FileOutputStream(f);
fos.write(contentTemp.getBytes("UTF-8"));
fos.close();
System.out.println("File written: " + f.getAbsolutePath() );
}
public void printRecursive(int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(_url.toString());
if (this._imports.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("IMPORTS");
for (SchemaElement kid : this._imports) {
kid.printRecursive(level+1);
}
}
if (this._includes.size() > 0) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("INCLUDES");
for (SchemaElement kid : this._includes) {
kid.printRecursive(level+1);
}
}
}
String getSchemaLocation() {
return schemaLocation;
}
/**
* removes html:// and replaces / with _
* #return
*/
private String getXDSName() {
String tmp = schemaLocation;
// Root on local File-System -- just grap the last part of it
if (tmp == null) {
tmp = _url.toString().replaceFirst(".*/([^/?]+).*", "$1");
}
if ( isHTTP() ) {
tmp = tmp.replace("http://", "");
tmp = tmp.replace("/", "_");
} else {
tmp = tmp.replace("/", "_");
tmp = tmp.replace("\\", "_");
}
return tmp;
}
private boolean isHTTP() {
return _url.getProtocol().startsWith("http");
}
private String downloadContent() throws Exception {
if (_content == null) {
System.out.println("reading content from " + _url.toString());
if (_httpContentCache.containsKey(_url.toString())) {
this._content = _httpContentCache.get(_url.toString());
System.out.println("Cache hit! " + _url.toString());
} else {
System.out.println("Download " + _url.toString());
Scanner scan = new Scanner(_url.openStream(), "UTF-8");
if (isHTTP()) {
this._content = scan.useDelimiter("\\A").next();
} else {
this._content = scan.useDelimiter("\\Z").next();
}
scan.close();
if (this._content != null) {
_httpContentCache.put(_url.toString(), this._content);
}
}
}
if (_content == null) {
throw new NullPointerException("Content of " + _url.toString() + "is null ");
}
return _content;
}
private List<Node> getXpathAttribute(Document doc, String path) throws Exception {
List <Node> returnList = new ArrayList <Node> ();
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
{
XPathExpression expr = xpath.compile(path);
NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET );
for (int i = 0 ; i < nodeList.getLength(); i++) {
Node n = nodeList.item(i);
returnList.add(n);
}
}
return returnList;
}
#Override
public String toString() {
if (_url != null) {
return _url.toString();
}
return super.toString();
}
}
}
I created a python tool to recursively download XSDs with relative paths in import tags (eg: <import schemaLocation="../../../../abc)
https://github.com/n-a-t-e/xsd_download
After downloading the schema you can use xmllint to validate an XML document
I am using org.apache.xmlbeans.impl.tool.SchemaResourceManager from the xmlbeans project. This class is quick and easy to use.
for example:
SchemaResourceManager manager = new SchemaResourceManager(new File(dir));
manager.process(schemaUris, emptyArray(), false, true, true);
manager.writeCache();
This class has a main method that documents the different options available.

table component not working in lwuit?

I want to display the table after selecting the values from comboBox. It working first time selection after that it adding another two more table in UI.
Can anyone say how to fix this?
Here the code:
package com.onmo.classes;
import java.io.IOException;
import com.sun.lwuit.Button;
import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TabbedPane;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.SelectionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.FlowLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.table.DefaultTableModel;
import com.sun.lwuit.table.Table;
import com.sun.lwuit.table.TableModel;
import com.sun.lwuit.util.Resources;
public class CompareScreen implements ActionListener, SelectionListener {
private Command enterCmd;
private Command backCmd;
private Command exitCmd;
private Form comparePage;
private Label lblLeagues, lblTeam;
private Button btnTeams, btnPlayers;
private FlowLayout flowLayout;
private ComboBox comboTeamA, comboTeamB, comboTeamC, comboTeamD, player1,
player2;
private Image firstTeamImage, secondTeamImage = null;
private Container teamsContainer, teamCombo, teamImages, playersTeamTab,
playersContainer, playersTab, playerImages;
int count = 0;
CompareScreen(){
enterCmd = new Command("Select");
backCmd = new Command("Back");
exitCmd = new Command("Exit");
}
public void displayCompareScreen() {
comparePage = new Form();
// comparePage.getStyle().setBgColor(0xaa00ff);
String[] teamA = { "Team A", "Villarreal", "Violent Vegans",
"Venom XI", "Betis" };
String[] teamB = { "Team B", "Villarreal", "Violent Vegans",
"Venom XI", "Betis" };
String[] playerList1 = { "Player1", "Acho, Sam", "Adams, Mike",
"Ajirotutu, Seyi", "Abel Gomez" };
String[] playerList2 = { "Player2", "Acho, Sam", "Adams, Mike",
"Ajirotutu, Seyi", "Abel Gomez" };
comparePage.addCommand(backCmd);
comparePage.addCommandListener(this);
lblLeagues = new Label("Premier League");
lblTeam = new Label("Team");
btnTeams = new Button("Teams");
btnPlayers = new Button("Players");
comboTeamA = new ComboBox(teamA);
comboTeamB = new ComboBox(teamB);
comboTeamC = new ComboBox(teamA);
comboTeamD = new ComboBox(teamB);
player1 = new ComboBox(playerList1);
player2 = new ComboBox(playerList2);
comparePage.setLayout(new BorderLayout());
comparePage
.addComponent(BorderLayout.WEST, new Label("Premier League"));
comparePage.addComponent(BorderLayout.EAST, new Label("Compare"));
flowLayout = new FlowLayout();
comparePage.setLayout(flowLayout);
try {
Resources r = Resources.open("/theme/javathema.res");
UIManager.getInstance().setThemeProps(r.getTheme("javathema"));
} catch (IOException ioe) {
System.out.println("Couldn't load theme.");
}
try {
firstTeamImage = Image.createImage("/team1.png");
secondTeamImage = Image.createImage("/team2.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Label lblFirstTeam = new Label(firstTeamImage);
lblFirstTeam.setAlignment(Component.LEFT);
Label lblSecondTeam = new Label(secondTeamImage);
lblSecondTeam.setAlignment(Component.RIGHT);
Label lblFirstPlayer = new Label(firstTeamImage);
lblFirstTeam.setAlignment(Component.LEFT);
Label lblSecondPlayer = new Label(secondTeamImage);
lblSecondTeam.setAlignment(Component.RIGHT);
teamsContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
teamCombo = new Container(new BoxLayout(BoxLayout.X_AXIS));
teamCombo.addComponent(comboTeamA);
teamCombo.addComponent(comboTeamB);
teamImages = new Container(new BoxLayout(BoxLayout.X_AXIS));
teamImages.addComponent(lblFirstTeam);
teamImages.addComponent(lblSecondTeam);
teamsContainer.addComponent(teamCombo);
teamsContainer.addComponent(teamImages);
playersTeamTab = new Container(new BoxLayout(BoxLayout.X_AXIS));
playersTeamTab.addComponent(comboTeamC);
playersTeamTab.addComponent(comboTeamD);
playersTab = new Container(new BoxLayout(BoxLayout.X_AXIS));
playersTab.addComponent(player1);
playersTab.addComponent(player2);
playerImages = new Container(new BoxLayout(BoxLayout.X_AXIS));
playerImages.addComponent(lblFirstPlayer);
playerImages.addComponent(lblSecondPlayer);
playersContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
playersContainer.addComponent(playersTeamTab);
playersContainer.addComponent(playersTab);
playersContainer.addComponent(playerImages);
TabbedPane tabbedPane = new TabbedPane(TabbedPane.TOP);
tabbedPane.addTab("Teams", teamsContainer);
tabbedPane.addTab("Players", playersContainer);
// comboTeamA.addSelectionListener(this);
comboTeamB.addSelectionListener(this);
// comboTeamC.addSelectionListener(this);
comboTeamD.addSelectionListener(this);
// comboTeamA.addActionListener(this);
comparePage.addComponent(tabbedPane);
comparePage.show();
}
public void selectionChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
System.out.println("Before :" + count);
Table tableTeam = null, tablePlayer = null;
if (comboTeamA.getSelectedIndex() != 0 && comboTeamB.getSelectedIndex() != 0 && comboTeamC.getSelectedIndex() == 0 && comboTeamD.getSelectedIndex() == 0) {
TableModel model = new DefaultTableModel(new String[] { "10 ",
"Games Played", "10" }, new Object[][] {
{ "7 ", "Wins", " 6" }, { "2 ", "Draws", " 1" },
{ "1 ", "Defeats", " 1" }, { "10 ", "Goals for", " 8" }, });
tableTeam = new Table(model);
if (count == 1) {
teamsContainer.addComponent(tableTeam);
count = 0;
}
count = count + 1;
System.out.println("On :" + count);
}
if (comboTeamA.getSelectedIndex() == 0 && comboTeamB.getSelectedIndex() == 0 && comboTeamC.getSelectedIndex() != 0 && comboTeamD.getSelectedIndex() != 0) {
TableModel model = new DefaultTableModel(new String[] { "10 ",
"Games Played", "10" }, new Object[][] {
{ "260 ", "Minutes Played", " 280" },
{ "240 ", "Starts", " 230" },
{ "20 ", "Substitute", " 30" },
{ "6 ", "Goals for", " 9" }, });
tablePlayer = new Table(model);
if (count == 1) {
playersContainer.addComponent(tablePlayer);
count = 0;
}
count = count + 1;
System.out.println("On :" + count);
}
/*
* if(tableTeam != null && tablePlayer != null) {
* teamsContainer.removeComponent(tableTeam);
* playersContainer.removeComponent(tablePlayer); }
*/
System.out.println("After :" + count);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
HomePage homePageObj=HomePage.getInstance();
homePageObj.displayHomePage();
}
}
The problem is at this code:
public void selectionChanged(int arg0, int arg1) {
...
tableTeam = new Table(model);
if (count == 1) {
teamsContainer.addComponent(tableTeam);
count = 0;
}
count = count + 1;
...
}
This code snippet means that you add another Table each time you select another value from the ComboBox : DON'T RESET "count" TO 0 !

Resources