repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/AllFieldsAreRequired.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/AllFieldsAreRequired.java
package me.grishka.examples.pokedex.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AllFieldsAreRequired{ }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/PokeAPIRequest.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/PokeAPIRequest.java
package me.grishka.examples.pokedex.api; import android.util.Log; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.util.List; import androidx.annotation.CallSuper; import me.grishka.appkit.api.APIRequest; import me.grishka.appkit.api.ErrorResponse; import me.grishka.examples.pokedex.BuildConfig; import me.grishka.examples.pokedex.model.BaseModel; import okhttp3.Call; import okhttp3.Response; public class PokeAPIRequest<T> extends APIRequest<T>{ private static final String TAG="PokeAPIRequest"; public String url; boolean canceled; Call okhttpCall; Class<T> respClass; TypeToken<T> respTypeToken; public PokeAPIRequest(Class<T> respClass){ this.respClass=respClass; } public PokeAPIRequest(TypeToken<T> respTypeToken){ this.respTypeToken=respTypeToken; } @Override public synchronized void cancel(){ if(BuildConfig.DEBUG) Log.d(TAG, "canceling request "+this); canceled=true; if(okhttpCall!=null){ okhttpCall.cancel(); } } @Override public APIRequest<T> exec(){ PokeAPIController.getInstance().submitRequest(this); return this; } @CallSuper public void validateAndPostprocessResponse(T respObj, Response httpResponse) throws IOException{ if(respObj instanceof BaseModel bm){ bm.postprocess(); }else if(respObj instanceof List<?> list){ for(Object item:list){ if(item instanceof BaseModel bm) bm.postprocess(); } } } void onError(ErrorResponse err){ if(!canceled) invokeErrorCallback(err); } void onError(String msg, int httpStatus, Throwable exception){ if(!canceled) invokeErrorCallback(new PokeAPIErrorResponse(msg, httpStatus, exception)); } void onSuccess(T resp){ if(!canceled) invokeSuccessCallback(resp); } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/ObjectValidationException.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/ObjectValidationException.java
package me.grishka.examples.pokedex.api; import java.io.IOException; public class ObjectValidationException extends IOException{ public ObjectValidationException(){ } public ObjectValidationException(String message){ super(message); } public ObjectValidationException(String message, Throwable cause){ super(message, cause); } public ObjectValidationException(Throwable cause){ super(cause); } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/PokeAPIErrorResponse.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/PokeAPIErrorResponse.java
package me.grishka.examples.pokedex.api; import android.content.Context; import android.view.View; import android.widget.TextView; import android.widget.Toast; import me.grishka.appkit.api.ErrorResponse; public class PokeAPIErrorResponse extends ErrorResponse{ public final String error; public final int httpStatus; public final Throwable underlyingException; public PokeAPIErrorResponse(String error, int httpStatus, Throwable underlyingException){ this.error=error; this.httpStatus=httpStatus; this.underlyingException=underlyingException; } @Override public void bindErrorView(View view){ TextView text=view.findViewById(me.grishka.appkit.R.id.error_text); text.setText(error); } @Override public void showToast(Context context){ if(context==null) return; Toast.makeText(context, error, Toast.LENGTH_SHORT).show(); } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/requests/GetPokemonList.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/requests/GetPokemonList.java
package me.grishka.examples.pokedex.api.requests; import android.net.Uri; import com.google.gson.reflect.TypeToken; import me.grishka.examples.pokedex.api.PokeAPIRequest; import me.grishka.examples.pokedex.model.ListPokemon; import me.grishka.examples.pokedex.model.PaginatedList; public class GetPokemonList extends PokeAPIRequest<PaginatedList<ListPokemon>>{ public GetPokemonList(int offset, int count){ super(new TypeToken<>(){}); url=new Uri.Builder() .scheme("https") .authority("pokeapi.co") .path("/api/v2/pokemon") .appendQueryParameter("offset", String.valueOf(offset)) .appendQueryParameter("limit", String.valueOf(count)) .build() .toString(); } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/requests/GetPokemonDetails.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/requests/GetPokemonDetails.java
package me.grishka.examples.pokedex.api.requests; import me.grishka.examples.pokedex.api.PokeAPIRequest; import me.grishka.examples.pokedex.model.PokemonDetailsResponse; public class GetPokemonDetails extends PokeAPIRequest<PokemonDetailsResponse>{ public GetPokemonDetails(String url){ super(PokemonDetailsResponse.class); this.url=url; } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/caching/DatabaseRunnable.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/caching/DatabaseRunnable.java
package me.grishka.examples.pokedex.api.caching; import android.database.sqlite.SQLiteDatabase; import java.io.IOException; @FunctionalInterface public interface DatabaseRunnable{ void run(SQLiteDatabase db) throws IOException; }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/api/caching/PokemonCache.java
PokeDex/src/main/java/me/grishka/examples/pokedex/api/caching/PokemonCache.java
package me.grishka.examples.pokedex.api.caching; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.os.Handler; import android.os.Looper; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.function.Consumer; import me.grishka.appkit.api.Callback; import me.grishka.appkit.api.ErrorResponse; import me.grishka.appkit.utils.WorkerThread; import me.grishka.examples.pokedex.BuildConfig; import me.grishka.examples.pokedex.PokeDexApplication; import me.grishka.examples.pokedex.api.PokeAPIErrorResponse; import me.grishka.examples.pokedex.api.requests.GetPokemonDetails; import me.grishka.examples.pokedex.api.requests.GetPokemonList; import me.grishka.examples.pokedex.model.ListPokemon; import me.grishka.examples.pokedex.model.PaginatedList; import me.grishka.examples.pokedex.model.PokemonDetails; import me.grishka.examples.pokedex.model.PokemonDetailsResponse; public class PokemonCache{ private static final String TAG="PokemonCache"; private static final int SCHEMA_VERSION=1; private static final WorkerThread databaseThread=new WorkerThread("databaseThread"); private static final Handler uiHandler=new Handler(Looper.getMainLooper()); private static final PokemonCache INSTANCE=new PokemonCache(); private DatabaseHelper db; private final Runnable databaseCloseRunnable=this::closeDatabase; static{ databaseThread.start(); } private PokemonCache(){ //no instance } public static PokemonCache getInstance(){ return INSTANCE; } public void getList(int offset, int count, boolean clearCache, Callback<PaginatedList<ListPokemon>> callback){ runOnDbThread(db->{ if(clearCache){ db.delete("pokemon_list", null, null); db.delete("pokemon_details", null, null); } try(Cursor cursor=db.query("pokemon_list", null, null, null, null, null, "id ASC", offset+","+count)){ if(cursor.moveToFirst()){ ArrayList<ListPokemon> list=new ArrayList<>(); do{ list.add(new ListPokemon(cursor)); }while(cursor.moveToNext()); PaginatedList<ListPokemon> res=new PaginatedList<>(); res.next="fake next url whatever absolute urls in api responses are stupid"; res.results=list; uiHandler.post(()->callback.onSuccess(res)); return; } } new GetPokemonList(offset, count) .setCallback(new Callback<>(){ @Override public void onSuccess(PaginatedList<ListPokemon> resp){ callback.onSuccess(resp); runOnDbThread(db->{ ContentValues values=new ContentValues(); for(ListPokemon lp:resp.results){ lp.toContentValues(values); db.insertWithOnConflict("pokemon_list", null, values, SQLiteDatabase.CONFLICT_REPLACE); } }); } @Override public void onError(ErrorResponse err){ callback.onError(err); } }) .exec(); }, x->uiHandler.post(()->callback.onError(new PokeAPIErrorResponse(x.getMessage(), -1, x)))); } public void getDetails(ListPokemon pokemon, Callback<PokemonDetails> callback){ runOnDbThread(db->{ try(Cursor cursor=db.query("pokemon_details", null, "id=?", new String[]{String.valueOf(pokemon.index)}, null, null, null)){ if(cursor.moveToFirst()){ PokemonDetails res=new PokemonDetails(cursor); uiHandler.post(()->callback.onSuccess(res)); return; } } new GetPokemonDetails(pokemon.url) .setCallback(new Callback<>(){ @Override public void onSuccess(PokemonDetailsResponse resp){ PokemonDetails pd=new PokemonDetails(resp); callback.onSuccess(pd); runOnDbThread(db->{ ContentValues values=new ContentValues(); pd.toContentValues(values); db.insertWithOnConflict("pokemon_details", null, values, SQLiteDatabase.CONFLICT_REPLACE); }); } @Override public void onError(ErrorResponse err){ callback.onError(err); } }) .exec(); }, x->uiHandler.post(()->callback.onError(new PokeAPIErrorResponse(x.getMessage(), -1, x)))); } private void closeDelayed(){ databaseThread.postRunnable(databaseCloseRunnable, 10_000); } public void closeDatabase(){ if(db!=null){ if(BuildConfig.DEBUG) Log.d(TAG, "closeDatabase"); db.close(); db=null; } } private void cancelDelayedClose(){ if(db!=null){ databaseThread.handler.removeCallbacks(databaseCloseRunnable); } } private SQLiteDatabase getOrOpenDatabase(){ if(db==null) db=new DatabaseHelper(); return db.getWritableDatabase(); } private void runOnDbThread(DatabaseRunnable r){ runOnDbThread(r, null); } private void runOnDbThread(DatabaseRunnable r, Consumer<Exception> onError){ cancelDelayedClose(); databaseThread.postRunnable(()->{ try{ SQLiteDatabase db=getOrOpenDatabase(); r.run(db); }catch(SQLiteException|IOException x){ Log.w(TAG, x); if(onError!=null) onError.accept(x); }finally{ closeDelayed(); } }, 0); } private static class DatabaseHelper extends SQLiteOpenHelper{ public DatabaseHelper(){ super(PokeDexApplication.context, "cache.db", null, SCHEMA_VERSION); } @Override public void onCreate(SQLiteDatabase db){ db.execSQL(""" CREATE TABLE `pokemon_list` ( `id` integer PRIMARY KEY, `name` text NOT NULL, `url` text NOT NULL )"""); db.execSQL(""" CREATE TABLE `pokemon_details` ( `id` integer PRIMARY KEY, `weight` integer NOT NULL, `height` integer NOT NULL, `types` integer NOT NULL, `health` integer NOT NULL, `attack` integer NOT NULL, `defense` integer NOT NULL, `special_attack` integer NOT NULL, `special_defense` integer NOT NULL, `speed` integer NOT NULL )"""); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ } } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/views/AnimatedLabeledProgressBar.java
PokeDex/src/main/java/me/grishka/examples/pokedex/views/AnimatedLabeledProgressBar.java
package me.grishka.examples.pokedex.views; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Property; import android.view.View; import java.util.Locale; import androidx.annotation.NonNull; import me.grishka.appkit.utils.CubicBezierInterpolator; import me.grishka.appkit.utils.CustomViewHelper; import me.grishka.examples.pokedex.R; public class AnimatedLabeledProgressBar extends View implements CustomViewHelper{ private static final Property<AnimatedLabeledProgressBar, Float> FRACTION_PROP=new Property<>(Float.class, "dsfsafsdafds"){ @Override public Float get(AnimatedLabeledProgressBar object){ return object.fraction; } @Override public void set(AnimatedLabeledProgressBar object, Float value){ object.fraction=value; object.invalidate(); } }; private int progress, maxValue; private int fgColor, bgColor, textInnerColor, textOuterColor; private float fraction; private RectF tmpRect=new RectF(); private Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG); private Animator currentAnim; public AnimatedLabeledProgressBar(Context context){ this(context, null); } public AnimatedLabeledProgressBar(Context context, AttributeSet attrs){ this(context, attrs, 0); } public AnimatedLabeledProgressBar(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); TypedArray ta=context.obtainStyledAttributes(attrs, R.styleable.AnimatedLabeledProgressBar, defStyle, 0); maxValue=ta.getInt(R.styleable.AnimatedLabeledProgressBar_android_max, 100); progress=ta.getInt(R.styleable.AnimatedLabeledProgressBar_android_progress, 0); fgColor=ta.getColor(R.styleable.AnimatedLabeledProgressBar_android_color, 0xff00ff00); bgColor=ta.getColor(R.styleable.AnimatedLabeledProgressBar_android_colorBackground, 0xffffffff); textInnerColor=ta.getColor(R.styleable.AnimatedLabeledProgressBar_android_numbersInnerTextColor, 0xffffffff); textOuterColor=ta.getColor(R.styleable.AnimatedLabeledProgressBar_android_numbersTextColor, 0xff000000); ta.recycle(); paint.setTextSize(dp(11)); } public void setProgress(int progress){ this.progress=progress; if(currentAnim!=null) currentAnim.cancel(); ObjectAnimator anim=ObjectAnimator.ofFloat(this, FRACTION_PROP, progress/(float)maxValue); anim.setDuration(400); anim.setInterpolator(CubicBezierInterpolator.DEFAULT); anim.addListener(new AnimatorListenerAdapter(){ @Override public void onAnimationEnd(Animator animation){ currentAnim=null; } }); currentAnim=anim; anim.start(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), dp(18)); } @Override protected void onDraw(@NonNull Canvas canvas){ tmpRect.set(0, 0, getWidth(), getHeight()); paint.setColor(bgColor); float radius=getHeight()/2f; canvas.drawRoundRect(tmpRect, radius, radius, paint); tmpRect.right=getWidth()*fraction; paint.setColor(fgColor); canvas.drawRoundRect(tmpRect, radius, radius, paint); String text=String.format(Locale.getDefault(), "%d/%d", Math.round(maxValue*fraction), maxValue); float textWidth=paint.measureText(text); float textGap=dp(4); float textX; if(tmpRect.width()<textWidth+textGap*2){ textX=tmpRect.right+textGap; paint.setColor(textOuterColor); }else{ textX=tmpRect.right-textWidth-textGap; paint.setColor(textInnerColor); } canvas.drawText(text, textX, getHeight()/2f-(paint.descent()-paint.ascent())/2f-paint.ascent(), paint); } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/fragments/PokemonListFragment.java
PokeDex/src/main/java/me/grishka/examples/pokedex/fragments/PokemonListFragment.java
package me.grishka.examples.pokedex.fragments; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.widget.ImageView; import android.widget.TextView; import org.parceler.Parcels; import androidx.annotation.AttrRes; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import me.grishka.appkit.Nav; import me.grishka.appkit.api.SimpleCallback; import me.grishka.appkit.fragments.BaseRecyclerFragment; import me.grishka.appkit.imageloader.ImageLoaderRecyclerAdapter; import me.grishka.appkit.imageloader.ImageLoaderViewHolder; import me.grishka.appkit.imageloader.requests.ImageLoaderRequest; import me.grishka.appkit.utils.BindableViewHolder; import me.grishka.appkit.utils.V; import me.grishka.appkit.views.UsableRecyclerView; import me.grishka.examples.pokedex.R; import me.grishka.examples.pokedex.api.caching.PokemonCache; import me.grishka.examples.pokedex.model.ListPokemon; import me.grishka.examples.pokedex.model.PaginatedList; import me.grishka.examples.pokedex.util.BitmapDrawableWithPalette; public class PokemonListFragment extends BaseRecyclerFragment<ListPokemon>{ private GridLayoutManager layoutManager; private boolean isDarkTheme; public PokemonListFragment(){ super(25); } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setRetainInstance(true); setTitle(R.string.app_name); loadData(); } @Override protected void doLoadData(int offset, int count){ PokemonCache.getInstance().getList(offset, count, refreshing, new SimpleCallback<>(this){ @Override public void onSuccess(PaginatedList<ListPokemon> result){ onDataLoaded(result.results, result.next!=null); } }); } @Override protected RecyclerView.Adapter<?> getAdapter(){ return new PokemonAdapter(); } @Override protected RecyclerView.LayoutManager onCreateLayoutManager(){ return layoutManager=new GridLayoutManager(getActivity(), 2); } @Override public void onViewCreated(View view, Bundle savedInstanceState){ super.onViewCreated(view, savedInstanceState); isDarkTheme=(getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK)==Configuration.UI_MODE_NIGHT_YES; UsableRecyclerView urv=(UsableRecyclerView)list; urv.setSelector(getResources().getDrawable(R.drawable.card_selector, getActivity().getTheme())); urv.setDrawSelectorOnTop(true); list.addItemDecoration(new RecyclerView.ItemDecoration(){ private final int padSmall=V.dp(6); private final int padLarge=V.dp(16); @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state){ int index=parent.getChildViewHolder(view).getLayoutPosition(); int spanCount=layoutManager.getSpanCount(); int column=index%spanCount; outRect.set(column==0 ? padLarge : padSmall, index<spanCount ? padLarge : padSmall, column==spanCount-1 ? padLarge : padSmall, padSmall); } }); } @Override public boolean wantsLightNavigationBar(){ return !isDarkTheme; } @Override public void onApplyWindowInsets(WindowInsets insets){ if(Build.VERSION.SDK_INT>=29 && insets.getTappableElementInsets().bottom==0){ list.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom()); insets=insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), 0); } super.onApplyWindowInsets(insets); } private int getThemeColor(@AttrRes int attr){ TypedArray ta=getActivity().obtainStyledAttributes(new int[]{attr}); int color=ta.getColor(0, 0xff00ff00); ta.recycle(); return color; } private class PokemonAdapter extends UsableRecyclerView.Adapter<PokemonViewHolder> implements ImageLoaderRecyclerAdapter{ public PokemonAdapter(){ super(imgLoader); } @NonNull @Override public PokemonViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i){ return new PokemonViewHolder(); } @Override public int getItemCount(){ return data.size(); } @Override public void onBindViewHolder(PokemonViewHolder holder, int position){ holder.bind(data.get(position)); super.onBindViewHolder(holder, position); } @Override public int getImageCountForItem(int pos){ return 1; } @Override public ImageLoaderRequest getImageRequest(int pos, int image){ return data.get(pos).imgRequest; } } private class PokemonViewHolder extends BindableViewHolder<ListPokemon> implements ImageLoaderViewHolder, UsableRecyclerView.Clickable{ private final TextView name; private final ImageView image; public PokemonViewHolder(){ super(getActivity(), R.layout.item_pokemon, list); name=findViewById(R.id.name); image=findViewById(R.id.image); } @Override public void onBind(ListPokemon listPokemon){ name.setText(listPokemon.name); } @Override public void setImage(int index, Drawable drawable){ image.setImageDrawable(drawable); if(drawable instanceof BitmapDrawableWithPalette dwp){ itemView.setBackgroundTintList(ColorStateList.valueOf(dwp.getCardBackgroundColor(isDarkTheme))); name.setTextColor(dwp.getCardTextColor(isDarkTheme)); }else{ itemView.setBackgroundTintList(null); name.setTextColor(getThemeColor(android.R.attr.textColorPrimary)); } } @Override public void onClick(){ Bundle args=new Bundle(); args.putParcelable("pokemon", Parcels.wrap(item)); Nav.go(getActivity(), PokemonDetailsFragment.class, args); } } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
grishka/poke.dex
https://github.com/grishka/poke.dex/blob/229c925988509b06b824079f8202c0a5001116f7/PokeDex/src/main/java/me/grishka/examples/pokedex/fragments/PokemonDetailsFragment.java
PokeDex/src/main/java/me/grishka/examples/pokedex/fragments/PokemonDetailsFragment.java
package me.grishka.examples.pokedex.fragments; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.app.Activity; import android.content.res.ColorStateList; import android.graphics.Outline; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.transition.Fade; import android.transition.TransitionManager; import android.transition.TransitionSet; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewOutlineProvider; import android.view.ViewTreeObserver; import android.view.WindowInsets; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toolbar; import org.parceler.Parcels; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import me.grishka.appkit.api.Callback; import me.grishka.appkit.api.ErrorResponse; import me.grishka.appkit.fragments.AppKitFragment; import me.grishka.appkit.fragments.CustomTransitionsFragment; import me.grishka.appkit.imageloader.ViewImageLoader; import me.grishka.appkit.utils.BindableViewHolder; import me.grishka.appkit.utils.CubicBezierInterpolator; import me.grishka.appkit.utils.V; import me.grishka.examples.pokedex.R; import me.grishka.examples.pokedex.api.caching.PokemonCache; import me.grishka.examples.pokedex.model.ListPokemon; import me.grishka.examples.pokedex.model.PokemonDetails; import me.grishka.examples.pokedex.model.PokemonType; import me.grishka.examples.pokedex.util.BitmapDrawableWithPalette; import me.grishka.examples.pokedex.views.AnimatedLabeledProgressBar; public class PokemonDetailsFragment extends AppKitFragment implements CustomTransitionsFragment{ private int lastTopInset; private View view; private FrameLayout imageWrap; private ImageView image; private TextView name; private ProgressBar progress; private LinearLayout typesContainer; private View sizeStats; private TextView weight, height; private View stats; private AnimatedLabeledProgressBar hpBar, attackBar, defenseBar, specialAttachBar, specialDefenseBar, speedBar; private ScrollView scroller; private View scrollableContent; private Animator currentTransition; private int headerRadius; private ListPokemon pokemon; private PokemonDetails details; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); pokemon=Parcels.unwrap(getArguments().getParcelable("pokemon")); try{pokemon.postprocess();}catch(IOException ignore){} setTitle(pokemon.name); loadDetails(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState){ view=inflater.inflate(R.layout.fragment_details, container, false); imageWrap=view.findViewById(R.id.image_wrap); image=view.findViewById(R.id.image); name=view.findViewById(R.id.name); progress=view.findViewById(R.id.progress); typesContainer=view.findViewById(R.id.types); weight=view.findViewById(R.id.weight); height=view.findViewById(R.id.height); sizeStats=view.findViewById(R.id.size_stats); stats=view.findViewById(R.id.stats); hpBar=view.findViewById(R.id.hp_bar); attackBar=view.findViewById(R.id.attack_bar); defenseBar=view.findViewById(R.id.defense_bar); specialAttachBar=view.findViewById(R.id.special_attack_bar); specialDefenseBar=view.findViewById(R.id.special_defense_bar); speedBar=view.findViewById(R.id.speed_bar); scroller=view.findViewById(R.id.scroller); scrollableContent=view.findViewById(R.id.scrollable_content); headerRadius=V.dp(64); imageWrap.setBackgroundColor(0xff000000); imageWrap.setOutlineProvider(new ViewOutlineProvider(){ @Override public void getOutline(View view, Outline outline){ outline.setRoundRect(0, -headerRadius, view.getWidth(), view.getHeight(), headerRadius); } }); imageWrap.setClipToOutline(true); ViewImageLoader.load(new ViewImageLoader.Target(){ @Override public void setImageDrawable(Drawable drawable){ image.setImageDrawable(drawable); if(drawable instanceof BitmapDrawableWithPalette bwp){ imageWrap.setBackground(new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, bwp.getGradientColors())); } } @Override public View getView(){ return image; } }, null, pokemon.imgRequest, false); name.setText(pokemon.name); scroller.getViewTreeObserver().addOnScrollChangedListener(()->{ Toolbar toolbar=getToolbar(); if(toolbar==null) return; int scrollY=scroller.getScrollY(); int defaultRadius=V.dp(64); int headerHeight=imageWrap.getHeight(); int topBarsHeight=toolbar.getHeight()+lastTopInset; int newRadius; if(headerHeight-scrollY-topBarsHeight<defaultRadius){ newRadius=Math.max(0, headerHeight-scrollY-topBarsHeight); imageWrap.setTranslationY(Math.max(0, scrollY-headerHeight+topBarsHeight)); }else{ newRadius=defaultRadius; imageWrap.setTranslationY(0); } if(currentTransition==null) image.setAlpha(1f-Math.max(0, Math.min(1, scrollY/(float)(headerHeight-topBarsHeight)))); if(newRadius!=headerRadius){ headerRadius=newRadius; imageWrap.invalidateOutline(); } }); return view; } @Override protected void onUpdateToolbar(){ super.onUpdateToolbar(); Toolbar toolbar=getToolbar(); toolbar.setBackground(null); ((ViewGroup.MarginLayoutParams)toolbar.getLayoutParams()).topMargin=lastTopInset; TextView index=(TextView) LayoutInflater.from(toolbar.getContext()).inflate(R.layout.pokemon_index_view, null); toolbar.addView(index, new Toolbar.LayoutParams(Gravity.END)); index.setText(String.format("#%03d", pokemon.index)); } @Override public void onApplyWindowInsets(WindowInsets insets){ int topInset=insets.getSystemWindowInsetTop(); ((ViewGroup.MarginLayoutParams)getToolbar().getLayoutParams()).topMargin=topInset; int pad=V.dp(16); imageWrap.setPadding(pad, pad+topInset+getToolbar().getLayoutParams().height, pad, pad); imageWrap.getLayoutParams().height=V.dp(250)+topInset; lastTopInset=topInset; insets=insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()); if(Build.VERSION.SDK_INT>=29 && insets.getTappableElementInsets().bottom==0){ scrollableContent.setPadding(0, 0, 0, insets.getSystemWindowInsetBottom()); insets=insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), 0); } super.onApplyWindowInsets(insets); } @Override public Animator onCreateEnterTransition(View prev, View container){ return createFragmentTransition(prev, container, true); } @Override public Animator onCreateExitTransition(View prev, View container){ return createFragmentTransition(prev, container, false); } private void showDetails(){ if(getActivity()==null) return; TransitionManager.beginDelayedTransition((ViewGroup) view, new TransitionSet() .addTransition(new Fade(Fade.IN | Fade.OUT)) .setDuration(250) .setInterpolator(CubicBezierInterpolator.DEFAULT) ); progress.setVisibility(View.GONE); typesContainer.setVisibility(View.VISIBLE); sizeStats.setVisibility(View.VISIBLE); stats.setVisibility(View.VISIBLE); NumberFormat format=NumberFormat.getInstance(); format.setMaximumFractionDigits(1); weight.setText(getString(R.string.weight_kg, format.format(details.weight/10.0))); height.setText(getString(R.string.height_m, format.format(details.height/10.0))); hpBar.setProgress(details.health); attackBar.setProgress(details.attack); defenseBar.setProgress(details.defense); specialAttachBar.setProgress(details.specialAttack); specialDefenseBar.setProgress(details.specialDefense); speedBar.setProgress(details.speed); for(PokemonType type:details.types){ TextView typeChip=new TextView(getActivity()); typeChip.setTextSize(13); typeChip.setTextColor(0xffffffff); typeChip.setShadowLayer(V.dp(1.5f), 0, V.dp(1), 0x80000000); typeChip.setText(type.toString()); // it's a capitalized English name anyway typeChip.setSingleLine(); typeChip.setBackgroundResource(R.drawable.bg_type_chip); typeChip.setBackgroundTintList(ColorStateList.valueOf(switch(type){ case NORMAL -> 0xffaaaa99; case FIRE -> 0xffff4422; case WATER -> 0xff3399ff; case ELECTRIC -> 0xffffcc33; case GRASS -> 0xff77cc55; case ICE -> 0xff66ccff; case FIGHTING -> 0xffbb5544; case POISON -> 0xffaa5599; case GROUND -> 0xffddbb55; case FLYING -> 0xff8899ff; case PSYCHIC -> 0xffff5599; case BUG -> 0xffaabb22; case ROCK -> 0xffbbaa66; case GHOST -> 0xff6666bb; case DRAGON -> 0xff7766ee; case DARK -> 0xff775544; case STEEL -> 0xffaaaabb; case FAIRY -> 0xffee99ee; })); typesContainer.addView(typeChip); } } private void loadDetails(){ PokemonCache.getInstance().getDetails(pokemon, new Callback<>(){ @Override public void onSuccess(PokemonDetails resp){ details=resp; showDetails(); } @Override public void onError(ErrorResponse err){ Activity activity=getActivity(); if(activity!=null) err.showToast(activity); } }); } private Animator createFragmentTransition(View prev, View container, boolean in){ if(currentTransition!=null) currentTransition.cancel(); ArrayList<Animator> anims=new ArrayList<>(); anims.add(ObjectAnimator.ofFloat(container, View.ALPHA, in ? 0f : 1f, in ? 1f : 0f)); RecyclerView parentList=prev.findViewById(me.grishka.appkit.R.id.list); RecyclerView.ViewHolder srcHolder=null; if(parentList!=null){ for(int i=0;i<parentList.getChildCount();i++){ RecyclerView.ViewHolder holder=parentList.getChildViewHolder(parentList.getChildAt(i)); if(holder instanceof BindableViewHolder<?> bvh && bvh.getItem() instanceof ListPokemon lp){ if(lp.index==pokemon.index){ srcHolder=holder; break; } } } } AnimatorSet set=new AnimatorSet(); if(srcHolder!=null){ FrameLayout parent=(FrameLayout) getActivity().getWindow().getDecorView(); View itemView=srcHolder.itemView; itemView.setHasTransientState(true); int[] pos={0, 0}; ImageView srcImage=srcHolder.itemView.findViewById(R.id.image); TextView srcName=srcHolder.itemView.findViewById(R.id.name); srcImage.getLocationInWindow(pos); int srcImgX=pos[0], srcImgY=pos[1]; image.getLocationInWindow(pos); int dstImgX=pos[0], dstImgY=pos[1]; int overlayImgSize=V.dp(200); float dstImgScale=image.getHeight()/(float)overlayImgSize; float srcImgScale=srcImage.getHeight()/(float)overlayImgSize; ImageView overlayImage=new ImageView(getActivity()); overlayImage.setScaleType(ImageView.ScaleType.FIT_CENTER); overlayImage.setImageDrawable(srcImage.getDrawable()); parent.addView(overlayImage, new FrameLayout.LayoutParams(overlayImgSize, overlayImgSize, Gravity.TOP | Gravity.LEFT)); float imgTransXFrom=srcImgX+srcImage.getWidth()/2f-overlayImgSize/2f; float imgTransYFrom=srcImgY+srcImage.getHeight()/2f-overlayImgSize/2f; float imgTransXTo=dstImgX+image.getWidth()/2f-overlayImgSize/2f; float imgTransYTo=dstImgY+image.getHeight()/2f-overlayImgSize/2f; anims.add(ObjectAnimator.ofFloat(overlayImage, View.TRANSLATION_X, in ? imgTransXFrom : imgTransXTo, in ? imgTransXTo : imgTransXFrom)); anims.add(ObjectAnimator.ofFloat(overlayImage, View.TRANSLATION_Y, in ? imgTransYFrom : imgTransYTo, in ? imgTransYTo : imgTransYFrom)); anims.add(ObjectAnimator.ofFloat(overlayImage, View.SCALE_X, in ? srcImgScale : dstImgScale, in ? dstImgScale : srcImgScale)); anims.add(ObjectAnimator.ofFloat(overlayImage, View.SCALE_Y, in ? srcImgScale : dstImgScale, in ? dstImgScale : srcImgScale)); TextView overlayNameSmall=new TextView(getActivity()); overlayNameSmall.setTextSize(TypedValue.COMPLEX_UNIT_PX, srcName.getTextSize()); overlayNameSmall.setTextColor(srcName.getTextColors()); overlayNameSmall.setSingleLine(); overlayNameSmall.setEllipsize(TextUtils.TruncateAt.END); overlayNameSmall.setGravity(Gravity.CENTER); overlayNameSmall.setText(pokemon.name); parent.addView(overlayNameSmall, new FrameLayout.LayoutParams(srcName.getWidth(), srcName.getHeight(), Gravity.TOP | Gravity.LEFT)); TextView overlayNameLarge=new TextView(getActivity()); overlayNameLarge.setTextSize(TypedValue.COMPLEX_UNIT_PX, name.getTextSize()); overlayNameLarge.setTextColor(name.getTextColors()); overlayNameLarge.setSingleLine(); overlayNameLarge.setEllipsize(TextUtils.TruncateAt.END); overlayNameLarge.setGravity(Gravity.CENTER); overlayNameLarge.setTypeface(name.getTypeface()); overlayNameLarge.setText(pokemon.name); parent.addView(overlayNameLarge, new FrameLayout.LayoutParams(name.getWidth(), name.getHeight(), Gravity.TOP | Gravity.LEFT)); srcName.getLocationInWindow(pos); float smNameTransXFrom=pos[0]; float smNameTransYFrom=pos[1]; float lgNameTransXFrom=pos[0]+srcName.getWidth()/2f-name.getWidth()/2f; float lgNameTransYFrom=pos[1]+srcName.getHeight()/2f-name.getHeight()/2f; name.getLocationInWindow(pos); float smNameTransXTo=pos[0]+name.getWidth()/2f-srcName.getWidth()/2f; float smNameTransYTo=pos[1]+name.getHeight()/2f-srcName.getHeight()/2f; float lgNameTransXTo=pos[0]; float lgNameTransYTo=pos[1]; float smNameScaleTo=name.getHeight()/(float)srcName.getHeight(); float lgNameScaleFrom=srcName.getHeight()/(float)name.getHeight(); anims.add(ObjectAnimator.ofFloat(overlayNameSmall, View.TRANSLATION_X, in ? smNameTransXFrom : smNameTransXTo, in ? smNameTransXTo : smNameTransXFrom)); anims.add(ObjectAnimator.ofFloat(overlayNameSmall, View.TRANSLATION_Y, in ? smNameTransYFrom : smNameTransYTo, in ? smNameTransYTo : smNameTransYFrom)); anims.add(ObjectAnimator.ofFloat(overlayNameSmall, View.SCALE_X, in ? 1f : smNameScaleTo, in ? smNameScaleTo : 1f)); anims.add(ObjectAnimator.ofFloat(overlayNameSmall, View.SCALE_Y, in ? 1f : smNameScaleTo, in ? smNameScaleTo : 1f)); anims.add(ObjectAnimator.ofFloat(overlayNameLarge, View.TRANSLATION_X, in ? lgNameTransXFrom : lgNameTransXTo, in ? lgNameTransXTo : lgNameTransXFrom)); anims.add(ObjectAnimator.ofFloat(overlayNameLarge, View.TRANSLATION_Y, in ? lgNameTransYFrom : lgNameTransYTo, in ? lgNameTransYTo : lgNameTransYFrom)); anims.add(ObjectAnimator.ofFloat(overlayNameLarge, View.SCALE_X, in ? lgNameScaleFrom : 1f, in ? 1f : lgNameScaleFrom)); anims.add(ObjectAnimator.ofFloat(overlayNameLarge, View.SCALE_Y, in ? lgNameScaleFrom : 1f, in ? 1f : lgNameScaleFrom)); anims.add(ObjectAnimator.ofFloat(overlayNameSmall, View.ALPHA, in ? 1f : 0f, in ? 0f : 1f)); anims.add(ObjectAnimator.ofFloat(overlayNameLarge, View.ALPHA, in ? 0f : 1f, in ? 1f : 0f)); image.setAlpha(0f); name.setAlpha(0f); set.addListener(new AnimatorListenerAdapter(){ @Override public void onAnimationEnd(Animator animation){ parent.removeView(overlayImage); parent.removeView(overlayNameSmall); parent.removeView(overlayNameLarge); srcImage.setAlpha(1f); image.setAlpha(1f); srcName.setAlpha(1f); name.setAlpha(1f); itemView.setHasTransientState(false); currentTransition=null; } @Override public void onAnimationStart(Animator animation){ // Prevents the image disappearing for one frame because the old one is already hidden but the overlay is not yet visible srcImage.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener(){ @Override public boolean onPreDraw(){ srcImage.getViewTreeObserver().removeOnPreDrawListener(this); srcImage.setAlpha(0f); srcName.setAlpha(0f); return true; } }); } }); } set.playTogether(anims); set.setDuration(500); set.setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT); currentTransition=set; return set; } }
java
Unlicense
229c925988509b06b824079f8202c0a5001116f7
2026-01-05T02:37:37.848615Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/PacketEncoder.java
src/main/java/com/github/puregero/minecraftstresstest/PacketEncoder.java
package com.github.puregero.minecraftstresstest; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class PacketEncoder extends MessageToByteEncoder<ByteBuf> { protected void encode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, ByteBuf byteBufDest) { FriendlyByteBuf friendlyByteBuf = new FriendlyByteBuf(byteBufDest); friendlyByteBuf.writeVarInt(byteBuf.readableBytes()); friendlyByteBuf.writeBytes(byteBuf); } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/FriendlyDataInputStream.java
src/main/java/com/github/puregero/minecraftstresstest/FriendlyDataInputStream.java
package com.github.puregero.minecraftstresstest; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.UUID; public class FriendlyDataInputStream extends DataInputStream { public FriendlyDataInputStream(InputStream in) { super(in); } public int readVarInt() throws IOException { int i = 0; int j = 0; byte b0; do { b0 = this.readByte(); i |= (b0 & 127) << j++ * 7; if (j > 5) { throw new RuntimeException("VarInt too big"); } } while ((b0 & 128) == 128); return i; } public long readVarLong() throws IOException { long i = 0L; int j = 0; byte b0; do { b0 = this.readByte(); i |= (long) (b0 & 127) << j++ * 7; if (j > 10) { throw new RuntimeException("VarLong too big"); } } while ((b0 & 128) == 128); return i; } public UUID readUUID() throws IOException { return new UUID(this.readLong(), this.readLong()); } public String readString() throws IOException { byte[] stringBytes = new byte[readVarInt()]; readFully(stringBytes); return new String(stringBytes, StandardCharsets.UTF_8); } public int remaining() { if (in instanceof ByteArrayInputStream byteArrayInputStream) { return byteArrayInputStream.available(); } throw new UnsupportedOperationException("Not a ByteArrayInputStream"); } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/PacketIds.java
src/main/java/com/github/puregero/minecraftstresstest/PacketIds.java
package com.github.puregero.minecraftstresstest; public final class PacketIds { private PacketIds() { } public static final class Clientbound { private Clientbound() { } public static final class Login { private Login() { } public static final int DISCONNECT = 0x00, ENCRYPTION_REQUEST = 0x01, LOGIN_SUCCESS = 0x02, SET_COMPRESSION = 0x03; } public static final class Configuration { private Configuration() { } public static final int DISCONNECT = 0x02, FINISH_CONFIGURATION = 0x03, KEEP_ALIVE = 0x04, PING = 0x05; } public static final class Play { private Play() { } //client outbound public static final int DISCONNECT = 0x1D, KEEP_ALIVE = 0x26, PING = 0x35, SYNCHRONIZE_PLAYER_POSITION = 0x40, RESOURCE_PACK = 0x46, SET_HEALTH = 0x5D; } } public static final class Serverbound { private Serverbound() { } public static final class Handshaking { private Handshaking() { } public static final int HANDSHAKE = 0x00; } public static final class Login { private Login() { } public static final int LOGIN_START = 0x00, LOGIN_ACKNOWLEDGED = 0x03; } public static final class Configuration { private Configuration() { } public static final int CLIENT_INFORMATION = 0x00, FINISH_CONFIGURATION = 0x03, KEEP_ALIVE = 0x04, PONG = 0x05, KNOWN_PACKS = 0x07; } public static final class Play { private Play() { } public static final int CONFIRM_TELEPORTATION = 0x00, CLIENT_RESPAWN = 0x09, KEEP_ALIVE = 0x18, SET_PLAYER_POSITION_AND_ROTATION = 0x1B, PONG = 0x27, RESOURCE_PACK = 0x2B; } } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/CompressionDecoder.java
src/main/java/com/github/puregero/minecraftstresstest/CompressionDecoder.java
package com.github.puregero.minecraftstresstest; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.nio.ByteBuffer; import java.util.List; import java.util.zip.Inflater; public class CompressionDecoder extends ByteToMessageDecoder { private final Inflater inflater = new Inflater(); @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { if (byteBuf.readableBytes() != 0) { FriendlyByteBuf friendlyByteBuf = new FriendlyByteBuf(byteBuf); int length = friendlyByteBuf.readVarInt(); if (length == 0) { list.add(friendlyByteBuf.readBytes(friendlyByteBuf.readableBytes())); return; } ByteBuffer bs; if (friendlyByteBuf.nioBufferCount() > 0) { bs = friendlyByteBuf.nioBuffer(); friendlyByteBuf.skipBytes(friendlyByteBuf.readableBytes()); } else { bs = ByteBuffer.allocateDirect(friendlyByteBuf.readableBytes()); friendlyByteBuf.readBytes(bs); bs.flip(); } this.inflater.setInput(bs); ByteBuf cs = channelHandlerContext.alloc().directBuffer(length); ByteBuffer csInternal = cs.internalNioBuffer(0, length); int startPos = csInternal.position(); this.inflater.inflate(csInternal); int csLength = csInternal.position() - startPos; if (csLength != length) { throw new IllegalStateException("Decompressed length " + csLength + " does not match expected length " + length); } cs.writerIndex(cs.writerIndex() + csLength); this.inflater.reset(); list.add(cs); } } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/Bot.java
src/main/java/com/github/puregero/minecraftstresstest/Bot.java
package com.github.puregero.minecraftstresstest; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.socket.SocketChannel; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class Bot extends ChannelInboundHandlerAdapter { private static final int PROTOCOL_VERSION = Integer.parseInt(System.getProperty("bot.protocol.version", "767")); // 767 is 1.21 https://wiki.vg/Protocol_version_numbers private static final double CENTER_X = Double.parseDouble(System.getProperty("bot.x", "0")); private static final double CENTER_Z = Double.parseDouble(System.getProperty("bot.z", "0")); private static final boolean LOGS = Boolean.parseBoolean(System.getProperty("bot.logs", "true")); private static final boolean Y_AXIS = Boolean.parseBoolean(System.getProperty("bot.yaxis", "true")); private static final int VIEW_DISTANCE = Integer.parseInt(System.getProperty("bot.viewdistance", "2")); private static final int RESOURCE_PACK_RESPONSE = Integer.parseInt(System.getProperty("bot.resource.pack.response", "3")); private static final Executor ONE_TICK_DELAY = CompletableFuture.delayedExecutor(50, TimeUnit.MILLISECONDS); public static final String DEFAULT_SPEED = "0.1"; public static double SPEED = Double.parseDouble(System.getProperty("bot.speed", DEFAULT_SPEED)); public static final String DEFAULT_RADIUS = "1000"; public static double RADIUS = Double.parseDouble(System.getProperty("bot.radius", DEFAULT_RADIUS)); public SocketChannel channel; private String username; private final String address; private final int port; private UUID uuid; private boolean loginState = true; private boolean configState = false; private boolean playState = false; private double x = 0; private double y = 0; private double z = 0; private float yaw = (float) (Math.random() * 360); private boolean goUp = false; private boolean goDown = false; private boolean isSpawned = false; public Bot(String username, String address, int port) { this.username = username; this.address = address; this.port = port; } @Override public void channelActive(final ChannelHandlerContext ctx) { sendPacket(ctx, PacketIds.Serverbound.Handshaking.HANDSHAKE, buffer -> { buffer.writeVarInt(PROTOCOL_VERSION); buffer.writeUtf(address); buffer.writeShort(port); buffer.writeVarInt(2); }); sendPacket(ctx, PacketIds.Serverbound.Login.LOGIN_START, buffer -> { buffer.writeUtf(username); buffer.writeUUID(UUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(StandardCharsets.UTF_8))); }); } @Override public void channelInactive(final ChannelHandlerContext ctx) { if (uuid != null) { System.out.println(username + " has disconnected from " + address + ":" + port); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try { FriendlyByteBuf byteBuf = new FriendlyByteBuf((ByteBuf) msg); if (loginState) { channelReadLogin(ctx, byteBuf); } else if (configState) { channelReadConfig(ctx, byteBuf); } else if (playState) { channelReadPlay(ctx, byteBuf); } } finally { ((ByteBuf) msg).release(); } } private void channelReadLogin(ChannelHandlerContext ctx, FriendlyByteBuf byteBuf) { int packetId = byteBuf.readVarInt(); if (packetId == PacketIds.Clientbound.Login.DISCONNECT) { System.out.println(username + " was disconnected during login due to " + byteBuf.readUtf()); ctx.close(); } else if (packetId == PacketIds.Clientbound.Login.ENCRYPTION_REQUEST) { System.out.println("Server requesting for ENCRYPTION_REQUEST, so it is on ONLINEMODE, disconnecting"); ctx.close(); } else if (packetId == PacketIds.Clientbound.Login.LOGIN_SUCCESS) { if (PROTOCOL_VERSION >= 764) { sendPacket(ctx, PacketIds.Serverbound.Login.LOGIN_ACKNOWLEDGED, buffer -> { }); } loggedIn(ctx, byteBuf); } else if (packetId == PacketIds.Clientbound.Login.SET_COMPRESSION) { byteBuf.readVarInt(); ctx.pipeline().addAfter("packetDecoder", "compressionDecoder", new CompressionDecoder()); ctx.pipeline().addAfter("packetEncoder", "compressionEncoder", new CompressionEncoder()); } else { throw new RuntimeException("Unknown login packet id of " + packetId); } } private void loggedIn(ChannelHandlerContext ctx, FriendlyByteBuf byteBuf) { UUID uuid = byteBuf.readUUID(); String username = byteBuf.readUtf(); int numberElements = byteBuf.readVarInt(); //number of elements after this position boolean isSigned = false; if (numberElements > 0) { try { byteBuf.readUtf(); //name byteBuf.readUtf(); //value isSigned = byteBuf.readBoolean(); //issigned } catch (Exception e) { } } this.uuid = uuid; this.username = username; if (isSigned) { System.out.println(username + " (" + uuid + ") has logged in on an ONLINEMODE server, stopping"); ctx.close(); return; } else System.out.println(username + " (" + uuid + ") has logged in"); loginState = false; configState = true; //System.out.println("changing to config mode"); CompletableFuture.delayedExecutor(1000, TimeUnit.MILLISECONDS).execute(() -> { if (configState) { sendPacket(ctx, PacketIds.Serverbound.Configuration.CLIENT_INFORMATION, buffer -> { buffer.writeUtf("en_GB"); buffer.writeByte(VIEW_DISTANCE); buffer.writeVarInt(0); buffer.writeBoolean(true); buffer.writeByte(0); buffer.writeVarInt(0); buffer.writeBoolean(false); buffer.writeBoolean(true); }); sendPacket(ctx, PacketIds.Serverbound.Configuration.KNOWN_PACKS, buffer -> { buffer.writeVarInt(0); }); } CompletableFuture.delayedExecutor(1000, TimeUnit.MILLISECONDS).execute(() -> tick(ctx)); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } private void tick(ChannelHandlerContext ctx) { if (!ctx.channel().isActive()) return; ONE_TICK_DELAY.execute(() -> tick(ctx)); if (!isSpawned) return; // Don't tick until we've spawned in if (!Y_AXIS && (goUp || goDown)) { goDown = goUp = false; if (Math.random() < 0.1) yaw = (float) (Math.random() * 360); } if (goUp) { y += 0.1; goUp = Math.random() < 0.98; } else if (goDown) { y -= 0.1; goDown = Math.random() < 0.98; } else { if (Math.max(Math.abs(x - CENTER_X), Math.abs(z - CENTER_Z)) > RADIUS) { double tx = Math.random() * RADIUS * 2 - RADIUS + CENTER_X; double tz = Math.random() * RADIUS * 2 - RADIUS + CENTER_Z; yaw = (float) Math.toDegrees(Math.atan2(x - tx, tz - z)); } x += SPEED * -Math.sin(Math.toRadians(yaw)); z += SPEED * Math.cos(Math.toRadians(yaw)); } if (Y_AXIS) { y -= SPEED / 10; } sendPacket(ctx, PacketIds.Serverbound.Play.SET_PLAYER_POSITION_AND_ROTATION, buffer -> { buffer.writeDouble(x); buffer.writeDouble(y); buffer.writeDouble(z); buffer.writeFloat(yaw); buffer.writeFloat(0); buffer.writeBoolean(true); }); } private void channelReadConfig(ChannelHandlerContext ctx, FriendlyByteBuf byteBuf) { int packetId = byteBuf.readVarInt(); if (packetId == PacketIds.Clientbound.Configuration.DISCONNECT) { System.out.println(username + " (" + uuid + ") (config) was kicked due to " + byteBuf.readUtf()); ctx.close(); } else if (packetId == PacketIds.Clientbound.Configuration.FINISH_CONFIGURATION) { sendPacket(ctx, PacketIds.Serverbound.Configuration.FINISH_CONFIGURATION, buffer -> { }); configState = false; playState = true; //System.out.println("changing to play mode"); } else if (packetId == PacketIds.Clientbound.Configuration.KEEP_ALIVE) { long id = byteBuf.readLong(); sendPacket(ctx, PacketIds.Serverbound.Configuration.KEEP_ALIVE, buffer -> buffer.writeLong(id)); //System.out.println(username + " (" + uuid + ") keep alive config mode"); } else if (packetId == PacketIds.Clientbound.Configuration.PING) { int id = byteBuf.readInt(); sendPacket(ctx, PacketIds.Serverbound.Configuration.PONG, buffer -> buffer.writeInt(id)); //System.out.println(username + " (" + uuid + ") ping config mode"); } } private void channelReadPlay(ChannelHandlerContext ctx, FriendlyByteBuf byteBuf) { int packetId = byteBuf.readVarInt(); if (packetId == PacketIds.Clientbound.Play.DISCONNECT) { System.out.println(username + " (" + uuid + ") was kicked due to " + byteBuf.readUtf()); ctx.close(); loginState = true; playState = false; } else if (packetId == PacketIds.Clientbound.Play.KEEP_ALIVE) { long id = byteBuf.readLong(); sendPacket(ctx, PacketIds.Serverbound.Play.KEEP_ALIVE, buffer -> buffer.writeLong(id)); } else if (packetId == PacketIds.Clientbound.Play.PING) { int id = byteBuf.readInt(); sendPacket(ctx, PacketIds.Serverbound.Play.PONG, buffer -> buffer.writeInt(id)); } else if (packetId == PacketIds.Clientbound.Play.SYNCHRONIZE_PLAYER_POSITION) { double dx = byteBuf.readDouble(); double dy = byteBuf.readDouble(); double dz = byteBuf.readDouble(); float dyaw = byteBuf.readFloat(); float dpitch = byteBuf.readFloat(); byte flags = byteBuf.readByte(); int id = byteBuf.readVarInt(); x = (flags & 0x01) == 0x01 ? x + dx : dx; y = (flags & 0x02) == 0x02 ? y + dy : dy; z = (flags & 0x04) == 0x04 ? z + dz : dz; if (LOGS) { System.out.println("Teleporting " + username + " to " + x + "," + y + "," + z); } // Try going up to go over the block, or turn around and go a different way if (goDown) { goDown = false; } else if (!goUp) { goUp = true; } else { // We hit our head on something goUp = false; goDown = Math.random() < 0.5; if (!goDown) yaw = (float) (Math.random() * 360); } sendPacket(ctx, PacketIds.Serverbound.Play.CONFIRM_TELEPORTATION, buffer -> buffer.writeVarInt(id)); isSpawned = true; } else if (packetId == PacketIds.Clientbound.Play.RESOURCE_PACK) { String url = byteBuf.readUtf(); String hash = byteBuf.readUtf(); boolean forced = byteBuf.readBoolean(); String message = null; if (byteBuf.readBoolean()) message = byteBuf.readUtf(); System.out.println("Resource pack info:\n" + url + "\n" + hash + "\n" + forced + "\n" + message); sendPacket(ctx, PacketIds.Serverbound.Play.RESOURCE_PACK, buffer -> buffer.writeVarInt(RESOURCE_PACK_RESPONSE)); } else if (packetId == PacketIds.Clientbound.Play.SET_HEALTH) { float health = byteBuf.readFloat(); if (health <= 0) { sendPacket(ctx, PacketIds.Serverbound.Play.CLIENT_RESPAWN, buffer -> buffer.writeVarInt(0)); } } } public void close() { channel.close(); } public void sendPacket(ChannelHandlerContext ctx, int packetId, Consumer<FriendlyByteBuf> applyToBuffer) { FriendlyByteBuf buffer = new FriendlyByteBuf(ctx.alloc().buffer()); buffer.writeVarInt(packetId); applyToBuffer.accept(buffer); ctx.writeAndFlush(buffer); } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/CompressionEncoder.java
src/main/java/com/github/puregero/minecraftstresstest/CompressionEncoder.java
package com.github.puregero.minecraftstresstest; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; public class CompressionEncoder extends MessageToByteEncoder<ByteBuf> { protected void encode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, ByteBuf byteBufDest) { FriendlyByteBuf friendlyByteBuf = new FriendlyByteBuf(byteBufDest); friendlyByteBuf.writeVarInt(0); friendlyByteBuf.writeBytes(byteBuf); } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/FriendlyByteBuf.java
src/main/java/com/github/puregero/minecraftstresstest/FriendlyByteBuf.java
package com.github.puregero.minecraftstresstest; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.EncoderException; import io.netty.util.ByteProcessor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.UUID; public class FriendlyByteBuf extends ByteBuf { private final ByteBuf source; public FriendlyByteBuf(ByteBuf parent) { this.source = parent; } public static int getVarIntSize(int value) { for (int j = 1; j < 5; ++j) { if ((value & -1 << j * 7) == 0) { return j; } } return 5; } public static int getVarLongSize(long value) { for (int j = 1; j < 10; ++j) { if ((value & -1L << j * 7) == 0L) { return j; } } return 10; } public int readVarInt() { int i = 0; int j = 0; byte b0; do { b0 = this.readByte(); i |= (b0 & 127) << j++ * 7; if (j > 5) { throw new RuntimeException("VarInt too big"); } } while ((b0 & 128) == 128); return i; } public long readVarLong() { long i = 0L; int j = 0; byte b0; do { b0 = this.readByte(); i |= (long) (b0 & 127) << j++ * 7; if (j > 10) { throw new RuntimeException("VarLong too big"); } } while ((b0 & 128) == 128); return i; } public FriendlyByteBuf writeUUID(UUID uuid) { this.writeLong(uuid.getMostSignificantBits()); this.writeLong(uuid.getLeastSignificantBits()); return this; } public UUID readUUID() { return new UUID(this.readLong(), this.readLong()); } public FriendlyByteBuf writeVarInt(int value) { while ((value & -128) != 0) { this.writeByte(value & 127 | 128); value >>>= 7; } this.writeByte(value); return this; } public FriendlyByteBuf writeVarLong(long value) { while ((value & -128L) != 0L) { this.writeByte((int) (value & 127L) | 128); value >>>= 7; } this.writeByte((int) value); return this; } public String readUtf() { return this.readUtf(32767); } public String readUtf(int maxLength) { int j = this.readVarInt(); if (j > maxLength * 4) { throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + j + " > " + maxLength * 4 + ")"); } else if (j < 0) { throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); } else { String s = this.toString(this.readerIndex(), j, StandardCharsets.UTF_8); this.readerIndex(this.readerIndex() + j); if (s.length() > maxLength) { throw new DecoderException("The received string length is longer than maximum allowed (" + j + " > " + maxLength + ")"); } else { return s; } } } public FriendlyByteBuf writeUtf(String string) { return this.writeUtf(string, 32767); } public FriendlyByteBuf writeUtf(String string, int maxLength) { byte[] abyte = string.getBytes(StandardCharsets.UTF_8); if (abyte.length > maxLength) { throw new EncoderException("String too big (was " + abyte.length + " bytes encoded, max " + maxLength + ")"); } else { this.writeVarInt(abyte.length); this.writeBytes(abyte); return this; } } public int capacity() { return this.source.capacity(); } public ByteBuf capacity(int i) { return this.source.capacity(i); } public int maxCapacity() { return this.source.maxCapacity(); } public ByteBufAllocator alloc() { return this.source.alloc(); } public ByteOrder order() { return this.source.order(); } public ByteBuf order(ByteOrder byteorder) { return this.source.order(byteorder); } public ByteBuf unwrap() { return this.source.unwrap(); } public boolean isDirect() { return this.source.isDirect(); } public boolean isReadOnly() { return this.source.isReadOnly(); } public ByteBuf asReadOnly() { return this.source.asReadOnly(); } public int readerIndex() { return this.source.readerIndex(); } public ByteBuf readerIndex(int i) { return this.source.readerIndex(i); } public int writerIndex() { return this.source.writerIndex(); } public ByteBuf writerIndex(int i) { return this.source.writerIndex(i); } public ByteBuf setIndex(int i, int j) { return this.source.setIndex(i, j); } public int readableBytes() { return this.source.readableBytes(); } public int writableBytes() { return this.source.writableBytes(); } public int maxWritableBytes() { return this.source.maxWritableBytes(); } public boolean isReadable() { return this.source.isReadable(); } public boolean isReadable(int i) { return this.source.isReadable(i); } public boolean isWritable() { return this.source.isWritable(); } public boolean isWritable(int i) { return this.source.isWritable(i); } public ByteBuf clear() { return this.source.clear(); } public ByteBuf markReaderIndex() { return this.source.markReaderIndex(); } public ByteBuf resetReaderIndex() { return this.source.resetReaderIndex(); } public ByteBuf markWriterIndex() { return this.source.markWriterIndex(); } public ByteBuf resetWriterIndex() { return this.source.resetWriterIndex(); } public ByteBuf discardReadBytes() { return this.source.discardReadBytes(); } public ByteBuf discardSomeReadBytes() { return this.source.discardSomeReadBytes(); } public ByteBuf ensureWritable(int i) { return this.source.ensureWritable(i); } public int ensureWritable(int i, boolean flag) { return this.source.ensureWritable(i, flag); } public boolean getBoolean(int i) { return this.source.getBoolean(i); } public byte getByte(int i) { return this.source.getByte(i); } public short getUnsignedByte(int i) { return this.source.getUnsignedByte(i); } public short getShort(int i) { return this.source.getShort(i); } public short getShortLE(int i) { return this.source.getShortLE(i); } public int getUnsignedShort(int i) { return this.source.getUnsignedShort(i); } public int getUnsignedShortLE(int i) { return this.source.getUnsignedShortLE(i); } public int getMedium(int i) { return this.source.getMedium(i); } public int getMediumLE(int i) { return this.source.getMediumLE(i); } public int getUnsignedMedium(int i) { return this.source.getUnsignedMedium(i); } public int getUnsignedMediumLE(int i) { return this.source.getUnsignedMediumLE(i); } public int getInt(int i) { return this.source.getInt(i); } public int getIntLE(int i) { return this.source.getIntLE(i); } public long getUnsignedInt(int i) { return this.source.getUnsignedInt(i); } public long getUnsignedIntLE(int i) { return this.source.getUnsignedIntLE(i); } public long getLong(int i) { return this.source.getLong(i); } public long getLongLE(int i) { return this.source.getLongLE(i); } public char getChar(int i) { return this.source.getChar(i); } public float getFloat(int i) { return this.source.getFloat(i); } public double getDouble(int i) { return this.source.getDouble(i); } public ByteBuf getBytes(int i, ByteBuf bytebuf) { return this.source.getBytes(i, bytebuf); } public ByteBuf getBytes(int i, ByteBuf bytebuf, int j) { return this.source.getBytes(i, bytebuf, j); } public ByteBuf getBytes(int i, ByteBuf bytebuf, int j, int k) { return this.source.getBytes(i, bytebuf, j, k); } public ByteBuf getBytes(int i, byte[] abyte) { return this.source.getBytes(i, abyte); } public ByteBuf getBytes(int i, byte[] abyte, int j, int k) { return this.source.getBytes(i, abyte, j, k); } public ByteBuf getBytes(int i, ByteBuffer bytebuffer) { return this.source.getBytes(i, bytebuffer); } public ByteBuf getBytes(int i, OutputStream outputstream, int j) throws IOException { return this.source.getBytes(i, outputstream, j); } public int getBytes(int i, GatheringByteChannel gatheringbytechannel, int j) throws IOException { return this.source.getBytes(i, gatheringbytechannel, j); } public int getBytes(int i, FileChannel filechannel, long j, int k) throws IOException { return this.source.getBytes(i, filechannel, j, k); } public CharSequence getCharSequence(int i, int j, Charset charset) { return this.source.getCharSequence(i, j, charset); } public ByteBuf setBoolean(int i, boolean flag) { return this.source.setBoolean(i, flag); } public ByteBuf setByte(int i, int j) { return this.source.setByte(i, j); } public ByteBuf setShort(int i, int j) { return this.source.setShort(i, j); } public ByteBuf setShortLE(int i, int j) { return this.source.setShortLE(i, j); } public ByteBuf setMedium(int i, int j) { return this.source.setMedium(i, j); } public ByteBuf setMediumLE(int i, int j) { return this.source.setMediumLE(i, j); } public ByteBuf setInt(int i, int j) { return this.source.setInt(i, j); } public ByteBuf setIntLE(int i, int j) { return this.source.setIntLE(i, j); } public ByteBuf setLong(int i, long j) { return this.source.setLong(i, j); } public ByteBuf setLongLE(int i, long j) { return this.source.setLongLE(i, j); } public ByteBuf setChar(int i, int j) { return this.source.setChar(i, j); } public ByteBuf setFloat(int i, float f) { return this.source.setFloat(i, f); } public ByteBuf setDouble(int i, double d0) { return this.source.setDouble(i, d0); } public ByteBuf setBytes(int i, ByteBuf bytebuf) { return this.source.setBytes(i, bytebuf); } public ByteBuf setBytes(int i, ByteBuf bytebuf, int j) { return this.source.setBytes(i, bytebuf, j); } public ByteBuf setBytes(int i, ByteBuf bytebuf, int j, int k) { return this.source.setBytes(i, bytebuf, j, k); } public ByteBuf setBytes(int i, byte[] abyte) { return this.source.setBytes(i, abyte); } public ByteBuf setBytes(int i, byte[] abyte, int j, int k) { return this.source.setBytes(i, abyte, j, k); } public ByteBuf setBytes(int i, ByteBuffer bytebuffer) { return this.source.setBytes(i, bytebuffer); } public int setBytes(int i, InputStream inputstream, int j) throws IOException { return this.source.setBytes(i, inputstream, j); } public int setBytes(int i, ScatteringByteChannel scatteringbytechannel, int j) throws IOException { return this.source.setBytes(i, scatteringbytechannel, j); } public int setBytes(int i, FileChannel filechannel, long j, int k) throws IOException { return this.source.setBytes(i, filechannel, j, k); } public ByteBuf setZero(int i, int j) { return this.source.setZero(i, j); } public int setCharSequence(int i, CharSequence charsequence, Charset charset) { return this.source.setCharSequence(i, charsequence, charset); } public boolean readBoolean() { return this.source.readBoolean(); } public byte readByte() { return this.source.readByte(); } public short readUnsignedByte() { return this.source.readUnsignedByte(); } public short readShort() { return this.source.readShort(); } public short readShortLE() { return this.source.readShortLE(); } public int readUnsignedShort() { return this.source.readUnsignedShort(); } public int readUnsignedShortLE() { return this.source.readUnsignedShortLE(); } public int readMedium() { return this.source.readMedium(); } public int readMediumLE() { return this.source.readMediumLE(); } public int readUnsignedMedium() { return this.source.readUnsignedMedium(); } public int readUnsignedMediumLE() { return this.source.readUnsignedMediumLE(); } public int readInt() { return this.source.readInt(); } public int readIntLE() { return this.source.readIntLE(); } public long readUnsignedInt() { return this.source.readUnsignedInt(); } public long readUnsignedIntLE() { return this.source.readUnsignedIntLE(); } public long readLong() { return this.source.readLong(); } public long readLongLE() { return this.source.readLongLE(); } public char readChar() { return this.source.readChar(); } public float readFloat() { return this.source.readFloat(); } public double readDouble() { return this.source.readDouble(); } public ByteBuf readBytes(int i) { return this.source.readBytes(i); } public ByteBuf readSlice(int i) { return this.source.readSlice(i); } public ByteBuf readRetainedSlice(int i) { return this.source.readRetainedSlice(i); } public ByteBuf readBytes(ByteBuf bytebuf) { return this.source.readBytes(bytebuf); } public ByteBuf readBytes(ByteBuf bytebuf, int i) { return this.source.readBytes(bytebuf, i); } public ByteBuf readBytes(ByteBuf bytebuf, int i, int j) { return this.source.readBytes(bytebuf, i, j); } public ByteBuf readBytes(byte[] abyte) { return this.source.readBytes(abyte); } public ByteBuf readBytes(byte[] abyte, int i, int j) { return this.source.readBytes(abyte, i, j); } public ByteBuf readBytes(ByteBuffer bytebuffer) { return this.source.readBytes(bytebuffer); } public ByteBuf readBytes(OutputStream outputstream, int i) throws IOException { return this.source.readBytes(outputstream, i); } public int readBytes(GatheringByteChannel gatheringbytechannel, int i) throws IOException { return this.source.readBytes(gatheringbytechannel, i); } public CharSequence readCharSequence(int i, Charset charset) { return this.source.readCharSequence(i, charset); } public int readBytes(FileChannel filechannel, long i, int j) throws IOException { return this.source.readBytes(filechannel, i, j); } public ByteBuf skipBytes(int i) { return this.source.skipBytes(i); } public ByteBuf writeBoolean(boolean flag) { return this.source.writeBoolean(flag); } public ByteBuf writeByte(int i) { return this.source.writeByte(i); } public ByteBuf writeShort(int i) { return this.source.writeShort(i); } public ByteBuf writeShortLE(int i) { return this.source.writeShortLE(i); } public ByteBuf writeMedium(int i) { return this.source.writeMedium(i); } public ByteBuf writeMediumLE(int i) { return this.source.writeMediumLE(i); } public ByteBuf writeInt(int i) { return this.source.writeInt(i); } public ByteBuf writeIntLE(int i) { return this.source.writeIntLE(i); } public ByteBuf writeLong(long i) { return this.source.writeLong(i); } public ByteBuf writeLongLE(long i) { return this.source.writeLongLE(i); } public ByteBuf writeChar(int i) { return this.source.writeChar(i); } public ByteBuf writeFloat(float f) { return this.source.writeFloat(f); } public ByteBuf writeDouble(double d0) { return this.source.writeDouble(d0); } public ByteBuf writeBytes(ByteBuf bytebuf) { return this.source.writeBytes(bytebuf); } public ByteBuf writeBytes(ByteBuf bytebuf, int i) { return this.source.writeBytes(bytebuf, i); } public ByteBuf writeBytes(ByteBuf bytebuf, int i, int j) { return this.source.writeBytes(bytebuf, i, j); } public ByteBuf writeBytes(byte[] abyte) { return this.source.writeBytes(abyte); } public ByteBuf writeBytes(byte[] abyte, int i, int j) { return this.source.writeBytes(abyte, i, j); } public ByteBuf writeBytes(ByteBuffer bytebuffer) { return this.source.writeBytes(bytebuffer); } public int writeBytes(InputStream inputstream, int i) throws IOException { return this.source.writeBytes(inputstream, i); } public int writeBytes(ScatteringByteChannel scatteringbytechannel, int i) throws IOException { return this.source.writeBytes(scatteringbytechannel, i); } public int writeBytes(FileChannel filechannel, long i, int j) throws IOException { return this.source.writeBytes(filechannel, i, j); } public ByteBuf writeZero(int i) { return this.source.writeZero(i); } public int writeCharSequence(CharSequence charsequence, Charset charset) { return this.source.writeCharSequence(charsequence, charset); } public int indexOf(int i, int j, byte b0) { return this.source.indexOf(i, j, b0); } public int bytesBefore(byte b0) { return this.source.bytesBefore(b0); } public int bytesBefore(int i, byte b0) { return this.source.bytesBefore(i, b0); } public int bytesBefore(int i, int j, byte b0) { return this.source.bytesBefore(i, j, b0); } public int forEachByte(ByteProcessor byteprocessor) { return this.source.forEachByte(byteprocessor); } public int forEachByte(int i, int j, ByteProcessor byteprocessor) { return this.source.forEachByte(i, j, byteprocessor); } public int forEachByteDesc(ByteProcessor byteprocessor) { return this.source.forEachByteDesc(byteprocessor); } public int forEachByteDesc(int i, int j, ByteProcessor byteprocessor) { return this.source.forEachByteDesc(i, j, byteprocessor); } public ByteBuf copy() { return this.source.copy(); } public ByteBuf copy(int i, int j) { return this.source.copy(i, j); } public ByteBuf slice() { return this.source.slice(); } public ByteBuf retainedSlice() { return this.source.retainedSlice(); } public ByteBuf slice(int i, int j) { return this.source.slice(i, j); } public ByteBuf retainedSlice(int i, int j) { return this.source.retainedSlice(i, j); } public ByteBuf duplicate() { return this.source.duplicate(); } public ByteBuf retainedDuplicate() { return this.source.retainedDuplicate(); } public int nioBufferCount() { return this.source.nioBufferCount(); } public ByteBuffer nioBuffer() { return this.source.nioBuffer(); } public ByteBuffer nioBuffer(int i, int j) { return this.source.nioBuffer(i, j); } public ByteBuffer internalNioBuffer(int i, int j) { return this.source.internalNioBuffer(i, j); } public ByteBuffer[] nioBuffers() { return this.source.nioBuffers(); } public ByteBuffer[] nioBuffers(int i, int j) { return this.source.nioBuffers(i, j); } public boolean hasArray() { return this.source.hasArray(); } public byte[] array() { return this.source.array(); } public int arrayOffset() { return this.source.arrayOffset(); } public boolean hasMemoryAddress() { return this.source.hasMemoryAddress(); } public long memoryAddress() { return this.source.memoryAddress(); } public String toString(Charset charset) { return this.source.toString(charset); } public String toString(int i, int j, Charset charset) { return this.source.toString(i, j, charset); } public int hashCode() { return this.source.hashCode(); } public boolean equals(Object object) { return this.source.equals(object); } public int compareTo(ByteBuf bytebuf) { return this.source.compareTo(bytebuf); } public String toString() { return this.source.toString(); } public ByteBuf retain(int i) { return this.source.retain(i); } public ByteBuf retain() { return this.source.retain(); } public ByteBuf touch() { return this.source.touch(); } public ByteBuf touch(Object object) { return this.source.touch(object); } public int refCnt() { return this.source.refCnt(); } public boolean release() { return this.source.release(); } public boolean release(int i) { return this.source.release(i); } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/CommandLine.java
src/main/java/com/github/puregero/minecraftstresstest/CommandLine.java
package com.github.puregero.minecraftstresstest; import java.util.Scanner; public class CommandLine implements Runnable { @Override public void run() { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String line = scanner.nextLine(); String[] args = line.split(" "); try { if (args[0].equalsIgnoreCase("count") || args[0].equalsIgnoreCase("botcount")) { int botCount = Math.max(0, Integer.parseInt(args[1])); System.out.println("Setting bot count to " + botCount); MinecraftStressTest.BOT_COUNT = botCount; MinecraftStressTest.updateBotCount(); } else if (args[0].equalsIgnoreCase("speed")) { double speed = Math.max(0.0, Double.parseDouble(args[1])); System.out.println("Setting speed to " + speed); Bot.SPEED = speed; } else if (args[0].equalsIgnoreCase("radius")) { double radius = Math.max(0.0, Double.parseDouble(args[1])); System.out.println("Setting radius to " + radius); Bot.RADIUS = radius; } else if (args[0].equalsIgnoreCase("logindelay")) { int loginDelay = Math.max(0, Integer.parseInt(args[1])); System.out.println("Setting login delay to " + loginDelay); MinecraftStressTest.DELAY_BETWEEN_BOTS_MS = loginDelay; } else { System.out.println("Commands:"); System.out.println("count <number of bots> (Default: " + MinecraftStressTest.DEFAULT_BOT_COUNT + ")"); System.out.println("speed <value> (Default: " + Bot.DEFAULT_SPEED + ")"); System.out.println("radius <value> (Default: " + Bot.DEFAULT_RADIUS + ")"); System.out.println("logindelay <value> (Default: " + MinecraftStressTest.DEFAULT_DELAY_BETWEEN_BOTS_MS + ")"); } } catch (Exception e) { e.printStackTrace(); } } } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/PacketDecoder.java
src/main/java/com/github/puregero/minecraftstresstest/PacketDecoder.java
package com.github.puregero.minecraftstresstest; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.util.List; public class PacketDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) { int i = byteBuf.readableBytes(); if (i >= 3) { FriendlyByteBuf friendlyByteBuf = new FriendlyByteBuf(byteBuf); friendlyByteBuf.markReaderIndex(); int length = friendlyByteBuf.readVarInt(); if (friendlyByteBuf.readableBytes() < length) { friendlyByteBuf.resetReaderIndex(); return; } list.add(friendlyByteBuf.readBytes(length)); } } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/FriendlyDataOutputStream.java
src/main/java/com/github/puregero/minecraftstresstest/FriendlyDataOutputStream.java
package com.github.puregero.minecraftstresstest; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.UUID; public class FriendlyDataOutputStream extends DataOutputStream { public FriendlyDataOutputStream(OutputStream out) { super(out); } public FriendlyDataOutputStream() { super(new ByteArrayOutputStream()); } public void writeUUID(UUID uuid) throws IOException { this.writeLong(uuid.getMostSignificantBits()); this.writeLong(uuid.getLeastSignificantBits()); } public void writeVarInt(int value) throws IOException { while ((value & -128) != 0) { this.writeByte(value & 127 | 128); value >>>= 7; } this.writeByte(value); } public void writeVarLong(long value) throws IOException { while ((value & -128L) != 0L) { this.writeByte((int) (value & 127L) | 128); value >>>= 7; } this.writeByte((int) value); } public void writeString(String string) throws IOException { byte[] stringBytes = string.getBytes(StandardCharsets.UTF_8); writeVarInt(stringBytes.length); write(stringBytes); } public byte[] toByteArray() { if (out instanceof ByteArrayOutputStream byteArrayOutputStream) { return byteArrayOutputStream.toByteArray(); } throw new UnsupportedOperationException("Not a ByteArrayOutputStream"); } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
PureGero/minecraft-stress-test
https://github.com/PureGero/minecraft-stress-test/blob/98d002c7f0e096556104959c03c7c302661fb3d8/src/main/java/com/github/puregero/minecraftstresstest/MinecraftStressTest.java
src/main/java/com/github/puregero/minecraftstresstest/MinecraftStressTest.java
package com.github.puregero.minecraftstresstest; import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.kqueue.KQueue; import io.netty.channel.kqueue.KQueueEventLoopGroup; import io.netty.channel.kqueue.KQueueSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MinecraftStressTest { private static final String ADDRESS = System.getProperty("bot.ip", "127.0.0.1"); private static final int PORT = Integer.parseInt(System.getProperty("bot.port", "25565")); public static final String DEFAULT_DELAY_BETWEEN_BOTS_MS = "100"; public static int DELAY_BETWEEN_BOTS_MS = Integer.parseInt(System.getProperty("bot.login.delay.ms", DEFAULT_DELAY_BETWEEN_BOTS_MS)); public static final String DEFAULT_BOT_COUNT = "1"; public static int BOT_COUNT = Integer.parseInt(System.getProperty("bot.count", DEFAULT_BOT_COUNT)); private static final List<Bot> bots = new ArrayList<>(); private static final Lock botsLock = new ReentrantLock(); private static final AtomicBoolean addingBots = new AtomicBoolean(); private static final EventLoopGroup workerGroup; private static final Class<? extends SocketChannel> nettyChannelClass; static { if (Epoll.isAvailable()) { workerGroup = new EpollEventLoopGroup(); nettyChannelClass = EpollSocketChannel.class; } else if (KQueue.isAvailable()) { workerGroup = new KQueueEventLoopGroup(); nettyChannelClass = KQueueSocketChannel.class; } else { workerGroup = new NioEventLoopGroup(); nettyChannelClass = NioSocketChannel.class; } System.out.println("Using " + workerGroup.getClass().getSimpleName() + " with " + nettyChannelClass.getSimpleName() + " for network communication."); } public static void main(String[] args) { if (args.length > 0 && (args[0].equals("--help") || args[0].equals("-h"))) { printHelp(); return; } updateBotCount(); new CommandLine().run(); System.out.println("stdin ended"); } private static void printHelp() { System.out.println("Minecraft Stress Test"); System.out.println("Usage: java [options] -jar minecraft-stress-test.jar"); System.out.println("\nOptions:"); System.out.println(" -Dbot.ip=<ip> Set the server IP (default: 127.0.0.1)"); System.out.println(" -Dbot.port=<port> Set the server port (default: 25565)"); System.out.println(" -Dbot.count=<count> Set the number of bots (default: 1)"); System.out.println(" -Dbot.login.delay.ms=<delay> Set the delay between bot logins in ms (default: 100)"); System.out.println(" -Dbot.name=<name> Set the base name for bots (default: Bot)"); System.out.println(" -Dbot.x=<x> Set the center X coordinate (default: 0)"); System.out.println(" -Dbot.z=<z> Set the center Z coordinate (default: 0)"); System.out.println(" -Dbot.logs=<true|false> Enable or disable bot logs (default: true)"); System.out.println(" -Dbot.yaxis=<true|false> Enable or disable Y-axis movement (default: true)"); System.out.println(" -Dbot.viewdistance=<distance> Set the view distance (default: 2)"); System.out.println(" -Dbot.speed=<speed> Set the bot movement speed (default: 0.1)"); System.out.println(" -Dbot.radius=<radius> Set the movement radius (default: 1000)"); System.out.println("\nRuntime Commands:"); System.out.println(" count <number> Change the number of bots"); System.out.println(" speed <value> Change the bot movement speed"); System.out.println(" radius <value> Change the movement radius"); System.out.println(" logindelay <value> Change the delay between bot logins"); System.out.println("\nExample:"); System.out.println(" java -Dbot.ip=localhost -Dbot.port=25565 -Dbot.count=10 -jar minecraft-stress-test.jar"); } public static void updateBotCount() { removeBotsIfNeeded(); addBotIfNeeded(true); } private static void removeBotsIfNeeded() { botsLock.lock(); try { Bot removedBot; while (bots.size() > BOT_COUNT) { removedBot = bots.remove(bots.size() - 1); removedBot.close(); } } finally { botsLock.unlock(); } } private static void addBotIfNeeded(boolean firstCall) { if (!firstCall || !addingBots.getAndSet(true)) { boolean scheduledNextCall = false; try { botsLock.lock(); try { if (bots.size() < BOT_COUNT) { bots.add(connectBot(System.getProperty("bot.name", "Bot") + (bots.size() + 1), ADDRESS, PORT)); CompletableFuture.delayedExecutor(DELAY_BETWEEN_BOTS_MS, TimeUnit.MILLISECONDS).execute(() -> addBotIfNeeded(false)); scheduledNextCall = true; } } finally { botsLock.unlock(); } } finally { if (!scheduledNextCall) { addingBots.set(false); } } } } private static Bot connectBot(String name, String address, int port) { Bot bot = new Bot(name, address, port); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(nettyChannelClass); b.option(ChannelOption.SO_KEEPALIVE, true); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { bot.channel = ch; ch.pipeline().addLast("packetEncoder", new PacketEncoder()); ch.pipeline().addLast("packetDecoder", new PacketDecoder()); ch.pipeline().addLast("bot", bot); } }); b.connect(address, port); return bot; } }
java
MIT
98d002c7f0e096556104959c03c7c302661fb3d8
2026-01-05T02:37:38.694007Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/stream/EDIValidationExceptionTest.java
src/test/java/io/xlate/edi/stream/EDIValidationExceptionTest.java
package io.xlate.edi.stream; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class EDIValidationExceptionTest { @Test void testSetNextException() { EDIValidationException[] exceptions = { new EDIValidationException(null, null, null, null), new EDIValidationException(null, null, null, null), new EDIValidationException(null, null, null, null), new EDIValidationException(null, null, null, null), new EDIValidationException(null, null, null, null) }; EDIValidationException primary = new EDIValidationException(null, null, null, null); primary.setNextException(exceptions[0]); primary.setNextException(exceptions[1]); primary.setNextException(exceptions[2]); primary.setNextException(exceptions[3]); primary.setNextException(exceptions[4]); assertSame(exceptions[0], primary.getNextException()); assertSame(exceptions[1], primary.getNextException() .getNextException()); assertSame(exceptions[2], primary.getNextException() .getNextException() .getNextException()); assertSame(exceptions[3], primary.getNextException() .getNextException() .getNextException() .getNextException()); assertSame(exceptions[4], primary.getNextException() .getNextException() .getNextException() .getNextException() .getNextException()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/test/StaEDITestEvent.java
src/test/java/io/xlate/edi/test/StaEDITestEvent.java
package io.xlate.edi.test; import java.util.Objects; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.Location; public class StaEDITestEvent { public final EDIStreamEvent event; public final EDIStreamValidationError error; public final String text; public final String referenceCode; public final Location location; public StaEDITestEvent(EDIStreamEvent event, EDIStreamValidationError error, String text, String referenceCode, Location location) { super(); this.event = event; this.error = error; this.text = text; this.referenceCode = referenceCode; this.location = location; } public static StaEDITestEvent from(EDIStreamReader reader, boolean includeLocation) { EDIStreamEvent event = reader.getEventType(); boolean error; switch (event) { case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: error = true; break; default: error = false; break; } return new StaEDITestEvent(reader.getEventType(), error ? reader.getErrorType() : null, reader.hasText() ? reader.getText() : null, reader.getReferenceCode(), includeLocation ? reader.getLocation().copy() : null); } public static StaEDITestEvent forError(EDIStreamValidationError error, String text, String referenceCode) { return new StaEDITestEvent(error.getCategory(), error, text, referenceCode, null); } public static StaEDITestEvent forEvent(EDIStreamEvent event, String text, String referenceCode) { return new StaEDITestEvent(event, null, text, referenceCode, null); } @Override public boolean equals(Object obj) { if (obj instanceof StaEDITestEvent) { StaEDITestEvent other = (StaEDITestEvent) obj; return event == other.event && error == other.error && Objects.equals(text, other.text) && Objects.equals(referenceCode, other.referenceCode) && Objects.equals(location, other.location); } return false; } @Override public String toString() { StringBuilder buffer = new StringBuilder("StaEDITestEvent"); buffer.append('('); buffer.append("event=").append(event); buffer.append(", ").append("error=").append(error); buffer.append(", ").append("referenceCode=").append(referenceCode); buffer.append(", ").append("text=").append(text); buffer.append(", ").append("location=").append(location); return buffer.append(')').append('\n').toString(); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/test/StaEDITestUtil.java
src/test/java/io/xlate/edi/test/StaEDITestUtil.java
package io.xlate.edi.test; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamFilter; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.EDIStreamWriter; public class StaEDITestUtil { /** * Write a full segment to the output writer. Elements in the elements * parameter are written as simple elements or composite elements when they * are an array. * * @param writer * @param segmentTag * @param elements * @throws EDIStreamException */ public static void write(EDIStreamWriter writer, String segmentTag, Object... elements) throws EDIStreamException { writer.writeStartSegment(segmentTag); for (Object e : elements) { if (e instanceof String) { writer.writeElement((String) e); } else if (e instanceof String[]) { writer.writeStartElement(); for (String c : (String[]) e) { writer.writeComponent(c); } writer.endElement(); } } writer.writeEndSegment(); } public static EDIStreamReader filterEvents(EDIInputFactory factory, EDIStreamReader reader, EDIStreamEvent... events) { final Set<EDIStreamEvent> filteredEvents = new HashSet<>(Arrays.asList(events)); final EDIStreamFilter filter = new EDIStreamFilter() { @Override public boolean accept(EDIStreamReader reader) { return filteredEvents.contains(reader.getEventType()); } }; return factory.createFilteredReader(reader, filter); } public static void assertEvent(EDIStreamReader reader, EDIStreamEvent event) throws EDIStreamException { assertEquals(event, reader.next()); } public static void assertEvent(EDIStreamReader reader, EDIStreamEvent event, String referenceCode) throws EDIStreamException { assertEvent(reader, event, null, referenceCode); } public static void assertEvent(EDIStreamReader reader, EDIStreamEvent event, EDIStreamValidationError error, String referenceCode) throws EDIStreamException { assertEquals(event, reader.next()); if (error != null) { assertEquals(error, reader.getErrorType(), () -> "Unexpected error type for code: " + reader.getReferenceCode()); } assertEquals(referenceCode, reader.getReferenceCode()); } public static void assertEvent(EDIStreamReader reader, EDIStreamEvent event, EDIStreamValidationError error, String text, String referenceCode) throws EDIStreamException { assertEquals(event, reader.next()); if (error != null) { assertEquals(error, reader.getErrorType(), () -> "Unexpected error type for code: " + reader.getReferenceCode()); } assertEquals(text, reader.getText()); assertEquals(referenceCode, reader.getReferenceCode()); } public static void assertLocation(EDIStreamReader reader, int segPos, int elePos, int eleOcc, int cmpPos) throws EDIStreamException { assertEquals(segPos, reader.getLocation().getSegmentPosition()); assertEquals(elePos, reader.getLocation().getElementPosition()); assertEquals(eleOcc, reader.getLocation().getElementOccurrence()); assertEquals(cmpPos, reader.getLocation().getComponentPosition()); } public static void assertTextLocation(EDIStreamReader reader, String text, int segPos, int elePos, int eleOcc, int cmpPos) throws EDIStreamException { assertEquals(text, reader.getText()); assertEquals(segPos, reader.getLocation().getSegmentPosition()); assertEquals(elePos, reader.getLocation().getElementPosition()); assertEquals(eleOcc, reader.getLocation().getElementOccurrence()); assertEquals(cmpPos, reader.getLocation().getComponentPosition()); } public static String[] getJavaVersion() { String versionString = System.getProperty("java.version"); return versionString.split("[\\._]"); } public static String toString(EDIStreamReader reader) { StringBuilder buffer = new StringBuilder(reader.getClass().getName()); buffer.append('('); EDIStreamEvent event = reader.getEventType(); buffer.append("event=").append(event); switch (event) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: buffer.append(", ").append("error=").append(reader.getErrorType()); buffer.append(", ").append("referenceCode=").append(reader.getReferenceCode()); break; case ELEMENT_DATA: buffer.append(", ").append("text=").append(reader.getText()); break; default: break; } buffer.append(", ").append("location=").append(reader.getLocation()); return buffer.append(')').toString(); } public static void printTransaction(String resourcePath, String schemaPath) throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); // Any InputStream can be used to create an `EDIStreamReader` try (InputStream stream = StaEDITestUtil.class.getResourceAsStream(resourcePath); EDIStreamReader reader = factory.createEDIStreamReader(stream)) { EDIStreamEvent event; boolean transactionBeginSegment = false; String comp = null; int depth = 0; StringBuilder buffer = new StringBuilder(); while (reader.hasNext()) { event = reader.next(); switch (event) { case START_INTERCHANGE: System.out.println(repeat(' ', depth) + "<Interchange>"); depth++; break; case END_INTERCHANGE: depth--; System.out.println(repeat(' ', depth) + "</Interchange>"); break; case START_GROUP: System.out.println(repeat(' ', depth) + "<FunctionalGroup>"); depth++; break; case END_GROUP: depth--; System.out.println(repeat(' ', depth) + "</FunctionalGroup>"); break; case START_TRANSACTION: transactionBeginSegment = true; System.out.println(repeat(' ', depth) + "<TransactionSet>"); depth++; break; case END_TRANSACTION: depth--; System.out.println(repeat(' ', depth) + "</TransactionSet>"); break; case START_LOOP: System.out.println(repeat(' ', depth) + "<" + reader.getReferenceCode() + ">"); depth++; break; case END_LOOP: depth--; System.out.println(repeat(' ', depth) + "</" + reader.getReferenceCode() + ">"); break; case START_SEGMENT: buffer.setLength(0); buffer.append(repeat(' ', depth)); buffer.append("<Segment-"); buffer.append(reader.getText()); if (reader.getReferenceCode() != null) { buffer.append(" code='"); buffer.append(reader.getReferenceCode()); buffer.append("'"); } buffer.append(">"); System.out.println(buffer.toString()); depth++; break; case END_SEGMENT: if (transactionBeginSegment) { SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaUrl = StaEDITestUtil.class.getResource(schemaPath); //schemaFactory.setProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, schemaUrl); Schema schema = schemaFactory.createSchema(schemaUrl); reader.setTransactionSchema(schema); } transactionBeginSegment = false; depth--; System.out.println(repeat(' ', depth) + "</Segment-" + reader.getText() + ">"); break; case START_COMPOSITE: System.out.println(repeat(' ', depth) + "<" + reader.getReferenceCode() + ">"); comp = reader.getReferenceCode(); depth++; break; case END_COMPOSITE: depth--; System.out.println(repeat(' ', depth) + "</" + comp + ">"); comp = null; break; case ELEMENT_DATA: String name = reader.getReferenceCode(); if (name != null && !name.contains("Element")) { name = "Element-" + name; } if (null != reader.getText() && !"".equals(reader.getText())) { System.out.println(repeat(' ', depth) + "<" + name + ">" + reader.getText() + "</" + name + ">"); if ("null".equals(reader.getReferenceCode())) { System.out.println(repeat(' ', depth) + "<" + name + ">" + reader.getText() + "</" + name + ">"); } } break; case SEGMENT_ERROR: // Handle a segment error EDIStreamValidationError segmentErrorType = reader.getErrorType(); System.out.println( "*" + repeat(' ', depth) + "** Segment error: " + segmentErrorType.name() + " " + reader.getLocation()); break; case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: // Handle a segment error EDIStreamValidationError elementErrorType = reader.getErrorType(); System.out.println( "*" + repeat(' ', depth) + "** Element error:" + elementErrorType.name() + ", " + reader.getReferenceCode()); break; default: break; } } } } static String repeat(char value, int times) { StringBuilder buffer = new StringBuilder(times); for (int i = 0; i < times; i++) { buffer.append(" "); } return buffer.toString(); } public static void assertEqualsNormalizeLineSeparators(String expected, String actual) { assertEquals(normalizeLines(expected), normalizeLines(actual)); } public static String normalizeLines(String input) { return input != null ? input.replaceAll("(?:\\r\\n|\\r)", "\n") : null; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/test/StaEDIReaderTestBase.java
src/test/java/io/xlate/edi/test/StaEDIReaderTestBase.java
package io.xlate.edi.test; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamReader; public class StaEDIReaderTestBase { protected Map<String, Object> ediReaderConfig; protected EDIInputFactory ediInputFactory; protected EDIStreamReader ediReader; @BeforeEach void setupFactory() throws Exception { ediReaderConfig = new HashMap<>(); ediInputFactory = EDIInputFactory.newFactory(); } protected void setupReader(InputStream ediStream, String schemaResource) throws Exception { ediReaderConfig.forEach(ediInputFactory::setProperty); ediReader = ediInputFactory.createEDIStreamReader(ediStream); if (schemaResource != null) { SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema transactionSchema = schemaFactory.createSchema(getClass().getResource(schemaResource)); ediReader = ediInputFactory.createFilteredReader(ediReader, (reader) -> { if (reader.getEventType() == EDIStreamEvent.START_TRANSACTION) { reader.setTransactionSchema(transactionSchema); } return true; }); } } protected void setupReader(String ediResource, String schemaResource) throws Exception { setupReader(getClass().getResourceAsStream(ediResource), schemaResource); } protected void setupReader(byte[] ediResource, String schemaResource) throws Exception { setupReader(new ByteArrayInputStream(ediResource), schemaResource); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIFilteredStreamReaderTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIFilteredStreamReaderTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.NoSuchElementException; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.Location; @SuppressWarnings("resource") class StaEDIFilteredStreamReaderTest implements ConstantsTest { @Test /** * Filter all except repeat > 1 of an element or component elements where * the position within the composite > 1. * * @throws EDIStreamException */ void testNext() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi"); EDIStreamReader reader = factory.createFilteredReader(factory.createEDIStreamReader(stream), r -> { if (r.getEventType() != EDIStreamEvent.ELEMENT_DATA) { return false; } Location location = r.getLocation(); return location.getComponentPosition() > 1 || location.getElementOccurrence() > 1; }); EDIStreamEvent event; int matches = 0; while (reader.hasNext()) { /* * Additional call to `hasNext` has not effect on the subsequent call to `next` * or the processing of the stream. */ assertTrue(reader.hasNext()); event = reader.next(); if (event != EDIStreamEvent.ELEMENT_DATA) { fail("Unexpected event: " + event); } String text = reader.getText(); assertTrue(text.matches(".*(R[2-9]|COMP[2-9]).*"), "Not matched: " + text); matches++; } assertEquals(9, matches); } @Test /** * Only allow segment tags containing S, G, or 5 to pass the filter. * * @throws EDIStreamException */ void testNextTag() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createFilteredReader(factory.createEDIStreamReader(stream), r -> { if (r.getEventType() != EDIStreamEvent.START_SEGMENT) { return false; } String tag = r.getText(); return tag.matches("^.{0,2}[SG5].{0,2}$"); }); EDIStreamEvent event; int matches = 0; String tag = null; while (reader.hasNext()) { try { event = reader.nextTag(); } catch (@SuppressWarnings("unused") NoSuchElementException e) { break; } if (event != EDIStreamEvent.START_SEGMENT) { fail("Unexpected event: " + event); } tag = reader.getText(); assertTrue( tag.indexOf('S') > -1 || tag.indexOf('G') > -1 || tag.indexOf('5') > -1); matches++; } assertEquals("GE", tag, "Unexpected last segment"); assertEquals(6, matches); } @Test /** * Filter all except single character element events * * @throws EDIStreamException */ void testHasNext() throws EDIStreamException, IOException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi"); EDIStreamReader reader = factory.createFilteredReader(factory.createEDIStreamReader(stream), r -> { if (r.getEventType() != EDIStreamEvent.ELEMENT_DATA) { return false; } return r.getTextLength() == 1; }); EDIStreamEvent event; int matches = 0; while (reader.hasNext()) { event = reader.next(); if (event != EDIStreamEvent.ELEMENT_DATA) { fail("Unexpected event: " + event); } String text = reader.getText(); assertEquals(1, text.length(), "Wrong length: " + text); matches++; } reader.close(); assertEquals(16, matches); } @Test /** * Test that the filtered and unfiltered readers return the same information * at each event of the filtered reader. * * @throws EDIStreamException */ void testNextTagFilterParityWithUnfiltered() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); final String PROP = EDIInputFactory.EDI_VALIDATE_CONTROL_STRUCTURE; factory.setProperty(PROP, Boolean.TRUE); EDIStreamReader unfiltered = factory.createEDIStreamReader(stream); EDIStreamReader filtered = factory.createFilteredReader(unfiltered, r -> { switch (r.getEventType()) { case START_INTERCHANGE: case START_TRANSACTION: return true; case START_SEGMENT: String tag = r.getText(); return tag.matches("^.{0,2}[SG5].{0,2}$"); default: break; } return false; }); SchemaFactory schemaFactory = SchemaFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> unfiltered.getProperty(null)); assertThrows(IllegalArgumentException.class, () -> filtered.getProperty(null)); assertEquals(unfiltered.getProperty(PROP), filtered.getProperty(PROP)); filtered.next(); // START_INTERCHANGE assertEquals(filtered.getStandard(), unfiltered.getStandard()); assertArrayEquals(filtered.getVersion(), unfiltered.getVersion()); assertEquals(unfiltered.getDelimiters(), filtered.getDelimiters()); assertNull(filtered.getControlSchema()); assertNull(filtered.getTransactionSchema()); Schema control = schemaFactory.getControlSchema(filtered.getStandard(), filtered.getVersion()); filtered.setControlSchema(control); assertEquals(control, filtered.getControlSchema()); assertEquals(control, unfiltered.getControlSchema()); IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> filtered.setControlSchema(control)); assertEquals("control schema already set", thrown.getMessage()); filtered.nextTag(); // ISA thrown = assertThrows(IllegalStateException.class, () -> filtered.setControlSchema(control)); assertEquals("control schema set after interchange start", thrown.getMessage()); assertStatusEquals(unfiltered, filtered); filtered.nextTag(); // GS assertStatusEquals(unfiltered, filtered); filtered.next(); // START_TRANSACTION Schema transaction = schemaFactory.createSchema(getClass().getResourceAsStream("/x12/EDISchema997.xml")); filtered.setTransactionSchema(transaction); assertEquals(transaction, filtered.getTransactionSchema()); assertEquals(transaction, unfiltered.getTransactionSchema()); filtered.nextTag(); // ST assertStatusEquals(unfiltered, filtered); filtered.nextTag(); // AK5 assertStatusEquals(unfiltered, filtered); filtered.nextTag(); // SE assertStatusEquals(unfiltered, filtered); filtered.nextTag(); // GE assertStatusEquals(unfiltered, filtered); } void assertStatusEquals(EDIStreamReader unfiltered, EDIStreamReader filtered) { assertEquals(unfiltered.getEventType(), filtered.getEventType()); assertEquals(unfiltered.getText(), filtered.getText()); assertEquals(unfiltered.getReferenceCode(), filtered.getReferenceCode()); assertArrayEquals(unfiltered.getTextCharacters(), filtered.getTextCharacters()); assertEquals(unfiltered.getTextStart(), filtered.getTextStart()); assertEquals(unfiltered.getTextLength(), filtered.getTextLength()); char[] uf_target = new char[100]; Arrays.fill(uf_target, '\0'); char[] f_target = new char[100]; Arrays.fill(f_target, '\0'); unfiltered.getTextCharacters(unfiltered.getTextStart(), uf_target, 0, unfiltered.getTextLength()); filtered.getTextCharacters(filtered.getTextStart(), f_target, 0, filtered.getTextLength()); assertArrayEquals(uf_target, f_target); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/SegmentValidationTest.java
src/test/java/io/xlate/edi/internal/stream/SegmentValidationTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static io.xlate.edi.test.StaEDITestUtil.assertEvent; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import io.xlate.edi.internal.schema.SchemaUtils; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIOutputErrorReporter; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamConstants.Standards; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamFilter; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.EDIStreamWriter; import io.xlate.edi.stream.Location; import io.xlate.edi.test.StaEDITestEvent; import io.xlate.edi.test.StaEDITestUtil; @SuppressWarnings("resource") class SegmentValidationTest { EDIStreamFilter segmentErrorFilter = new EDIStreamFilter() { @Override public boolean accept(EDIStreamReader reader) { switch (reader.getEventType()) { case START_TRANSACTION: case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: return true; default: return false; } } }; @Test void testValidSequenceXml() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* .. *00* .. *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S12*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testValidSequenceEdifact() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:1+005435656:1+006415160:1+060515:1434+00000000000778'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNT+23+00000000000117'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); assertArrayEquals(new String[] { "UNOA", "1" }, reader.getVersion()); Schema schema = SchemaUtils.getControlSchema(Standards.EDIFACT, reader.getVersion()); reader.setControlSchema(schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); assertTrue(!reader.hasNext(), "Segment errors exist"); } @Test void testMissingMandatoryXml() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S13*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, reader.getErrorType()); assertEquals("S12", reader.getText()); reader.next(); assertEquals(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, reader.getErrorType()); assertEquals("S19", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testMissingMandatoryEdifact() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:1+005435656:1+006415160:1+060515:1434+00000000000778'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); assertArrayEquals(new String[] { "UNOA", "1" }, reader.getVersion()); Schema schema = SchemaUtils.getControlSchema(Standards.EDIFACT, reader.getVersion()); reader.setControlSchema(schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, reader.getErrorType()); assertEquals("UNT", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testUnexpected() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S12*X~" + "S21*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.UNEXPECTED_SEGMENT, reader.getErrorType()); assertEquals("S21", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testImproperSequence() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S12*X~" + "S14*X~" + "S13*X~" + "S13*X~" + "S14*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_NOT_IN_PROPER_SEQUENCE, reader.getErrorType()); assertEquals("S13", reader.getText()); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_NOT_IN_PROPER_SEQUENCE, reader.getErrorType()); assertEquals("S13", reader.getText()); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_EXCEEDS_MAXIMUM_USE, reader.getErrorType()); assertEquals("S13", reader.getText()); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_EXCEEDS_MAXIMUM_USE, reader.getErrorType()); assertEquals("S14", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testSegmentNotDefined() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S12*X~" + "S0B*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_NOT_IN_DEFINED_TRANSACTION_SET, reader.getErrorType()); assertEquals("S0B", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testLoopMultiOccurrenceSingleSegment() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S0A*X~" + "S11*X~" + "S12*X~" + "S19*X~" + "S20*X~" + "S20*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, new EDIStreamFilter() { @Override public boolean accept(EDIStreamReader reader) { switch (reader.getEventType()) { case START_TRANSACTION: case SEGMENT_ERROR: case START_LOOP: case END_LOOP: return true; default: return false; } } }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertEquals(EDIStreamEvent.START_LOOP, reader.next()); assertEquals("L0000", reader.getReferenceCode()); assertEquals(EDIStreamEvent.END_LOOP, reader.next()); assertEquals("L0000", reader.getReferenceCode()); for (int i = 0; i < 2; i++) { assertEquals(EDIStreamEvent.START_LOOP, reader.next()); assertEquals("L0001", reader.getReferenceCode()); assertEquals(EDIStreamEvent.END_LOOP, reader.next()); assertEquals("L0001", reader.getReferenceCode()); } assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testLoopOccurrence() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S12*X~" + "S19*X~" + "S11*X~" + "S12*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.LOOP_OCCURS_OVER_MAXIMUM_TIMES, reader.getErrorType()); assertEquals("S11", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testOptionalLoopNotUsed() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testRequiredLoopNotUsed() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, segmentErrorFilter); assertTrue(reader.hasNext(), "Segment errors do not exist"); reader.next(); assertEquals(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, reader.getErrorType()); assertEquals("S01", reader.getText()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testImplementationValidSequence() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S0A*X~" + "S11*A~" + "S12*X~" // IMPLEMENTATION_UNUSED_SEGMENT_PRESENT // IMPLEMENTATION_SEGMENT_BELOW_MINIMUM_USE (missing S13) + "S11*B~" + "S12*X~" + "S12*X~" + "S12*X~" // SEGMENT_EXCEEDS_MAXIMUM_USE + "S11*B~" + "S11*B~" // LOOP_OCCURS_OVER_MAXIMUM_TIMES + "S11*C~" // IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES + "S11*D~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader unfiltered = factory.createEDIStreamReader(stream, schema); EDIStreamReader reader = StaEDITestUtil.filterEvents( factory, unfiltered, EDIStreamEvent.START_TRANSACTION, EDIStreamEvent.SEGMENT_ERROR, EDIStreamEvent.START_LOOP, EDIStreamEvent.END_LOOP); assertEvent(reader, EDIStreamEvent.START_TRANSACTION); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationImpl.xml"))); // Loop A assertEvent(reader, EDIStreamEvent.START_LOOP, "0000A"); assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.IMPLEMENTATION_UNUSED_SEGMENT_PRESENT, "S12"); assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.IMPLEMENTATION_SEGMENT_BELOW_MINIMUM_USE, "S13"); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000A"); // Loop B - Occurrence 1 assertEvent(reader, EDIStreamEvent.START_LOOP, "0000B"); assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.SEGMENT_EXCEEDS_MAXIMUM_USE, "S12"); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000B"); // Loop B - Occurrence 2 assertEvent(reader, EDIStreamEvent.START_LOOP, "0000B"); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000B"); // Loop B - Occurrence 3 assertEvent(reader, EDIStreamEvent.START_LOOP, "0000B"); assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.LOOP_OCCURS_OVER_MAXIMUM_TIMES, "S11", "0000B"); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000B"); // Loop C - Occurrence 1 assertEvent(reader, EDIStreamEvent.START_LOOP, "0000C"); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000C"); // Loop D - Occurrence 1 assertEvent(reader, EDIStreamEvent.START_LOOP, "0000D"); // Standard Loop L0000 may only occur 5 times assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.LOOP_OCCURS_OVER_MAXIMUM_TIMES, "S11", "L0000"); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000D"); assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, "0000C"); // Loop L0001 has minOccurs=1 in standard (not used in implementation, invalid configuration) assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, "S20"); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @SuppressWarnings("deprecation") @Test void testImplementationValidAlternateSequence() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setProperty(EDIInputFactory.EDI_ENABLE_LOOP_TEXT, "false"); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S0A*X~" + "S11*A~" + "S13*X~" + "S11*C~" + "S11*B~" + "S12*X~" + "S12*X~" + "S11*D~" + "S11*C~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader unfiltered = factory.createEDIStreamReader(stream, schema); EDIStreamReader reader = StaEDITestUtil.filterEvents( factory, unfiltered, EDIStreamEvent.START_TRANSACTION, EDIStreamEvent.SEGMENT_ERROR, EDIStreamEvent.START_LOOP, EDIStreamEvent.END_LOOP); assertEvent(reader, EDIStreamEvent.START_TRANSACTION); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationImpl.xml"))); List<StaEDITestEvent> expected = Arrays.asList( StaEDITestEvent.forEvent(EDIStreamEvent.START_TRANSACTION, null, "TRANSACTION"), // Loop A StaEDITestEvent.forEvent(EDIStreamEvent.START_LOOP, null, "0000A"), StaEDITestEvent.forEvent(EDIStreamEvent.END_LOOP, null, "0000A"), // Loop C - Occurrence 1 StaEDITestEvent.forEvent(EDIStreamEvent.START_LOOP, null, "0000C"), StaEDITestEvent.forEvent(EDIStreamEvent.END_LOOP, null, "0000C"), // Loop B StaEDITestEvent.forEvent(EDIStreamEvent.START_LOOP, null, "0000B"), StaEDITestEvent.forEvent(EDIStreamEvent.END_LOOP, null, "0000B"), // Loop D StaEDITestEvent.forEvent(EDIStreamEvent.START_LOOP, null, "0000D"), StaEDITestEvent.forEvent(EDIStreamEvent.END_LOOP, null, "0000D"), // Loop C - Occurrence 2 StaEDITestEvent.forEvent(EDIStreamEvent.START_LOOP, null, "0000C"), StaEDITestEvent.forEvent(EDIStreamEvent.END_LOOP, null, "0000C"), StaEDITestEvent.forError(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, "S20", "S20")); List<StaEDITestEvent> events = new ArrayList<>(); events.add(StaEDITestEvent.from(reader, false)); while (reader.hasNext()) { reader.next(); events.add(StaEDITestEvent.from(reader, false)); } assertEquals(expected, events); } @Test void testImplementationValidSequenceAllMissingReader() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = StaEDITestUtil.filterEvents( factory, reader, EDIStreamEvent.START_TRANSACTION, EDIStreamEvent.SEGMENT_ERROR, EDIStreamEvent.START_LOOP, EDIStreamEvent.END_LOOP); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationImpl.xml"))); assertEquals(EDIStreamEvent.SEGMENT_ERROR, reader.next()); assertEquals(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, reader.getErrorType()); assertEquals("0000A", reader.getReferenceCode()); assertEquals(EDIStreamEvent.SEGMENT_ERROR, reader.next()); assertEquals(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, reader.getErrorType()); assertEquals("0000B", reader.getReferenceCode()); assertEquals(EDIStreamEvent.SEGMENT_ERROR, reader.next()); assertEquals(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, reader.getErrorType()); assertEquals("0000C", reader.getReferenceCode()); assertEquals(EDIStreamEvent.SEGMENT_ERROR, reader.next()); assertEquals(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, reader.getErrorType()); assertEquals("0000D", reader.getReferenceCode()); // Loop L0001 has minOccurs=1 in standard (not used in implementation, invalid configuration) assertEquals(EDIStreamEvent.SEGMENT_ERROR, reader.next()); assertEquals(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, reader.getErrorType()); assertEquals("S20", reader.getReferenceCode()); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } @Test void testImplementationValidSequenceAllMissingWriter() throws EDISchemaException, EDIStreamException { SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema ctlSchema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidation.xml")); Schema txnSchema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationImpl.xml")); List<StaEDITestEvent> errorEvents = new ArrayList<>(); EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIOutputFactory.FORMAT_ELEMENTS, true); factory.setErrorReporter(new EDIOutputErrorReporter() { @Override public void report(EDIStreamValidationError errorType, EDIStreamWriter writer, Location location, CharSequence data, EDIReference typeReference) { EDIType type = typeReference instanceof EDIType ? EDIType.class.cast(typeReference) : typeReference.getReferencedType(); errorEvents.add(StaEDITestEvent.forError(errorType, data.toString(), type.getCode())); } }); EDIStreamWriter writer = factory.createEDIStreamWriter(new ByteArrayOutputStream()); writer.setControlSchema(ctlSchema); writer.setTransactionSchema(txnSchema); writer.startInterchange(); writer.writeStartSegment("ISA") .writeElement("00") .writeElement(" ") .writeElement("00") .writeElement(" ") .writeElement("ZZ") .writeElement("ReceiverID") .writeElement("ZZ") .writeElement("Sender") .writeElement("203001") .writeElement("1430") .writeElement("^") .writeElement("00501") .writeElement("000000001") .writeElement("0") .writeElement("P") .writeElement(":") .writeEndSegment(); writer.writeStartSegment("S01") .writeElement("X") .writeEndSegment(); writer.writeStartSegment("S09") .writeElement("X") .writeEndSegment(); writer.writeStartSegment("IEA") .writeElement("1") .writeElement("000000001") .writeEndSegment(); List<StaEDITestEvent> expected = Arrays.asList( StaEDITestEvent.forError(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, "L0000", "0000A"), StaEDITestEvent.forError(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, "L0000", "0000B"), StaEDITestEvent.forError(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, "L0000", "0000C"), StaEDITestEvent.forError(EDIStreamValidationError.IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES, "L0000", "0000D"), StaEDITestEvent.forError(EDIStreamValidationError.MANDATORY_SEGMENT_MISSING, "S20", "S20") ); assertEquals(expected, errorEvents); } @Test void testImplementationLoopsSelectedByWriter() throws EDISchemaException, EDIStreamException { SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema ctlSchema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidation.xml")); Schema txnSchema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationImpl.xml")); List<StaEDITestEvent> errorEvents = new ArrayList<>(); EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIOutputFactory.FORMAT_ELEMENTS, true); factory.setErrorReporter(new EDIOutputErrorReporter() { @Override public void report(EDIStreamValidationError errorType, EDIStreamWriter writer, Location location, CharSequence data, EDIReference typeReference) {
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/CharArraySequenceTest.java
src/test/java/io/xlate/edi/internal/stream/CharArraySequenceTest.java
package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.*; import java.nio.CharBuffer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class CharArraySequenceTest { CharArraySequence target; @BeforeEach void setUp() { target = new CharArraySequence(); } @Test void testClear() { char[] text = "ANYVALUEEXCEPTTHIS".toCharArray(); int start = 3; int length = 5; target.set(text, start, length); assertEquals(5, target.length()); assertEquals("VALUE", target.toString()); target.clear(); assertEquals("", target.toString()); } @Test void testPutToBuffer() { char[] text = "ANYVALUEEXCEPTTHIS".toCharArray(); int start = 3; int length = 5; target.set(text, start, length); CharBuffer buffer = CharBuffer.allocate(20); target.putToBuffer(buffer); buffer.flip(); assertEquals("VALUE", buffer.toString()); } @Test void testCharAt() { char[] text = "ANYVALUEEXCEPTTHIS".toCharArray(); int start = 3; int length = 5; target.set(text, start, length); assertThrows(StringIndexOutOfBoundsException.class, () -> target.charAt(-1)); assertEquals('V', target.charAt(0)); assertEquals('E', target.charAt(4)); assertThrows(StringIndexOutOfBoundsException.class, () -> target.charAt(5)); } @Test void testSubSequence() { char[] text = "ANYVALUEEXCEPTTHIS".toCharArray(); int start = 3; int length = 5; target.set(text, start, length); assertThrows(IndexOutOfBoundsException.class, () -> target.subSequence(-10, 3)); assertEquals("VALUE", target.subSequence(0, 5).toString()); assertEquals("VAL", target.subSequence(0, 3).toString()); assertEquals("ALUE", target.subSequence(1, 5).toString()); assertThrows(IndexOutOfBoundsException.class, () -> target.subSequence(0, 10)); assertThrows(IndexOutOfBoundsException.class, () -> target.subSequence(6, 5)); } @Test void testCompareTo() { char[] text = "ANYVALUEEXCEPTTHIS".toCharArray(); int start = 3; int length = 5; target.set(text, start, length); assertEquals(0, target.compareTo("VALUE")); assertTrue(target.compareTo("VALUE1") < 0); assertTrue(target.compareTo("A") > 0); assertTrue(target.compareTo("Z") < 0); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIStreamReaderSyntaxTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIStreamReaderSyntaxTest.java
package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.Location; @SuppressWarnings("unchecked") class StaEDIStreamReaderSyntaxTest { Object[] readInterchange(String data, String schemaPath) throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(data.getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); List<Location> errorLocations = new ArrayList<>(); while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.createSchema(getClass().getResource(schemaPath)); reader.setTransactionSchema(schema); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); errorLocations.add(reader.getLocation().copy()); break; default: break; } } return new Object[] { errors, errorLocations }; } @ParameterizedTest @ValueSource( strings = { "" // None Present + "UNB+UNOA:3+SENDER+RECEIVER+200906:1148+1'" + "UNH+1+INVOIC:D:93A:UN'" + "UXA+++'" + "UNT+3+1'" + "UNZ+1+1'", "" // First Only Present + "UNB+UNOA:3+SENDER+RECEIVER+200906:1148+1'" + "UNH+1+INVOIC:D:93A:UN'" + "UXA+FIRST++'" + "UNT+3+1'" + "UNZ+1+1'", "" // First And Second Present + "UNB+UNOA:3+SENDER+RECEIVER+200906:1148+1'" + "UNH+1+INVOIC:D:93A:UN'" + "UXA+FIRST+SECOND+'" + "UNT+3+1'" + "UNZ+1+1'", "" // Second And Third Present + "UNB+UNOA:3+SENDER+RECEIVER+200906:1148+1'" + "UNH+1+INVOIC:D:93A:UN'" + "UXA++SECOND+THIRD'" + "UNT+3+1'" + "UNZ+1+1'" }) void testFirstSyntaxValidation_Valid(String interchange) throws Exception { Object[] result = readInterchange(interchange, "/EDIFACT/fragment-first-syntax-validation.xml"); List<EDIStreamValidationError> errors = (List<EDIStreamValidationError>) result[0]; assertEquals(0, errors.size(), () -> "Unexpected errors: " + errors); } @Test void testFirstSyntaxValidation_FirstAndThirdPresent() throws Exception { Object[] result = readInterchange("" + "UNB+UNOA:3+SENDER+RECEIVER+200906:1148+1'" + "UNH+1+INVOIC:D:93A:UN'" + "UXA+FIRST++THIRD'" + "UNT+3+1'" + "UNZ+1+1'", "/EDIFACT/fragment-first-syntax-validation.xml"); List<EDIStreamValidationError> errors = (List<EDIStreamValidationError>) result[0]; List<Location> errorLocations = (List<Location>) result[1]; assertEquals(1, errors.size(), () -> "Unexpected errors: " + errors); assertEquals(EDIStreamValidationError.EXCLUSION_CONDITION_VIOLATED, errors.get(0)); assertEquals("UXA", errorLocations.get(0).getSegmentTag()); assertEquals(3, errorLocations.get(0).getElementPosition()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/ErrorEventsTest.java
src/test/java/io/xlate/edi/internal/stream/ErrorEventsTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.schema.SchemaUtils; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamFilter; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; @SuppressWarnings("resource") class ErrorEventsTest { EDIStreamFilter errorFilter = new EDIStreamFilter() { @Override public boolean accept(EDIStreamReader reader) { switch (reader.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: return true; default: break; } return false; } }; @Test void testInvalidElements1() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema control = SchemaUtils.getControlSchema("X12", new String[] { "00501" }); Schema transaction = schemaFactory.createSchema(getClass().getResourceAsStream("/x12/EDISchema997.xml")); EDIStreamReader reader = factory.createEDIStreamReader(stream, control); prescan: while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: reader.setTransactionSchema(transaction); break prescan; default: break; } } reader = factory.createFilteredReader(reader, errorFilter); assertNextEvent(reader, EDIStreamValidationError.INVALID_CHARACTER_DATA, "AK3", 6, 2, 1, -1, "AK302-R1"); assertNextEvent(reader, EDIStreamValidationError.TOO_MANY_REPETITIONS, "AK3", 6, 2, 2, -1, "AK302-R2"); assertNextEvent(reader, EDIStreamValidationError.INVALID_CHARACTER_DATA, "AK3", 6, 2, 2, -1, "AK302-R2"); assertNextEvent(reader, EDIStreamValidationError.TOO_MANY_REPETITIONS, "AK3", 6, 2, 3, -1, ""); assertNextEvent(reader, EDIStreamValidationError.TOO_MANY_COMPONENTS, "AK3", 6, 2, 3, 1, "AK302-R3-COMP1"); assertNextEvent(reader, EDIStreamValidationError.TOO_MANY_COMPONENTS, "AK3", 6, 2, 3, 2, "AK302-R3-COMP2"); assertNextEvent(reader, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, "AK3", 6, 4, 1, -1, "AK304-R1"); assertNextEvent(reader, EDIStreamValidationError.INVALID_CODE_VALUE, "AK3", 6, 4, 1, -1, "AK304-R1"); assertNextEvent(reader, EDIStreamValidationError.TOO_MANY_REPETITIONS, "AK3", 6, 4, 2, -1, "AK304-R2"); assertNextEvent(reader, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, "AK3", 6, 4, 2, -1, "AK304-R2"); assertNextEvent(reader, EDIStreamValidationError.INVALID_CODE_VALUE, "AK3", 6, 4, 2, -1, "AK304-R2"); assertNextEvent(reader, EDIStreamValidationError.TOO_MANY_REPETITIONS, "AK3", 6, 4, 3, -1, "AK304-R3"); assertNextEvent(reader, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, "AK3", 6, 4, 3, -1, "AK304-R3"); assertNextEvent(reader, EDIStreamValidationError.INVALID_CODE_VALUE, "AK3", 6, 4, 3, -1, "AK304-R3"); } @Test void testListSyntaxValid() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG+INVOIC+15623+23457+20060515:1433+CD1352+UN+D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, errorFilter); assertFalse(reader.hasNext(), "Unexpected errors"); } @Test void testListSyntaxMissingFirst() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG++15623+23457+20060515:1433+CD1352+UN+D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING, reader.getErrorType()); assertEquals(2, reader.getLocation().getSegmentPosition()); assertEquals(1, reader.getLocation().getElementPosition()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testListSyntaxMissingSecond() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG+INVOIC+15623+23457+20060515:1433+CD1352++D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING, reader.getErrorType()); assertEquals(2, reader.getLocation().getSegmentPosition()); assertEquals(6, reader.getLocation().getElementPosition()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testTooManyOccurrencesComposite() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG+INVOIC+15623+23457+20060515:1433+CD1352+UN+D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN+FIRST OK*TOO MANY REPETITIONS'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.TOO_MANY_REPETITIONS, reader.getErrorType()); assertEquals(3, reader.getLocation().getSegmentPosition()); assertEquals(3, reader.getLocation().getElementPosition()); assertEquals(2, reader.getLocation().getElementOccurrence()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testTooManyElementsComposite() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG+INVOIC+15623+23457+20060515:1433+CD1352+UN+D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN++++++MY:EXTRA:COMPOSITE'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, reader.getErrorType()); assertEquals(3, reader.getLocation().getSegmentPosition()); assertEquals(8, reader.getLocation().getElementPosition()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testTooManySimpleElements() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG+INVOIC+15623+23457+20060515:1433+CD1352+UN+D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN++++++MY_EXTRA_SIMPLE_ELEMENT'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, reader.getErrorType()); assertEquals(3, reader.getLocation().getSegmentPosition()); assertEquals(8, reader.getLocation().getElementPosition()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testEDIFACT_BothGroupAndTransactionUsed() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000778'" + "UNG+INVOIC+15623+23457+20060515:1433+CD1352+UN+D:97B+A3P52'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNT+2+00000000000117'" + "UNE+1+CD1352'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UNT+2+00000000000117'" + "UNZ+1+00000000000778'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader.next(); // Advance to interchange start reader.setControlSchema(SchemaFactory.newFactory().createSchema(getClass().getResource("/EDIFACT/v4r02-bogus-syntax-position.xml"))); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_EXCLUSION_CONDITION_VIOLATED, reader.getErrorType()); assertEquals("UNH", reader.getReferenceCode()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testEDIFACT_NeitherGroupNorTransactionUsed() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000001'" + "UNZ+0+00000000000001'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader.next(); // Advance to interchange start reader.setControlSchema(SchemaFactory.newFactory().createSchema(getClass().getResource("/EDIFACT/v4r02-bogus-syntax-position.xml"))); reader = factory.createFilteredReader(reader, errorFilter); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.CONDITIONAL_REQUIRED_SEGMENT_MISSING, reader.getErrorType()); assertEquals("UNG", reader.getReferenceCode()); reader.next(); assertEquals(EDIStreamValidationError.CONDITIONAL_REQUIRED_SEGMENT_MISSING, reader.getErrorType()); assertEquals("UNH", reader.getReferenceCode()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testEDIFACT_SegmentExclusionSyntax() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:4:::02+005435656:1+006415160:1+20060515:1434+00000000000001'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "UXA+1'" + "UXC+1'" + "UNT+4+00000000000117'" + "UNZ+0001+00000000000001'").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (rdr) -> { switch (rdr.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: return true; case START_TRANSACTION: try { rdr.setTransactionSchema(SchemaFactory.newFactory().createSchema(getClass().getResource("/EDIFACT/fragment-segment-syntax-exclusion.xml"))); } catch (EDISchemaException e) { throw new RuntimeException(e); } break; default: break; } return false; }); assertTrue(reader.hasNext(), "Expected errors not found"); reader.next(); assertEquals(EDIStreamValidationError.SEGMENT_EXCLUSION_CONDITION_VIOLATED, reader.getErrorType()); assertEquals("UXC", reader.getReferenceCode()); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testValidEmptySegment() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "ETY~" + "S11*X~" + "S12*X~" + "S19*X~" + "S09*X~" + "IEA*00*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(!reader.hasNext(), "Unexpected errors exist"); } @Test void testEmptySegmentSchemaWithData() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "ETY*DATA_SHOULD_NOT_BE_HERE~" + "S11*X~" + "S12*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaSegmentValidationTx.xml"))); assertTrue(reader.hasNext(), "Expected error missing"); assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, reader.getErrorType()); } @Test void testExtraAnyElementAllowedInAK1() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*HC*000001**ANY1*ANY2~" + "AK9*A*1*1*1~" + "SE*4*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema case START_COMPOSITE: // To ensure no composites signaled for "any" elements return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997_support_any_elements.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertFalse(reader.hasNext(), "Unexpected errors in transaction"); } @Test void testTooManyExtraAnyElementAllowedInAK1() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*HC*000001**ANY1*ANY2*ANY3~" + "AK9*A*1*1*1~" + "SE*4*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema case START_COMPOSITE: // To ensure no composites signaled for "any" elements return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997_support_any_elements.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertTrue(reader.hasNext(), "Expected error missing"); assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.getEventType()); assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, reader.getErrorType()); assertEquals("AK1", reader.getLocation().getSegmentTag()); assertEquals(6, reader.getLocation().getElementPosition()); assertEquals(1, reader.getLocation().getElementOccurrence()); assertEquals(-1, reader.getLocation().getComponentPosition()); } @Test void testNoExtraAnyElementInAK1() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*HC*000001~" + "AK9*A*1*1*1~" + "SE*4*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema case START_COMPOSITE: // To ensure no composites signaled for "any" elements return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997_support_any_elements.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertFalse(reader.hasNext(), "Unexpected errors in transaction"); } @Test void testCompositesSupportedInAnyElementInAK1() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*HC*000001**ANY1:ANY2~" + "AK9*A*1*1*1~" + "SE*4*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997_support_any_elements.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertFalse(reader.hasNext(), "Unexpected errors in transaction"); } @Test void testRequiredComponentInC030InAnyElementInAK4() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*HC*000001~" + "AK2*837*0021~" + "AK3*NM1*8**8~" + "AK4*8:::ANYCOMPONENT*66*7*MI~" + "AK5*R*5~" + "AK9*R*1*1*0~" + "SE*8*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997_support_any_elements.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertFalse(reader.hasNext(), "Unexpected errors in transaction"); } @Test void testMissingRequiredComponentInC030InAnyElementInAK4() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*HC*000001~" + "AK2*837*0021~" + "AK3*NM1*8**8~" + "AK4*8:::*66*7*MI~" + "AK5*R*5~" + "AK9*R*1*1*0~" + "SE*8*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader = factory.createFilteredReader(reader, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997_support_any_elements.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertTrue(reader.hasNext(), "Expected error missing"); assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.next()); assertEquals(EDIStreamValidationError.REQUIRED_DATA_ELEMENT_MISSING, reader.getErrorType()); assertEquals("AK4", reader.getLocation().getSegmentTag()); assertEquals(1, reader.getLocation().getElementPosition()); assertEquals(1, reader.getLocation().getElementOccurrence()); assertEquals(4, reader.getLocation().getComponentPosition()); assertFalse(reader.hasNext(), "Unexpected errors in transaction"); } @Test void testMultiVersionElementType() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*200615*133025*000001*X*003020~" + "ST*000*0001~" + "S0A*AA*GOOD~" // Good + "S0A*111~" // Too long + "S0A*CC~" // Invalid code + "SE*5*0001~" + "GE*1*000001~" + "GS*FA*ReceiverDept*SenderDept*20200615*133025*000002*X*004010~" + "ST*000*0001~" + "S0A*AA*LONG ENOUGH~" // Good + "S0A*111*SHORT~" // Good, 2nd too short + "S0A*3333~" // Too long + "S0A*222~" // Good + "S0A*333~" // Invalid code + "SE*7*0001~" + "GE*1*000002~" + "GS*FA*ReceiverDept*SenderDept*20200615*133025*000003*X*005010~" + "ST*000*0001~" + "S0A*AA~" // Good + "S0A*111~" // Good + "S0A*3333~" // Too long + "S0A*222~" // Good + "S0A*333~" // Good + "S0A*444~" // Invalid code + "SE*8*0001~" + "GE*1*000003~" + "IEA*3*508121953~").getBytes()); EDIStreamReader unfiltered = factory.createEDIStreamReader(stream); EDIStreamReader reader = factory.createFilteredReader(unfiltered, (r) -> { switch (r.getEventType()) { case SEGMENT_ERROR: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case START_TRANSACTION: // To set the schema return true; default: break; } return false; }); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), () -> "Expecting start of transaction, got other " + reader.getLocation()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaMultiVersionElementType.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertTrue(reader.hasNext(), "Expected error missing"); assertNextEvent(reader, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, "S0A", 5, 1, "111"); assertNextEvent(reader, EDIStreamValidationError.INVALID_CODE_VALUE, "S0A", 5, 1, "111"); assertNextEvent(reader, EDIStreamValidationError.INVALID_CODE_VALUE, "S0A", 6, 1, "CC"); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), () -> "Expecting start of transaction, got other " + reader.getLocation()); assertNextEvent(reader, EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT, "S0A", 12, 2, "SHORT");
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIXMLStreamWriterTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIXMLStreamWriterTest.java
package io.xlate.edi.internal.stream; import static io.xlate.edi.test.StaEDITestUtil.assertEqualsNormalizeLineSeparators; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.namespace.NamespaceContext; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stax.StAXResult; import javax.xml.transform.stream.StreamSource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import io.xlate.edi.stream.EDINamespaces; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamWriter; class StaEDIXMLStreamWriterTest { static final Class<UnsupportedOperationException> UNSUPPORTED = UnsupportedOperationException.class; static final String NS_URI_TEST = "urn:names:test"; static final String NS_PFX_TEST = "t"; ByteArrayOutputStream stream; EDIStreamWriter ediWriter; StaEDIXMLStreamWriter it; @BeforeEach void setUp() { EDIOutputFactory ediOutFactory = EDIOutputFactory.newFactory(); ediOutFactory.setProperty(EDIOutputFactory.PRETTY_PRINT, "true"); stream = new ByteArrayOutputStream(); ediWriter = ediOutFactory.createEDIStreamWriter(stream); it = new StaEDIXMLStreamWriter(ediWriter); } @Test void testRepeatedElement() { assertFalse(it.repeatedElement(new QName(EDINamespaces.ELEMENTS, "SG101", "e"), null)); assertTrue(it.repeatedElement(new QName(EDINamespaces.ELEMENTS, "SG101", "e"), new QName(EDINamespaces.ELEMENTS, "SG101", "e2"))); assertFalse(it.repeatedElement(new QName(EDINamespaces.ELEMENTS, "SG101", "e"), new QName(EDINamespaces.ELEMENTS, "SG102", "e2"))); assertTrue(it.repeatedElement(new QName(EDINamespaces.ELEMENTS, "SG101", "e"), new QName(EDINamespaces.COMPOSITES, "SG101", "e2"))); assertFalse(it.repeatedElement(new QName(EDINamespaces.ELEMENTS, "SG101", "e"), new QName(EDINamespaces.COMPOSITES, "SG102", "e2"))); } static void unconfirmedBufferEquals(String expected, EDIStreamWriter writer) { StaEDIStreamWriter writerImpl = (StaEDIStreamWriter) writer; writerImpl.unconfirmedBuffer.mark(); writerImpl.unconfirmedBuffer.flip(); assertEquals(expected, writerImpl.unconfirmedBuffer.toString()); } @Test void testWriteStartElementString() throws XMLStreamException { it.setPrefix("l", EDINamespaces.LOOPS); it.setPrefix("s", EDINamespaces.SEGMENTS); it.writeStartDocument(); it.writeStartElement("l:INTERCHANGE"); it.writeStartElement("s:ISA"); it.flush(); it.close(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteStartElementString_DefaultNamespace() throws XMLStreamException { it.setPrefix("l", EDINamespaces.LOOPS); it.setDefaultNamespace(EDINamespaces.SEGMENTS); it.writeStartDocument(); it.writeStartElement("l:INTERCHANGE"); it.writeStartElement("ISA"); it.flush(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteStartElementString_UndefinedNamespace() throws XMLStreamException { XMLStreamException thrown; it.setPrefix("l", EDINamespaces.LOOPS); it.writeStartDocument(); it.writeStartElement("l:INTERCHANGE"); it.setDefaultNamespace(null); thrown = assertThrows(XMLStreamException.class, () -> it.writeStartElement("ISA")); assertEquals("Element ISA has an undefined namespace", thrown.getMessage()); it.setDefaultNamespace(""); thrown = assertThrows(XMLStreamException.class, () -> it.writeStartElement("ISA")); assertEquals("Element ISA has an undefined namespace", thrown.getMessage()); } @Test void testWriteStartElementStringString() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement(EDINamespaces.LOOPS, "INTERCHANGE"); it.writeStartElement(EDINamespaces.SEGMENTS, "ISA"); it.flush(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteStartElementStringStringString() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); // Test it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); // Test it.writeStartElement("e", "ISA01", EDINamespaces.ELEMENTS); // Test it.writeCharacters("00"); it.flush(); unconfirmedBufferEquals("ISA*00", ediWriter); } @Test void testWriteEmptyElementStringString() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.writeEmptyElement(EDINamespaces.ELEMENTS, "ISA01"); // Test it.writeStartElement("e", "ISA02", EDINamespaces.ELEMENTS); it.writeCharacters(" "); it.flush(); unconfirmedBufferEquals("ISA** ", ediWriter); } @Test void testWriteEmptyElementStringStringString() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.writeEmptyElement("e", "ISA01", EDINamespaces.ELEMENTS); // Test it.writeStartElement("e", "ISA02", EDINamespaces.ELEMENTS); it.writeCharacters(" "); it.flush(); unconfirmedBufferEquals("ISA** ", ediWriter); } @Test void testWriteEmptyElementString() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.writeEmptyElement(EDINamespaces.ELEMENTS, "ISA01"); // Test it.writeStartElement("e", "ISA02", EDINamespaces.ELEMENTS); it.writeCharacters(" "); it.flush(); unconfirmedBufferEquals("ISA** ", ediWriter); } @Test void testWriteEmptyElement() throws XMLStreamException { it.setPrefix("e", EDINamespaces.ELEMENTS); it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.writeEmptyElement("e:ISA01"); // Test it.writeStartElement("e", "ISA02", EDINamespaces.ELEMENTS); it.writeCharacters(" "); it.flush(); unconfirmedBufferEquals("ISA** ", ediWriter); } @Test void testWriteEmptyElement_OutOfSequence() throws XMLStreamException { XMLStreamException thrown; it.setPrefix("e", EDINamespaces.ELEMENTS); it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); thrown = assertThrows(XMLStreamException.class, () -> it.writeEmptyElement("e:ISA01")); assertEquals(IllegalStateException.class, thrown.getCause().getClass()); } @Test void testWriteEndElement() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.writeStartElement(EDINamespaces.ELEMENTS, "ISA01"); it.writeCharacters("00"); it.writeEndElement(); // Test it.flush(); unconfirmedBufferEquals("ISA*00", ediWriter); } @Test void testWriteAttributeStringString() { assertThrows(UNSUPPORTED, () -> it.writeAttribute("", "")); } @Test void testWriteAttributeStringStringStringString() { assertThrows(UNSUPPORTED, () -> it.writeAttribute("", "", "", "")); } @Test void testWriteAttributeStringStringString() { assertThrows(UNSUPPORTED, () -> it.writeAttribute("", "", "")); } @Test void testWriteComment() throws XMLStreamException { it.writeComment(""); it.flush(); unconfirmedBufferEquals("", ediWriter); } @Test void testWriteProcessingInstructionString() { assertThrows(UNSUPPORTED, () -> it.writeProcessingInstruction("")); } @Test void testWriteProcessingInstructionStringString() { assertThrows(UNSUPPORTED, () -> it.writeProcessingInstruction("", "")); } @Test void testWriteDTD() { assertThrows(UNSUPPORTED, () -> it.writeDTD("")); } @Test void testWriteEntityRef() { assertThrows(UNSUPPORTED, () -> it.writeEntityRef("")); } @Test void testWriteStartDocumentString() throws XMLStreamException { it.setPrefix("l", EDINamespaces.LOOPS); it.setPrefix("s", EDINamespaces.SEGMENTS); it.writeStartDocument("1.0"); // Test it.writeStartElement("l:INTERCHANGE"); it.writeStartElement("s:ISA"); it.flush(); it.close(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteStartDocumentStringString() throws XMLStreamException { it.setPrefix("l", EDINamespaces.LOOPS); it.setPrefix("s", EDINamespaces.SEGMENTS); it.writeStartDocument("UTF-8", "1.0"); // Test it.writeStartElement("l:INTERCHANGE"); it.writeStartElement("s:ISA"); it.flush(); it.close(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteCData() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeCData(" \t\n\r"); // Test it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.flush(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteCharactersString_WhitespaceLegal() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeCharacters(" \t\n\r"); // Test it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.flush(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteCharactersString_JunkIllegal() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); XMLStreamException thrown = assertThrows(XMLStreamException.class, () -> it.writeCharacters(" illegal non-whitespace characters ")); assertEquals("Illegal non-whitespace characters", thrown.getMessage()); } @Test void testWriteCharactersCharArrayIntInt_WhitespaceLegal() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); it.writeCharacters(" \t \n \r OUT OF INDEX BOUNDS".toCharArray(), 2, 6); // Test it.writeStartElement("s", "ISA", EDINamespaces.SEGMENTS); it.flush(); unconfirmedBufferEquals("ISA", ediWriter); } @Test void testWriteCharactersCharArrayIntInt_JunkIllegal() throws XMLStreamException { it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); XMLStreamException thrown = assertThrows(XMLStreamException.class, () -> it.writeCharacters(" \t \n \r OUT OF INDEX BOUNDS".toCharArray(), 2, 7)); // Test assertEquals("Illegal non-whitespace characters", thrown.getMessage()); } @Test void testPrefixConfiguration() throws XMLStreamException { it.setPrefix("e", EDINamespaces.SEGMENTS); it.setPrefix("s", EDINamespaces.ELEMENTS); assertEquals("e", it.getPrefix(EDINamespaces.SEGMENTS)); assertNull(it.getPrefix(EDINamespaces.LOOPS)); } @Test void testSetNamespaceContext() throws XMLStreamException { NamespaceContext ctx = Mockito.mock(NamespaceContext.class); Mockito.when(ctx.getNamespaceURI(NS_PFX_TEST)).thenReturn(NS_URI_TEST); Mockito.when(ctx.getPrefix(NS_URI_TEST)).thenReturn(NS_PFX_TEST); it.setNamespaceContext(ctx); assertEquals(NS_PFX_TEST, it.getContextPrefix(NS_URI_TEST)); assertEquals(NS_URI_TEST, it.getContextNamespaceURI(NS_PFX_TEST)); assertNull(it.getContextNamespaceURI("m")); assertNull(it.getContextPrefix("urn:names:missing")); } @Test void testSetNamespaceContext_MultipleCalls() throws XMLStreamException { NamespaceContext ctx = Mockito.mock(NamespaceContext.class); Mockito.when(ctx.getNamespaceURI(NS_PFX_TEST)).thenReturn(NS_URI_TEST); Mockito.when(ctx.getPrefix(NS_URI_TEST)).thenReturn(NS_PFX_TEST); it.setNamespaceContext(ctx); Throwable thrown = assertThrows(XMLStreamException.class, () -> it.setNamespaceContext(ctx)); assertEquals("NamespaceContext has already been set", thrown.getMessage()); } @Test void testSetNamespaceContext_AfterDocumentStart() throws XMLStreamException { NamespaceContext ctx = Mockito.mock(NamespaceContext.class); Mockito.when(ctx.getNamespaceURI(NS_PFX_TEST)).thenReturn(NS_URI_TEST); Mockito.when(ctx.getPrefix(NS_URI_TEST)).thenReturn(NS_PFX_TEST); it.writeStartDocument(); it.writeStartElement("l", "INTERCHANGE", EDINamespaces.LOOPS); Throwable thrown = assertThrows(XMLStreamException.class, () -> it.setNamespaceContext(ctx)); assertEquals("NamespaceContext must only be called at the start of the document", thrown.getMessage()); } @Test void testGetNamespaceContext() throws XMLStreamException { NamespaceContext ctx = Mockito.mock(NamespaceContext.class); it.setNamespaceContext(ctx); assertEquals(ctx, it.getNamespaceContext()); } @Test void testGetProperty() { assertThrows(IllegalArgumentException.class, () -> it.getProperty("anything")); } @Test void testSkippedElementsValid() throws Exception { String input = "" + "<l:INTERCHANGE xmlns:l=\"urn:xlate.io:staedi:names:loops\" xmlns:s=\"urn:xlate.io:staedi:names:segments\" xmlns:c=\"urn:xlate.io:staedi:names:composites\" xmlns:e=\"urn:xlate.io:staedi:names:elements\">\n" + " <s:ISA>\n" + " <e:ISA01>00</e:ISA01>\n" + " <e:ISA02> </e:ISA02>\n" + " <e:ISA03>00</e:ISA03>\n" + " <e:ISA04> </e:ISA04>\n" + " <e:ISA05>ZZ</e:ISA05>\n" + " <e:ISA06>ReceiverID </e:ISA06>\n" + " <e:ISA07>ZZ</e:ISA07>\n" + " <e:ISA08>Sender </e:ISA08>\n" + " <e:ISA09>050812</e:ISA09>\n" + " <e:ISA10>1953</e:ISA10>\n" + " <e:ISA11>^</e:ISA11>\n" + " <e:ISA12>00501</e:ISA12>\n" + " <e:ISA13>000000001</e:ISA13>\n" + " <e:ISA14>0</e:ISA14>\n" + " <e:ISA15>P</e:ISA15>\n" + " <e:ISA16>:</e:ISA16>\n" + " </s:ISA>" + "<l:GROUP>\n" + " <s:GS>\n" + // GS01 skipped " <e:GS02>Receiver</e:GS02>\n" + " <e:GS03>Sender</e:GS03>\n" + " <e:GS04>20050812</e:GS04>\n" + " <e:GS05>195335</e:GS05>\n" + " <e:GS06>1</e:GS06>\n" + " <e:GS07>X</e:GS07>\n" + " <e:GS08>005010X230</e:GS08>\n" + " </s:GS>" + " <s:GE>\n" + " <e:GE01>1</e:GE01>\n" + " <e:GE02>1</e:GE02>\n" + " </s:GE>\n" + " </l:GROUP>" + "<s:IEA>\n" + " <e:IEA01>1</e:IEA01>\n" + " <e:IEA02>000000001</e:IEA02>\n" + " </s:IEA>\n" + "</l:INTERCHANGE>"; StreamSource source = new StreamSource(new ByteArrayInputStream(input.getBytes())); StAXResult result = new StAXResult(it); TransformerFactory.newInstance().newTransformer().transform(source, result); it.close(); assertEqualsNormalizeLineSeparators("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*000000001*0*P*:~\n" + "GS**Receiver*Sender*20050812*195335*1*X*005010X230~\n" + "GE*1*1~\n" + "IEA*1*000000001~\n" + "", new String(stream.toByteArray())); } @Test void testSkippedCompositesValid() throws Exception { String input = "" + "<l:INTERCHANGE xmlns:l=\"urn:xlate.io:staedi:names:loops\" xmlns:s=\"urn:xlate.io:staedi:names:segments\" xmlns:c=\"urn:xlate.io:staedi:names:composites\" xmlns:e=\"urn:xlate.io:staedi:names:elements\">\n" + " <s:UNB>\n" + " <c:UNB01>" + " <e:UNB01-01>UNOA</e:UNB01-01>" + " <e:UNB01-02>3</e:UNB01-02>" + " </c:UNB01>\n" + " <c:UNB04>" + " <e:UNB04-01>200914</e:UNB04-01>" + " <e:UNB04-02>1945</e:UNB04-02>" + " </c:UNB04>" + " <e:UNB05>1</e:UNB05>" + " </s:UNB>" + "<s:UNZ>\n" + " <e:UNZ01>0</e:UNZ01>\n" + " <e:UNZ02>1</e:UNZ02>\n" + " </s:UNZ>\n" + "</l:INTERCHANGE>"; StreamSource source = new StreamSource(new ByteArrayInputStream(input.getBytes())); StAXResult result = new StAXResult(it); TransformerFactory.newInstance().newTransformer().transform(source, result); it.close(); assertEqualsNormalizeLineSeparators("" + "UNB+UNOA:3+++200914:1945+1'\n" + "UNZ+0+1'\n", new String(stream.toByteArray())); } @Test void testSkippedComponentValid() throws Exception { String input = "" + "<l:INTERCHANGE xmlns:l=\"urn:xlate.io:staedi:names:loops\" xmlns:s=\"urn:xlate.io:staedi:names:segments\" xmlns:c=\"urn:xlate.io:staedi:names:composites\" xmlns:e=\"urn:xlate.io:staedi:names:elements\">\n" + " <s:UNB>\n" + " <c:UNB01>" + " <e:UNB01-01>UNOA</e:UNB01-01>" + " <e:UNB01-02>3</e:UNB01-02>" + " </c:UNB01>\n" + " <c:UNB04>" + " <e:UNB04-02>1945</e:UNB04-02>" + " </c:UNB04>" + " <e:UNB05>1</e:UNB05>" + " </s:UNB>" + "<s:UNZ>\n" + " <e:UNZ01>0</e:UNZ01>\n" + " <e:UNZ02>1</e:UNZ02>\n" + " </s:UNZ>\n" + "</l:INTERCHANGE>"; StreamSource source = new StreamSource(new ByteArrayInputStream(input.getBytes())); StAXResult result = new StAXResult(it); TransformerFactory.newInstance().newTransformer().transform(source, result); it.close(); assertEqualsNormalizeLineSeparators("" + "UNB+UNOA:3+++:1945+1'\n" + "UNZ+0+1'\n", new String(stream.toByteArray())); } @Test void testInvalidCompositeNameThrowsException() throws Exception { String input = "" + "<l:INTERCHANGE xmlns:l=\"urn:xlate.io:staedi:names:loops\" xmlns:s=\"urn:xlate.io:staedi:names:segments\" xmlns:c=\"urn:xlate.io:staedi:names:composites\" xmlns:e=\"urn:xlate.io:staedi:names:elements\">\n" + " <s:UNB>\n" + " <c:UNB01>" + " <e:B-01>UNOA</e:B-01>" + " <e:UNB01-02>3</e:UNB01-02>" + " </c:UNB01>\n" + " </s:UNB>" + "<s:UNZ>\n" + " <e:UNZ01>0</e:UNZ01>\n" + " <e:UNZ02>1</e:UNZ02>\n" + " </s:UNZ>\n" + "</l:INTERCHANGE>"; StreamSource source = new StreamSource(new ByteArrayInputStream(input.getBytes())); StAXResult result = new StAXResult(it); Transformer tx = TransformerFactory.newInstance().newTransformer(); Exception thrown; thrown = assertThrows(TransformerException.class, () -> tx.transform(source, result)); Throwable cause = thrown; while (cause.getCause() != null) { cause = cause.getCause(); } assertEquals(String.format(StaEDIXMLStreamWriter.MSG_INVALID_COMPONENT_NAME, "{urn:xlate.io:staedi:names:elements}B-01"), cause.getMessage()); } @Test void testInvalidCompositePositionThrowsException() throws Exception { String input = "" + "<l:INTERCHANGE xmlns:l=\"urn:xlate.io:staedi:names:loops\" xmlns:s=\"urn:xlate.io:staedi:names:segments\" xmlns:c=\"urn:xlate.io:staedi:names:composites\" xmlns:e=\"urn:xlate.io:staedi:names:elements\">\n" + " <s:UNB>\n" + " <c:UNB01>" + " <e:UNB01-AB>UNOA</e:UNB01-AB>" + " <e:UNB01-02>3</e:UNB01-02>" + " </c:UNB01>\n" + " </s:UNB>" + "<s:UNZ>\n" + " <e:UNZ01>0</e:UNZ01>\n" + " <e:UNZ02>1</e:UNZ02>\n" + " </s:UNZ>\n" + "</l:INTERCHANGE>"; StreamSource source = new StreamSource(new ByteArrayInputStream(input.getBytes())); StAXResult result = new StAXResult(it); Transformer tx = TransformerFactory.newInstance().newTransformer(); Exception thrown; thrown = assertThrows(TransformerException.class, () -> tx.transform(source, result)); Throwable cause = thrown; while (cause.getCause() != null) { cause = cause.getCause(); } assertEquals(String.format(StaEDIXMLStreamWriter.MSG_INVALID_COMPONENT_POSITION, "{urn:xlate.io:staedi:names:elements}UNB01-AB"), cause.getMessage()); } @Test void testInvalidElementPositionThrowsException() throws Exception { String input = "" + "<l:INTERCHANGE xmlns:l=\"urn:xlate.io:staedi:names:loops\" xmlns:s=\"urn:xlate.io:staedi:names:segments\" xmlns:c=\"urn:xlate.io:staedi:names:composites\" xmlns:e=\"urn:xlate.io:staedi:names:elements\">\n" + " <s:UNB>\n" + " <c:UNBAA>" + " <e:UNB01-01>UNOA</e:UNB01-01>" + " <e:UNB01-02>3</e:UNB01-02>" + " </c:UNBAA>\n" + " </s:UNB>" + "<s:UNZ>\n" + " <e:UNZ01>0</e:UNZ01>\n" + " <e:UNZ02>1</e:UNZ02>\n" + " </s:UNZ>\n" + "</l:INTERCHANGE>"; StreamSource source = new StreamSource(new ByteArrayInputStream(input.getBytes())); StAXResult result = new StAXResult(it); Transformer tx = TransformerFactory.newInstance().newTransformer(); Exception thrown; thrown = assertThrows(TransformerException.class, () -> tx.transform(source, result)); Throwable cause = thrown; while (cause.getCause() != null) { cause = cause.getCause(); } assertEquals(String.format(StaEDIXMLStreamWriter.MSG_INVALID_ELEMENT_NAME, "{urn:xlate.io:staedi:names:composites}UNBAA"), cause.getMessage()); } @Test void testRepeatedSegmentClearsPreviousElement() throws Exception { StreamSource source = new StreamSource(getClass().getResourceAsStream("/x12/issue134/repeated-ctx-ctx01.xml")); StAXResult result = new StAXResult(it); Transformer tx = TransformerFactory.newInstance().newTransformer(); assertDoesNotThrow(() -> tx.transform(source, result)); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIStreamReaderTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIStreamReaderTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static io.xlate.edi.test.StaEDITestUtil.assertLocation; import static io.xlate.edi.test.StaEDITestUtil.assertTextLocation; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; import java.util.logging.Logger; import java.util.stream.Collectors; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.w3c.dom.Document; import org.xml.sax.SAXException; import io.xlate.edi.internal.schema.SchemaUtils; import io.xlate.edi.schema.EDIComplexType; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.EDIType.Type; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamConstants.Delimiters; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.Location; @SuppressWarnings({ "resource", "unused" }) class StaEDIStreamReaderTest implements ConstantsTest { private static final Logger LOG = Logger.getLogger(StaEDIStreamReaderTest.class.getName()); private Set<EDIStreamEvent> possible = new HashSet<>(); public StaEDIStreamReaderTest() { possible.addAll(Arrays.asList(EDIStreamEvent.ELEMENT_DATA, EDIStreamEvent.START_INTERCHANGE, EDIStreamEvent.START_GROUP, EDIStreamEvent.START_TRANSACTION, EDIStreamEvent.START_LOOP, EDIStreamEvent.START_SEGMENT, EDIStreamEvent.START_COMPOSITE, EDIStreamEvent.END_INTERCHANGE, EDIStreamEvent.END_GROUP, EDIStreamEvent.END_TRANSACTION, EDIStreamEvent.END_LOOP, EDIStreamEvent.END_SEGMENT, EDIStreamEvent.END_COMPOSITE)); } @Test void testGetProperty() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); assertNull(reader.getProperty("NONE"), "Property was not null"); assertThrows(IllegalArgumentException.class, () -> reader.getProperty(null)); } @Test void testGetDelimitersX12() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '~'); expected.put(Delimiters.DATA_ELEMENT, '*'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.REPETITION, '^'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } if (reader.next() == EDIStreamEvent.START_INTERCHANGE) { delimiters = reader.getDelimiters(); } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @ParameterizedTest @CsvSource({ "Basic TRADACOMS, /TRADACOMS/order.edi", "Basic TRADACOMS (extra MHD data), /TRADACOMS/order-extra-mhd-data.edi", }) void testGetDelimitersTRADACOMS(String title, String resourceName) throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream(resourceName); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '\''); expected.put(Delimiters.DATA_ELEMENT, '+'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.RELEASE, '?'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } if (reader.next() == EDIStreamEvent.START_INTERCHANGE) { delimiters = reader.getDelimiters(); } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testGetDelimitersEDIFACTA() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/EDIFACT/invoic_d93a_una.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '\''); expected.put(Delimiters.DATA_ELEMENT, '+'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.RELEASE, '?'); expected.put(Delimiters.DECIMAL, ','); Map<String, Character> delimiters = null; int delimiterExceptions = 0; while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } if (reader.next() == EDIStreamEvent.START_INTERCHANGE) { delimiters = reader.getDelimiters(); } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testGetDelimitersEDIFACTB() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/EDIFACT/invoic_d97b.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '\''); expected.put(Delimiters.DATA_ELEMENT, '+'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); // expected.put(Delimiters.REPETITION, '*'); Input is version 3. No repetition character until version 4 expected.put(Delimiters.RELEASE, '?'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } if (reader.next() == EDIStreamEvent.START_INTERCHANGE) { delimiters = reader.getDelimiters(); } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testAlternateEncodingEDIFACT() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/EDIFACT/invoic_d97b.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); int matches = 0; while (reader.hasNext()) { switch (reader.next()) { case ELEMENT_DATA: Location location = reader.getLocation(); if ("NAD".equals(location.getSegmentTag()) && location.getSegmentPosition() == 7 && location.getElementPosition() == 4) { assertEquals("BÜTTNER WIDGET COMPANY", reader.getText()); matches++; } break; default: break; } } assertEquals(1, matches); } @Test void testGetDelimitersX12_WithISX_00401() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*U*00401*000000001*0*T*:~" + "ISX*\\~" + "GS*FA*ReceiverDept*SenderDept*20200711*010015*1*X*005010~" + "ST*997*0001*005010X230~" + "SE*2*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '~'); expected.put(Delimiters.DATA_ELEMENT, '*'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); //expected.put(Delimiters.REPETITION, '*'); //expected.put(Delimiters.RELEASE, '\\'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; List<EDIStreamValidationError> errors = new ArrayList<>(); while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } switch (reader.next()) { case START_GROUP: delimiters = reader.getDelimiters(); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertArrayEquals(new EDIStreamValidationError[] { EDIStreamValidationError.UNEXPECTED_SEGMENT }, errors.toArray(new EDIStreamValidationError[errors.size()])); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testGetDelimitersX12_WithISX_00501() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "ISX*\\~" + "GS*FA*ReceiverDept*SenderDept*20200711*010015*1*X*005010~" + "ST*997*0001*005010X230~" + "SE*2*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '~'); expected.put(Delimiters.DATA_ELEMENT, '*'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.REPETITION, '^'); //expected.put(Delimiters.RELEASE, '\\'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; List<EDIStreamValidationError> errors = new ArrayList<>(); while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } switch (reader.next()) { case START_GROUP: delimiters = reader.getDelimiters(); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertArrayEquals(new EDIStreamValidationError[] { EDIStreamValidationError.UNEXPECTED_SEGMENT }, errors.toArray(new EDIStreamValidationError[errors.size()])); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testGetDelimitersX12_WithISX_00501_Invalid_Repitition() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*V*00501*000000001*0*T*:~" + "ISX*\\~" + "GS*FA*ReceiverDept*SenderDept*20200711*010015*1*X*005010~" + "ST*997*0001*005010X230~" + "SE*2*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '~'); expected.put(Delimiters.DATA_ELEMENT, '*'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; List<EDIStreamValidationError> errors = new ArrayList<>(); while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } switch (reader.next()) { case START_GROUP: delimiters = reader.getDelimiters(); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertArrayEquals(new EDIStreamValidationError[] { EDIStreamValidationError.UNEXPECTED_SEGMENT }, errors.toArray(new EDIStreamValidationError[errors.size()])); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testGetDelimitersX12_WithISX_00704() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00704*000000001*0*T*:~" + "ISX*\\~" + "GS*FA*ReceiverDept*SenderDept*20200711*010015*1*X*005010~" + "ST*997*0001*005010X230~" + "SE*2*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '~'); expected.put(Delimiters.DATA_ELEMENT, '*'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.REPETITION, '^'); expected.put(Delimiters.RELEASE, '\\'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; List<EDIStreamValidationError> errors = new ArrayList<>(); while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } switch (reader.next()) { case START_GROUP: delimiters = reader.getDelimiters(); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertEquals(0, errors.size(), "Unexpected errors"); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testGetDelimitersX12_WithISX_CharTooLong_00704() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00704*000000001*0*T*:~" + "ISX*##~" + "GS*FA*ReceiverDept*SenderDept*20200711*010015*1*X*005010~" + "ST*997*0001*005010X230~" + "SE*2*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); Map<String, Character> expected = new HashMap<>(5); expected.put(Delimiters.SEGMENT, '~'); expected.put(Delimiters.DATA_ELEMENT, '*'); expected.put(Delimiters.COMPONENT_ELEMENT, ':'); expected.put(Delimiters.REPETITION, '^'); //expected.put(Delimiters.RELEASE, '\\'); expected.put(Delimiters.DECIMAL, '.'); Map<String, Character> delimiters = null; int delimiterExceptions = 0; List<EDIStreamValidationError> errors = new ArrayList<>(); while (reader.hasNext()) { try { reader.getDelimiters(); } catch (IllegalStateException e) { delimiterExceptions++; } switch (reader.next()) { case START_GROUP: delimiters = reader.getDelimiters(); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(expected, delimiters, "Unexpected delimiters"); assertArrayEquals(new EDIStreamValidationError[] { EDIStreamValidationError.DATA_ELEMENT_TOO_LONG }, errors.toArray(new EDIStreamValidationError[errors.size()])); assertEquals(1, delimiterExceptions, "Unexpected exceptions"); } @Test void testX12_ReleaseCharacter() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00704*000000001*0*T*:~" + "ISX*\\~" + "GS*FA*Receiver\\*Dept*Sender\\*Dept*20200711*010015*1*X*005010~" + "ST*997*0001*005010X230~" + "SE*2*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); String senderId = null; String receiverId = null; while (reader.hasNext()) { switch (reader.next()) { case ELEMENT_DATA: if ("GS".equals(reader.getLocation().getSegmentTag())) { switch (reader.getLocation().getElementPosition()) { case 2: receiverId = reader.getText(); break; case 3: senderId = reader.getText(); break; default: break; } } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(0, errors.size(), "Unexpected errors"); assertEquals("Receiver*Dept", receiverId); assertEquals("Sender*Dept", senderId); } @Test void testNext() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); EDIStreamEvent event; do { try { event = reader.next(); assertTrue(possible.contains(event), "Unknown event " + event); } catch (NoSuchElementException e) { event = null; } } while (event != null); } @Test void testNextTag() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setProperty(EDIInputFactory.EDI_VALIDATE_CONTROL_STRUCTURE, "false"); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); int s = 0; EDIStreamEvent event; String tag = null; while (reader.hasNext()) { try { event = reader.nextTag(); } catch (NoSuchElementException e) { break; } if (event != EDIStreamEvent.START_SEGMENT) { fail("Unexpected event: " + event); } tag = reader.getText(); assertEquals(simple997tags[s++], tag, "Unexpected segment"); } String last = simple997tags[simple997tags.length - 1]; assertEquals(last, tag, "Unexpected last segment"); } @Test void testHasNext() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); assertTrue(reader.hasNext(), "Does not have next after create"); EDIStreamEvent event; while (reader.hasNext()) { event = reader.next(); assertTrue(possible.contains(event), "Unknown event"); } } @Test void testClose() throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); reader.close(); try { assertNotEquals(0, stream.available(), "Stream was closed"); } catch (IOException e) { fail("IO Exception: " + e); } assertThrows(IllegalStateException.class, () -> reader.getEventType()); } @Test void testGetEventType() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); EDIStreamEvent event; while (reader.hasNext()) { event = reader.next(); assertEquals(event, reader.getEventType(), "Event not equal"); } } @Test void testGetStandard() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); String standard = null; int events = 0; assertThrows(IllegalStateException.class, () -> reader.getStandard()); while (reader.hasNext()) { if (reader.next() != EDIStreamEvent.END_INTERCHANGE) { standard = reader.getStandard(); events++; } } assertEquals("X12", standard, "Unexpected version"); assertTrue(events > 2, "Unexpected number of events"); } @Test void testGetVersion() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); String version[] = null; int events = 0; assertThrows(IllegalStateException.class, () -> reader.getVersion()); while (reader.hasNext()) { if (reader.next() != EDIStreamEvent.END_INTERCHANGE) { version = reader.getVersion(); events++; } } assertArrayEquals(new String[] { "00501" }, version, "Unexpected version"); assertTrue(events > 2, "Unexpected number of events"); } @Test void testSetSchema() throws EDIStreamException, EDISchemaException, IOException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/invalid997.edi"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema transaction = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema997.xml")); EDIStreamReader reader = factory.createEDIStreamReader(stream); EDIStreamEvent event; int events = 0; String segment = null; Map<String, Set<EDIStreamValidationError>> errors = new HashMap<>(2); while (reader.hasNext()) { event = reader.next(); if (event == EDIStreamEvent.START_INTERCHANGE) { String standard = reader.getStandard(); String[] version = reader.getVersion(); Schema control = SchemaUtils.getControlSchema(standard, version); reader.setControlSchema(control); } else { if (event == EDIStreamEvent.START_TRANSACTION) { reader.setTransactionSchema(transaction); } else if (event == EDIStreamEvent.START_SEGMENT) { segment = reader.getText(); } else if (event == EDIStreamEvent.ELEMENT_DATA_ERROR) { Location l = reader.getLocation(); String key = String.format( "%s%02d", segment, l.getElementPosition()); if (!errors.containsKey(key)) { errors.put(key, new HashSet<EDIStreamValidationError>(2)); } errors.get(key).add(reader.getErrorType()); } else if (event == EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR) { fail("Unexpected error: " + event + " => " + reader.getErrorType() + ", " + reader.getText()); } else if (event == EDIStreamEvent.SEGMENT_ERROR) { fail("Unexpected error: " + event + " => " + reader.getErrorType() + ", " + reader.getText()); } } events++; } assertTrue(errors.get("AK402").contains(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG)); assertTrue(errors.get("AK402").contains(EDIStreamValidationError.INVALID_CHARACTER_DATA)); } @Test void testAddSchema() throws EDIStreamException, EDISchemaException, IOException { EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setProperty(EDIInputFactory.EDI_VALIDATE_CONTROL_STRUCTURE, "false"); InputStream stream = getClass().getResourceAsStream("/x12/invalid997.edi"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema transaction = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema997.xml")); EDIStreamReader reader = factory.createEDIStreamReader(stream); EDIStreamEvent event; int events = 0; String segment = null; Map<String, Set<EDIStreamValidationError>> errors = new HashMap<>(2); while (reader.hasNext()) { event = reader.next(); events++; switch (event) { case START_INTERCHANGE: { String standard = reader.getStandard(); String version[] = reader.getVersion(); Schema control = SchemaUtils.getControlSchema(standard, version); IllegalStateException illegal = null; try { reader.setTransactionSchema(control); } catch (IllegalStateException e) { illegal = e; } assertNotNull(illegal); reader.setControlSchema(control); continue; } case START_SEGMENT: { segment = reader.getText(); IllegalStateException illegal = null; try { reader.setTransactionSchema(transaction); } catch (IllegalStateException e) { illegal = e; } if ("ST".equals(segment)) { assertNull(illegal); } else { assertNotNull(illegal); } break; } case END_SEGMENT: segment = reader.getText(); IllegalStateException illegal = null; try { reader.setTransactionSchema(transaction); } catch (IllegalStateException e) { illegal = e; } if ("ST".equals(segment)) { assertNull(illegal); } else { assertNotNull(illegal);
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIOutputFactoryTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIOutputFactoryTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.OutputStream; import org.junit.jupiter.api.Test; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamConstants; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamWriter; class StaEDIOutputFactoryTest { @Test void testNewFactory() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); assertTrue(factory instanceof StaEDIOutputFactory); } @Test void testCreateEDIStreamWriterOutputStream() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = System.out; EDIStreamWriter writer = factory.createEDIStreamWriter(stream); assertNotNull(writer, "Writer was null"); } @Test void testCreateEDIStreamWriterOutputStreamString() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = System.out; String encoding = "US-ASCII"; EDIStreamWriter writer = factory.createEDIStreamWriter(stream, encoding); assertNotNull(writer, "Writer was null"); } @Test void testCreateEDIStreamWriterInvalidEncoding() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = System.out; String encoding = "EBCDIC"; EDIStreamException e = assertThrows(EDIStreamException.class, () -> factory.createEDIStreamWriter(stream, encoding)); assertEquals("Unsupported encoding: EBCDIC", e.getMessage()); } @Test void testIsPropertySupported() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); assertTrue(!factory.isPropertySupported("FOO"), "FOO supported"); } @Test void testGetPropertyUnsupported() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> factory.getProperty("FOO")); } @Test() void testGetPropertySupported() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); assertNull(factory.getProperty(EDIStreamConstants.Delimiters.DATA_ELEMENT)); } @Test void testSetPropertyUnsupported() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> factory.setProperty("FOO", null)); } @Test void testSetPropertySupported() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIStreamConstants.Delimiters.REPETITION, '`'); assertEquals('`', factory.getProperty(EDIStreamConstants.Delimiters.REPETITION)); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/ConstantsTest.java
src/test/java/io/xlate/edi/internal/stream/ConstantsTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; public interface ConstantsTest { String[] simple997tags = { "ISA", "GS", "ST", "AK1", "AK2", "AK3", "AK4", "AK5", "AK9", "SE", "GE", "IEA" }; String[] invoic_d97btags = { "UNB", "UNH", "BGM", "DTM", "RFF", "NAD", "NAD", "CUX", "LIN", "IMD", "QTY", "ALI", "MOA", "PRI", "LIN", "IMD", "QTY", "ALI", "MOA", "PRI", "UNS", "MOA", "ALC", "MOA", "UNT", "UNZ" }; String[] invoic_d97b_unatags = { "UNA", "UNB", "UNH", "BGM", "DTM", "RFF", "NAD", "NAD", "CUX", "LIN", "IMD", "QTY", "ALI", "MOA", "PRI", "LIN", "IMD", "QTY", "ALI", "MOA", "PRI", "UNS", "MOA", "ALC", "MOA", "UNT", "UNZ" }; }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIXMLStreamReaderTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIXMLStreamReaderTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static io.xlate.edi.test.StaEDITestUtil.assertEqualsNormalizeLineSeparators; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Base64; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.StreamFilter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stax.StAXResult; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.builder.Input; import org.xmlunit.diff.DefaultComparisonFormatter; import org.xmlunit.diff.Diff; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDINamespaces; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamFilter; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.EDIStreamWriter; import io.xlate.edi.stream.EDIValidationException; import io.xlate.edi.stream.Location; import io.xlate.edi.test.StaEDITestUtil; @SuppressWarnings("resource") class StaEDIXMLStreamReaderTest { static byte[] DUMMY_X12 = ("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S11*X~" + "S12*X~" + "S19*X~" + "S09*X~" + "IEA*1*508121953~").getBytes(); static byte[] TINY_X12 = ("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "IEA*1*508121953~").getBytes(); private EDIStreamReader ediReader; XMLStreamReader getXmlReader(String resource) throws XMLStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream(resource); ediReader = factory.createEDIStreamReader(stream); return new StaEDIXMLStreamReader(ediReader); } XMLStreamReader getXmlReader(byte[] bytes) throws XMLStreamException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setProperty(EDIInputFactory.EDI_VALIDATE_CONTROL_STRUCTURE, "false"); InputStream stream = new ByteArrayInputStream(bytes); ediReader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, ediReader.next()); return new StaEDIXMLStreamReader(ediReader); } static void skipEvents(XMLStreamReader reader, int eventCount) throws XMLStreamException { for (int i = 0; i < eventCount; i++) { reader.next(); } } @Test void testCreateEDIXMLStreamReader() throws XMLStreamException { XMLStreamReader xmlReader = getXmlReader("/x12/simple997.edi"); assertNotNull(xmlReader, "xmlReader was null"); } @Test void testHasNext() throws Exception { XMLStreamReader xmlReader = getXmlReader(TINY_X12); assertTrue(xmlReader.hasNext()); xmlReader.close(); assertThrows(XMLStreamException.class, () -> xmlReader.hasNext()); assertThrows(XMLStreamException.class, () -> xmlReader.next()); } private static void assertSegmentBoundaries(XMLStreamReader xmlReader, String tag, int elementCount) throws XMLStreamException { assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals(tag, xmlReader.getLocalName()); xmlReader.require(XMLStreamConstants.START_ELEMENT, null, tag); skipEvents(xmlReader, 3 * elementCount); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals(tag, xmlReader.getLocalName()); xmlReader.require(XMLStreamConstants.END_ELEMENT, null, tag); } @Test void testSegmentSequence() throws Exception { XMLStreamReader xmlReader = getXmlReader(DUMMY_X12); assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertSegmentBoundaries(xmlReader, "ISA", 16); assertSegmentBoundaries(xmlReader, "S01", 1); assertSegmentBoundaries(xmlReader, "S11", 1); assertSegmentBoundaries(xmlReader, "S12", 1); assertSegmentBoundaries(xmlReader, "S19", 1); assertSegmentBoundaries(xmlReader, "S09", 1); assertSegmentBoundaries(xmlReader, "IEA", 2); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_DOCUMENT, xmlReader.next()); } @Test void testRequire() throws Exception { XMLStreamReader xmlReader = getXmlReader(DUMMY_X12); XMLStreamException thrown; assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType()); thrown = assertThrows(XMLStreamException.class, () -> xmlReader.require(XMLStreamConstants.START_DOCUMENT, EDINamespaces.LOOPS, "INTERCHANGE")); assertTrue(thrown.getMessage().endsWith("does not have a corresponding name")); thrown = assertThrows(XMLStreamException.class, () -> xmlReader.require(XMLStreamConstants.START_ELEMENT, EDINamespaces.LOOPS, "INTERCHANGE")); assertTrue(thrown.getMessage().contains("does not match required type")); xmlReader.next(); // Happy Path xmlReader.require(XMLStreamConstants.START_ELEMENT, EDINamespaces.LOOPS, "INTERCHANGE"); xmlReader.require(XMLStreamConstants.START_ELEMENT, EDINamespaces.LOOPS, null); xmlReader.require(XMLStreamConstants.START_ELEMENT, null, "INTERCHANGE"); xmlReader.require(XMLStreamConstants.START_ELEMENT, null, null); thrown = assertThrows(XMLStreamException.class, () -> xmlReader.require(XMLStreamConstants.START_ELEMENT, EDINamespaces.LOOPS, "GROUP")); assertTrue(thrown.getMessage().contains("does not match required localName")); thrown = assertThrows(XMLStreamException.class, () -> xmlReader.require(XMLStreamConstants.START_ELEMENT, EDINamespaces.SEGMENTS, "INTERCHANGE")); assertTrue(thrown.getMessage().contains("does not match required namespaceURI")); } @Test void testGetElementText() throws Exception { XMLStreamReader xmlReader = getXmlReader(DUMMY_X12); XMLStreamException thrown; assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); thrown = assertThrows(XMLStreamException.class, () -> xmlReader.getElementText()); assertEquals("Element text only available for simple element", thrown.getMessage()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // ISA01; assertEquals("00", xmlReader.getElementText()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // ISA02; assertEquals(" ", xmlReader.getElementText()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // ISA03; assertEquals("00", xmlReader.getElementText()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // ISA04; xmlReader.next(); // CHARACTERS thrown = assertThrows(XMLStreamException.class, () -> xmlReader.getElementText()); assertEquals("Element text only available on START_ELEMENT", thrown.getMessage()); } @Test void testNamespaces() throws Exception { XMLStreamReader xmlReader = getXmlReader(TINY_X12); assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType()); assertNull(xmlReader.getNamespaceURI()); assertThrows(IllegalStateException.class, () -> xmlReader.getName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals(EDINamespaces.LOOPS, xmlReader.getNamespaceURI("l")); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(EDINamespaces.LOOPS, xmlReader.getName().getNamespaceURI()); assertEquals("l", xmlReader.getName().getPrefix()); assertEquals(4, xmlReader.getNamespaceCount()); assertEquals(EDINamespaces.LOOPS, xmlReader.getNamespaceURI()); assertSegmentBoundaries(xmlReader, "ISA", 16); NamespaceContext context = xmlReader.getNamespaceContext(); assertEquals("s", context.getPrefix(EDINamespaces.SEGMENTS)); assertEquals("s", context.getPrefixes(EDINamespaces.SEGMENTS).next()); assertEquals(EDINamespaces.SEGMENTS, context.getNamespaceURI("s")); assertNull(context.getNamespaceURI("x")); assertEquals(EDINamespaces.SEGMENTS, xmlReader.getNamespaceURI()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("IEA", xmlReader.getLocalName()); assertEquals(EDINamespaces.SEGMENTS, xmlReader.getNamespaceURI()); // No namespaces declared on the segment assertEquals(0, xmlReader.getNamespaceCount()); assertNull(xmlReader.getNamespacePrefix(0)); assertNull(xmlReader.getNamespaceURI(0)); assertElement(xmlReader, "IEA01", "1"); assertEquals(EDINamespaces.ELEMENTS, xmlReader.getNamespaceURI()); // No namespaces declared on the element assertEquals(0, xmlReader.getNamespaceCount()); assertNull(xmlReader.getNamespacePrefix(0)); assertNull(xmlReader.getNamespaceURI(0)); assertElement(xmlReader, "IEA02", "508121953"); assertEquals(EDINamespaces.ELEMENTS, xmlReader.getNamespaceURI()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("IEA", xmlReader.getLocalName()); assertEquals(EDINamespaces.SEGMENTS, xmlReader.getNamespaceURI()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(EDINamespaces.LOOPS, xmlReader.getName().getNamespaceURI()); assertEquals("l", xmlReader.getName().getPrefix()); assertEquals(4, xmlReader.getNamespaceCount()); assertEquals(EDINamespaces.LOOPS, xmlReader.getNamespaceURI()); assertEquals(XMLStreamConstants.END_DOCUMENT, xmlReader.next()); assertNull(xmlReader.getNamespaceURI("l")); } private void assertElement(XMLStreamReader xmlReader, String tag, String value) throws Exception { assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals(tag, xmlReader.getLocalName()); assertEquals(value, xmlReader.getElementText()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.getEventType()); assertEquals(tag, xmlReader.getLocalName()); } @Test void testElementEvents() throws Exception { XMLStreamReader xmlReader = getXmlReader(TINY_X12); assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertElement(xmlReader, "ISA01", "00"); assertElement(xmlReader, "ISA02", " "); assertElement(xmlReader, "ISA03", "00"); assertElement(xmlReader, "ISA04", " "); assertElement(xmlReader, "ISA05", "ZZ"); assertElement(xmlReader, "ISA06", "ReceiverID "); assertElement(xmlReader, "ISA07", "ZZ"); assertElement(xmlReader, "ISA08", "Sender "); assertElement(xmlReader, "ISA09", "050812"); assertElement(xmlReader, "ISA10", "1953"); assertElement(xmlReader, "ISA11", "^"); assertElement(xmlReader, "ISA12", "00501"); assertElement(xmlReader, "ISA13", "508121953"); assertElement(xmlReader, "ISA14", "0"); assertElement(xmlReader, "ISA15", "P"); assertElement(xmlReader, "ISA16", ":"); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("IEA", xmlReader.getLocalName()); assertElement(xmlReader, "IEA01", "1"); assertElement(xmlReader, "IEA02", "508121953"); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("IEA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_DOCUMENT, xmlReader.next()); assertFalse(xmlReader.hasNext()); xmlReader.close(); } @Test void testReadXml() throws Exception { XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi"); xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter result = new StringWriter(); transformer.transform(new StAXSource(xmlReader), new StreamResult(result)); String resultString = result.toString(); Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997.xml")) .withTest(resultString).build(); assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter())); } @Test void testReadXml_WithOptionalInterchangeServiceRequests_TransactionOnly() throws Exception { EDIInputFactory ediFactory = EDIInputFactory.newFactory(); XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); InputStream stream = getClass().getResourceAsStream("/x12/optionalInterchangeServices.edi"); ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE); EDIStreamReader reader = ediFactory.createEDIStreamReader(stream); EDIStreamReader filtered = ediFactory.createFilteredReader(reader, r -> true); XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(filtered); xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state XMLStreamReader xmlCursor = xmlFactory.createFilteredReader(xmlReader, r -> { boolean startTx = (r.getEventType() == XMLStreamConstants.START_ELEMENT && r.getName().getLocalPart().equals("TRANSACTION")); if (!startTx) { Logger.getGlobal().info("Skipping event: " + r.getEventType() + "; " + (r.getEventType() == XMLStreamConstants.START_ELEMENT || r.getEventType() == XMLStreamConstants.END_ELEMENT ? r.getName() : "")); } return startTx; }); xmlCursor.hasNext(); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter result = new StringWriter(); transformer.transform(new StAXSource(xmlReader), new StreamResult(result)); String resultString = result.toString(); System.out.println(resultString); Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/optionalInterchangeServices_transactionOnly.xml")) .withTest(resultString).build(); assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter())); } @Test void testTransactionElementWithXmlns() throws Exception { EDIInputFactory ediFactory = EDIInputFactory.newFactory(); ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE); InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi"); ediReader = ediFactory.createEDIStreamReader(stream); XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(ediReader); xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter result = new StringWriter(); transformer.transform(new StAXSource(xmlReader), new StreamResult(result)); String resultString = result.toString(); Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997-transaction-xmlns.xml")) .withTest(resultString).build(); assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter())); } @Test void testXmlIOEquivalence() throws Exception { XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi"); xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter result = new StringWriter(); transformer.transform(new StAXSource(xmlReader), new StreamResult(result)); String resultString = result.toString(); EDIOutputFactory ediOutFactory = EDIOutputFactory.newFactory(); ediOutFactory.setProperty(EDIOutputFactory.PRETTY_PRINT, "true"); ByteArrayOutputStream resultEDI = new ByteArrayOutputStream(); EDIStreamWriter ediWriter = ediOutFactory.createEDIStreamWriter(resultEDI); XMLStreamWriter xmlWriter = new StaEDIXMLStreamWriter(ediWriter); transformer.transform(new StreamSource(new StringReader(resultString)), new StAXResult(xmlWriter)); String expectedEDI = String.join("\n", Files.readAllLines(Paths.get("src/test/resources/x12/extraDelimiter997.edi"))); assertEqualsNormalizeLineSeparators(expectedEDI, new String(resultEDI.toByteArray()).trim()); } @Test void testSchemaValidatedInput() throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema997.xml")); EDIStreamReader ediReader = factory.createEDIStreamReader(stream); EDIStreamFilter ediFilter = (reader) -> { switch (reader.getEventType()) { case START_INTERCHANGE: case START_GROUP: case START_TRANSACTION: case START_LOOP: case START_SEGMENT: case END_SEGMENT: case END_LOOP: case END_TRANSACTION: case END_GROUP: case END_INTERCHANGE: return true; default: return false; } }; ediReader = factory.createFilteredReader(ediReader, ediFilter); XMLStreamReader xmlReader = new StaEDIXMLStreamReader(ediReader); assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.next()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("GROUP", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("GS", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("GS", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("TRANSACTION", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("ST", xmlReader.getLocalName()); ediReader.setTransactionSchema(schema); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("ST", xmlReader.getLocalName()); } @Test @SuppressWarnings("unused") void testUnsupportedOperations() throws Exception { EDIStreamReader ediReader = Mockito.mock(EDIStreamReader.class); XMLStreamReader xmlReader = new StaEDIXMLStreamReader(ediReader); try { xmlReader.getAttributeValue("", ""); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getAttributeName(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getAttributeNamespace(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getAttributeLocalName(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getAttributePrefix(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getAttributeType(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getAttributeValue(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.isAttributeSpecified(0); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getPITarget(); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} try { xmlReader.getPIData(); fail("UnsupportedOperationExpected"); } catch (UnsupportedOperationException e) {} } @Test void testGetTextString() throws Exception { XMLStreamReader xmlReader = getXmlReader(DUMMY_X12); assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.getEventType()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // ISA01; assertEquals(XMLStreamConstants.CHARACTERS, xmlReader.next()); // ISA01 content; assertNull(xmlReader.getNamespaceURI()); assertThrows(IllegalStateException.class, () -> xmlReader.getName()); String textString = xmlReader.getText(); assertEquals("00", textString); char[] textArray = xmlReader.getTextCharacters(); assertArrayEquals(new char[] { '0', '0' }, textArray); char[] textArray2 = xmlReader.getTextCharacters(); // 2nd call should be the same characters assertArrayEquals(textArray, textArray2); char[] textArrayLocal = new char[3]; xmlReader.getTextCharacters(xmlReader.getTextStart(), textArrayLocal, 0, xmlReader.getTextLength()); assertArrayEquals(new char[] { '0', '0', '\0' }, textArrayLocal); } @Test void testGetCdataBinary() throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple_with_binary_segment.edi"); EDIStreamReader ediReader = factory.createEDIStreamReader(stream); AtomicReference<String> segmentName = new AtomicReference<>(); EDIStreamFilter ediFilter = (reader) -> { switch (reader.getEventType()) { case START_SEGMENT: segmentName.set(reader.getText()); return true; case START_INTERCHANGE: case START_GROUP: case START_TRANSACTION: case START_LOOP: case ELEMENT_DATA_BINARY: case END_SEGMENT: case END_LOOP: case END_TRANSACTION: case END_GROUP: case END_INTERCHANGE: return true; default: return "BIN".equals(segmentName.get()); } }; ediReader = factory.createFilteredReader(ediReader, ediFilter); XMLStreamReader xmlReader = new StaEDIXMLStreamReader(ediReader); SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchemaBinarySegment.xml")); assertEquals(XMLStreamConstants.START_DOCUMENT, xmlReader.next()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("INTERCHANGE", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("ISA", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("GROUP", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("GS", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("GS", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("TRANSACTION", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("ST", xmlReader.getLocalName()); ediReader.setTransactionSchema(schema); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("ST", xmlReader.getLocalName()); /* BIN #1 ********************************************************************/ assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("BIN", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // BIN01; assertEquals(XMLStreamConstants.CHARACTERS, xmlReader.next()); // BIN01 content; assertEquals("25", xmlReader.getText()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); // BIN01; assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // BIN02; assertEquals(XMLStreamConstants.CDATA, xmlReader.next()); // BIN02 content; assertEquals(Base64.getEncoder().encodeToString("1234567890123456789012345".getBytes()), xmlReader.getText()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); // BIN02; assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("BIN", xmlReader.getLocalName()); /* BIN #2 ********************************************************************/ assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("BIN", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // BIN01; assertEquals(XMLStreamConstants.CHARACTERS, xmlReader.next()); // BIN01 content; assertEquals("25", xmlReader.getText()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); // BIN01; assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // BIN02; assertEquals(XMLStreamConstants.CDATA, xmlReader.next()); // BIN02 content; String expected2 = Base64.getEncoder().encodeToString("12345678901234567890\n1234".getBytes()); assertArrayEquals(expected2.toCharArray(), xmlReader.getTextCharacters()); assertArrayEquals(expected2.toCharArray(), xmlReader.getTextCharacters()); // 2nd call should be the same characters assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); // BIN02; assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); assertEquals("BIN", xmlReader.getLocalName()); /* BIN #3 ********************************************************************/ assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.nextTag()); assertEquals("BIN", xmlReader.getLocalName()); assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // BIN01; assertEquals(XMLStreamConstants.CHARACTERS, xmlReader.next()); // BIN01 content; assertEquals("25", xmlReader.getText()); assertEquals(XMLStreamConstants.END_ELEMENT, xmlReader.next()); // BIN01; assertEquals(XMLStreamConstants.START_ELEMENT, xmlReader.next()); // BIN02;
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/CompositeValidationTest.java
src/test/java/io/xlate/edi/internal/stream/CompositeValidationTest.java
/******************************************************************************* * Copyright 2020 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static io.xlate.edi.test.StaEDITestUtil.assertEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamFilter; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; @SuppressWarnings("resource") class CompositeValidationTest { @Test void testInvalidCompositeOccurrences() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "S01*X~" + "S10*A*1:COMP2*2:COMP3~" // TOO_MANY_DATA_ELEMENTS + "S11*A*2:REP1^3:REP2^4:REP3*5~" // TOO_MANY_REPETITIONS + "S11*B*3:REP1*4~" // IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT + "S11*B**:5~" // TOO_MANY_COMPONENTS + "S99*X:X~" // SEGMENT_NOT_IN_DEFINED_TRANSACTION_SET + "S12*A^B**X~" // REQUIRED_DATA_ELEMENT_MISSING (S1202), IMPLEMENTATION_TOO_FEW_REPETITIONS (S1203) + "S12*A*X:Y*1^2*YY~" // IMPLEMENTATION_TOO_FEW_REPETITIONS (S1201), IMPLEMENTATION_INVALID_CODE_VALUE (S1204 == YY) + "S12*A^B*X:Y:ZZ:??*1^2*XX~" // IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT (S1202-03 == ZZ) + "S13*A*1234567890~" // IMPLEMENTATION_TOO_FEW_REPETITIONS (S1202) + "S09*X~" + "IEA*1*508121953~").getBytes()); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchemaSegmentValidation.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); reader = factory.createFilteredReader(reader, new EDIStreamFilter() { @Override public boolean accept(EDIStreamReader reader) { switch (reader.getEventType()) { case START_TRANSACTION: case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: case START_LOOP: case END_LOOP: return true; default: return false; } } }); assertEvent(reader, EDIStreamEvent.START_TRANSACTION); reader.setTransactionSchema(schemaFactory.createSchema(getClass().getResource("/x12/composites/invalid-composite-occurrences.xml"))); // Loop A assertEvent(reader, EDIStreamEvent.START_LOOP, "0000A"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, null); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.TOO_MANY_REPETITIONS, "C001"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT, "C001"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.TOO_MANY_COMPONENTS, "E002"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.TOO_MANY_COMPONENTS, "E002"); assertEvent(reader, EDIStreamEvent.SEGMENT_ERROR, EDIStreamValidationError.SEGMENT_NOT_IN_DEFINED_TRANSACTION_SET, "S99", null); assertEvent(reader, EDIStreamEvent.END_LOOP, "0000A"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.REQUIRED_DATA_ELEMENT_MISSING, "C002"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.IMPLEMENTATION_TOO_FEW_REPETITIONS, "E002"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.IMPLEMENTATION_TOO_FEW_REPETITIONS, "E001"); assertEvent(reader, EDIStreamEvent.ELEMENT_DATA_ERROR, EDIStreamValidationError.IMPLEMENTATION_INVALID_CODE_VALUE, "E003"); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT, "E003"); assertEquals(10, reader.getLocation().getSegmentPosition()); assertEquals(2, reader.getLocation().getElementPosition()); assertEquals(3, reader.getLocation().getComponentPosition()); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.TOO_MANY_COMPONENTS, "C002"); assertEquals(10, reader.getLocation().getSegmentPosition()); assertEquals(2, reader.getLocation().getElementPosition()); assertEquals(4, reader.getLocation().getComponentPosition()); assertEvent(reader, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamValidationError.IMPLEMENTATION_TOO_FEW_REPETITIONS, "E002"); assertTrue(!reader.hasNext(), "Unexpected segment errors exist"); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/EventSequenceTest.java
src/test/java/io/xlate/edi/internal/stream/EventSequenceTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.schema.SchemaUtils; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamConstants.Standards; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamFilter; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; class EventSequenceTest { @Test void testValidatedTagSequence() throws EDISchemaException, EDIStreamException, IllegalStateException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001*005010X230~" + "AK1*HC*000001~" + "AK2*837*0021~" + "AK3*NM1*8**8~" + "AK4*8*66*7*MI~" + "AK5*R*5~" + "AK9*R*1*1*0~" + "SE*8*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamEvent event; @SuppressWarnings("resource") EDIStreamReader reader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); reader.setControlSchema(SchemaUtils.getControlSchema(reader.getStandard(), reader.getVersion())); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("ISA", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_GROUP, reader.next()); assertEquals("GROUP", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("GS", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next()); assertEquals("TRANSACTION", reader.getText()); reader.setTransactionSchema(loadX12FuncAckSchema()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("ST", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK1", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_LOOP, reader.next()); assertEquals("2000", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK2", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_LOOP, reader.next()); assertEquals("2100", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK3", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK4", reader.getText()); ak4: while (true) { switch (event = reader.next()) { case ELEMENT_DATA: case START_COMPOSITE: case END_COMPOSITE: continue; default: break ak4; } } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.END_LOOP, reader.next()); // 2100 assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK5", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.END_LOOP, reader.next()); // 2000 assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK9", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("SE", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.END_TRANSACTION, reader.next()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("GE", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.END_GROUP, reader.next()); // 0000 assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("IEA", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // IEA01 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // IEA02 assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); // IEA assertEquals(EDIStreamEvent.END_INTERCHANGE, reader.next()); } @Test void testMissingTagSequence() throws EDISchemaException, EDIStreamException, IllegalStateException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001*005010X230~" + "AK1*HC*000001~" + "SE*3*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); EDIStreamEvent event; @SuppressWarnings("resource") EDIStreamReader reader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); reader.setControlSchema(SchemaUtils.getControlSchema(reader.getStandard(), reader.getVersion())); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("ISA", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_GROUP, reader.next()); assertEquals("GROUP", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("GS", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next()); assertEquals("TRANSACTION", reader.getText()); reader.setTransactionSchema(loadX12FuncAckSchema()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("ST", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("AK1", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); // Missing AK9 in our test schema, does not match the standard. assertEquals(EDIStreamEvent.SEGMENT_ERROR, reader.next()); assertEquals("AK9", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("SE", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.END_TRANSACTION, reader.next()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("GE", reader.getText()); while ((event = reader.next()) == EDIStreamEvent.ELEMENT_DATA) { continue; } assertEquals(EDIStreamEvent.END_SEGMENT, event); assertEquals(EDIStreamEvent.END_GROUP, reader.next()); // GROUP assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("IEA", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // IEA01 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // IEA02 assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); // IEA assertEquals(EDIStreamEvent.END_INTERCHANGE, reader.next()); } @Test void testValidSequenceEDIFACT() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "UNB+UNOA:3+005435656:1+006415160:1+060515:1434+00000000000778'" + "UNH+00000000000117+INVOIC:D:97B:UN'" + "BLA+UNVALIDATED'" + "UNT+3+00000000000117'" + "UNZ+1+00000000000778'").getBytes()); @SuppressWarnings("resource") EDIStreamReader reader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); assertArrayEquals(new String[] { "UNOA", "3" }, reader.getVersion()); Schema schema = SchemaUtils.getControlSchema(Standards.EDIFACT, reader.getVersion()); reader.setControlSchema(schema); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("UNB", reader.getText()); assertEquals(EDIStreamEvent.START_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("UNOA", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("3", reader.getText()); assertEquals(EDIStreamEvent.END_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.START_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("005435656", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("1", reader.getText()); assertEquals(EDIStreamEvent.END_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.START_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("006415160", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("1", reader.getText()); assertEquals(EDIStreamEvent.END_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.START_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("060515", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("1434", reader.getText()); assertEquals(EDIStreamEvent.END_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("00000000000778", reader.getText()); assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next()); assertEquals("TRANSACTION", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("UNH", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("00000000000117", reader.getText()); assertEquals(EDIStreamEvent.START_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("INVOIC", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("D", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("97B", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("UN", reader.getText()); assertEquals(EDIStreamEvent.END_COMPOSITE, reader.next()); assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("BLA", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("UNVALIDATED", reader.getText()); assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("UNT", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("3", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("00000000000117", reader.getText()); assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); assertEquals(EDIStreamEvent.END_TRANSACTION, reader.next()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.next()); assertEquals("UNZ", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("1", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("00000000000778", reader.getText()); assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); assertEquals(EDIStreamEvent.END_INTERCHANGE, reader.next()); } @Test void testElementErrorSequence() throws EDISchemaException, EDIStreamException, IllegalStateException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*BAD_DATE*295335*000005*X*005010X230~" + "ST*997*0001~" + "AK1*<NOT_IN_CODESET>*000001~" + "AK9*R*1*1*0~" + "AK9*~" + "SE*8*0001~" + "GE*1*<TOO_LONG_AND_NOT_NUMERIC>^0001^AGAIN!*:~" + "IEA*1*508121953~").getBytes()); @SuppressWarnings("resource") EDIStreamReader reader = factory.createEDIStreamReader(stream); assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); reader.setControlSchema(SchemaUtils.getControlSchema(reader.getStandard(), reader.getVersion())); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("ISA", reader.getText()); assertEquals(EDIStreamEvent.START_GROUP, reader.nextTag()); assertEquals("GROUP", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("GS", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS01 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS02 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS03 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS04 assertEquals("BAD_DATE", reader.getText()); // GS05 invalid time assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.INVALID_TIME, reader.getErrorType()); assertEquals("295335", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS05 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS06 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS07 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GS08 // GS04 BAD_DATE (known bad only after GS08 version is set) assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals("373", reader.getReferenceCode()); assertEquals(EDIStreamValidationError.INVALID_DATE, reader.getErrorType()); assertEquals("BAD_DATE", reader.getText()); assertEquals(2, reader.getLocation().getSegmentPosition()); assertEquals("GS", reader.getLocation().getSegmentTag()); assertEquals(4, reader.getLocation().getElementPosition()); assertEquals(1, reader.getLocation().getElementOccurrence()); assertEquals(-1, reader.getLocation().getComponentPosition()); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.nextTag()); reader.setTransactionSchema(loadX12FuncAckSchema()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("ST", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("AK1", reader.getText()); // AK01 <NOT_IN_CODESET> assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, reader.getErrorType()); assertEquals("<NOT_IN_CODESET>", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.INVALID_CODE_VALUE, reader.getErrorType()); assertEquals("<NOT_IN_CODESET>", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // AK01 assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("AK9", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("AK9", reader.getText()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("SE", reader.getText()); //assertEquals(EDIStreamEvent.END_TRANSACTION, reader.nextTag()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("GE", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GE01 // GE02 <TOO_LONG_AND_NOT_NUMERIC> assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, reader.getErrorType()); assertEquals("<TOO_LONG_AND_NOT_NUMERIC>", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.INVALID_CHARACTER_DATA, reader.getErrorType()); assertEquals("<TOO_LONG_AND_NOT_NUMERIC>", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); // GE02 assertEquals(EDIStreamValidationError.CONTROL_REFERENCE_MISMATCH, reader.getErrorType()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // GE02 assertEquals("28", reader.getReferenceCode()); // GE02 - 2nd occurrence assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.next()); assertEquals(EDIStreamValidationError.TOO_MANY_REPETITIONS, reader.getErrorType()); assertEquals("0001", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.CONTROL_REFERENCE_MISMATCH, reader.getErrorType()); assertEquals("0001", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("0001", reader.getText()); // GE02 - 3rd occurrence plus data error assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.next()); assertEquals("28", reader.getReferenceCode()); assertEquals("AGAIN!", reader.getText()); // data association with error assertEquals(EDIStreamValidationError.TOO_MANY_REPETITIONS, reader.getErrorType()); assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.INVALID_CHARACTER_DATA, reader.getErrorType()); assertEquals("AGAIN!", reader.getText()); // data association with error assertEquals(EDIStreamEvent.ELEMENT_DATA_ERROR, reader.next()); assertEquals(EDIStreamValidationError.CONTROL_REFERENCE_MISMATCH, reader.getErrorType()); assertEquals("AGAIN!", reader.getText()); // data association with error assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); assertEquals("AGAIN!", reader.getText()); // here comes the element data // event // GE03 too many elements assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.next()); assertEquals(EDIStreamValidationError.TOO_MANY_DATA_ELEMENTS, reader.getErrorType()); assertEquals("", reader.getText()); // data association with error //assertEquals(EDIStreamEvent.END_GROUP, reader.nextTag()); assertEquals(EDIStreamEvent.START_SEGMENT, reader.nextTag()); assertEquals("IEA", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // IEA01 assertEquals(EDIStreamEvent.ELEMENT_DATA, reader.next()); // IEA02 assertEquals(EDIStreamEvent.END_SEGMENT, reader.next()); // IEA assertEquals(EDIStreamEvent.END_INTERCHANGE, reader.next()); } @Test @SuppressWarnings("resource") void testSegmentNameMatchesReferenceCode() throws EDISchemaException, EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*01*0000000000*01*0000000000*ZZ*ABCDEFGHIJKLMNO*ZZ*123456789012345*101127*1719*`*00402*000003438*0*P*>\n" + "GS*HC*99999999999*888888888888*20111219*1340*1377*X*005010X222\n" + "ST*837*0001*005010X222\n" + "BHT*0019*00*565743*20110523*154959*CH\n" + "HL*1**20*1\n" + "SE*4*0001\n" + "GE*1*1377\n" + "IEA*1*000003438\n" + "").getBytes()); EDIStreamReader unfiltered = factory.createEDIStreamReader(stream); EDIStreamReader reader = factory.createFilteredReader(unfiltered, new EDIStreamFilter() { @Override public boolean accept(EDIStreamReader reader) { switch (reader.getEventType()) { case START_TRANSACTION: case START_SEGMENT: return true; default: return false; } } }); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "ISA"); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "GS"); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next(), "Expecting start of transaction"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/005010X222/837.xml"); Schema schema = schemaFactory.createSchema(schemaLocation); reader.setTransactionSchema(schema); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "ST"); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "BHT"); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "HL"); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "SE"); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "GE"); assertTagEvent(reader, EDIStreamEvent.START_SEGMENT, "IEA"); assertTrue(!reader.hasNext(), "Unexpected events exist"); } private Schema loadX12FuncAckSchema() throws EDISchemaException { SchemaFactory schemaFactory = SchemaFactory.newFactory(); URL schemaLocation = getClass().getResource("/x12/EDISchema997.xml"); return schemaFactory.createSchema(schemaLocation); } private void assertTagEvent(EDIStreamReader reader, EDIStreamEvent expectedEvent, String expectedText) throws EDIStreamException { assertEquals(expectedEvent, reader.nextTag()); assertEquals(expectedText, reader.getText()); assertEquals(expectedText, reader.getReferenceCode()); } @Test void testElementReturnedOnDerivedComposite() throws EDISchemaException, EDIStreamException { SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.createSchema(new ByteArrayInputStream(("" + "<schema xmlns='http://xlate.io/EDISchema/v4'>" + "<transaction>" + " <sequence>" + " <segment type='SG1'/>" + " </sequence>" + "</transaction>" + "" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "" + "<compositeType name=\"C1\">" + " <sequence>" + " <element type='E1'/>" + " <element type='E1'/>" + " </sequence>" + "</compositeType>" + "" + "<segmentType name=\"SG1\">" + " <sequence>" + " <element type='E1'/>" + " <composite type='C1'/>" + " <element type='E1'/>" + " </sequence>" + "</segmentType>" + "</schema>").getBytes())); InputStream stream = new ByteArrayInputStream(("" + "ISA*01*0000000000*01*0000000000*ZZ*ABCDEFGHIJKLMNO*ZZ*123456789012345*101127*1719*`*00402*000003438*0*P*>\n" + "GS*HC*99999999999*888888888888*20111219*1340*1377*X*005010\n" + "ST*999*0001\n" + "SG1*11111*22222`22222*33333\n" + "SE*3*0001\n" + "GE*1*1377\n" + "IEA*1*000003438\n" + "").getBytes()); EDIInputFactory factory = EDIInputFactory.newFactory(); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIReference> c1refs = new ArrayList<>(); List<EDIReference> e1refs = new ArrayList<>(); while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: reader.setTransactionSchema(schema); break; case START_COMPOSITE: if (reader.getLocation().getSegmentTag().equals("SG1") && reader.getLocation().getElementPosition() == 2) { c1refs.add(reader.getSchemaTypeReference()); } break; case ELEMENT_DATA: if (reader.getLocation().getSegmentTag().equals("SG1") && reader.getLocation().getElementPosition() == 2) { e1refs.add(reader.getSchemaTypeReference()); } break; default: break; } } assertEquals(2, c1refs.size()); assertEquals("C1", c1refs.get(0).getReferencedType().getId()); assertEquals("C1", c1refs.get(1).getReferencedType().getId()); assertEquals(2, e1refs.size()); assertEquals("E1", e1refs.get(0).getReferencedType().getId()); assertEquals("E1", e1refs.get(1).getReferencedType().getId()); } @Test void testTransactionMetadataAvailable() throws EDIStreamException, IllegalStateException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*FA*ReceiverDept*SenderDept*20050812*195335*000005*X*005010X230~" + "ST*997*0001*005010X230~" + "AK1*HC*000001~" + "AK9*R*1*1*0~" + "SE*8*0001~" + "GE*1*000005~" + "IEA*1*508121953~").getBytes()); @SuppressWarnings("resource") EDIStreamReader reader = factory.createEDIStreamReader(stream); while (reader.next() != EDIStreamEvent.START_TRANSACTION) { assertThrows(IllegalStateException.class, reader::getTransactionType); } assertEquals(EDIStreamEvent.START_TRANSACTION, reader.getEventType()); do { assertEquals("997", reader.getTransactionType()); assertArrayEquals(new String[] { "X", "005010X230" }, reader.getTransactionVersion()); } while (reader.next() != EDIStreamEvent.END_TRANSACTION); assertEquals(EDIStreamEvent.END_TRANSACTION, reader.getEventType()); assertEquals("997", reader.getTransactionType()); assertArrayEquals(new String[] { "X", "005010X230" }, reader.getTransactionVersion()); reader.next(); assertThrows(IllegalStateException.class, reader::getTransactionType); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIStreamReaderExtraneousCharsTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIStreamReaderExtraneousCharsTest.java
/******************************************************************************* * Copyright 2020 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamReader; class StaEDIStreamReaderExtraneousCharsTest { Logger LOGGER = Logger.getGlobal(); @SuppressWarnings("unchecked") List<Object>[] readFully(EDIInputFactory factory, String resource) throws IOException { EDIStreamReader reader = factory.createEDIStreamReader(getClass().getResourceAsStream(resource)); List<Object> expected = new ArrayList<>(); List<Object> unexpected = new ArrayList<>(); try { while (reader.hasNext()) { switch (reader.next()) { case START_INTERCHANGE: expected.add(reader.getEventType()); break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: LOGGER.log(Level.WARNING, () -> reader.getErrorType() + ", " + reader.getLocation() + ", data: [" + reader.getText() + "]"); unexpected.add(reader.getErrorType()); break; case START_GROUP: case START_TRANSACTION: case START_LOOP: case START_SEGMENT: case END_GROUP: case END_TRANSACTION: case END_LOOP: case END_SEGMENT: case ELEMENT_DATA: expected.add(reader.getEventType() + " [" + reader.getText() + "]"); break; default: expected.add(reader.getEventType() + ", " + reader.getLocation()); break; } } } catch (Exception e) { unexpected.add(e); e.printStackTrace(); } finally { reader.close(); } return new List[] { expected, unexpected }; } /** * Original issue: https://github.com/xlate/staedi/issues/128 * * @throws Exception */ @ParameterizedTest @ValueSource( strings = { "/x12/issue128/ts210_80char.edi", "/EDIFACT/issue128/wrapped_invoic_d97b_una.edi", "/EDIFACT/issue128/wrapped_invoic_d97b.edi" }) void testExtraneousCharactersIgnoredWithoutError(String resourceName) throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setProperty(EDIInputFactory.EDI_IGNORE_EXTRANEOUS_CHARACTERS, "true"); List<Object>[] results = readFully(factory, resourceName); List<Object> unexpected = results[1]; assertEquals(0, unexpected.size(), () -> "Expected none, but got: " + unexpected); } @ParameterizedTest @CsvSource({ "/EDIFACT/issue128/wrapped_invoic_d97b_una.edi, /EDIFACT/invoic_d97b_una.edi", "/EDIFACT/issue128/wrapped_invoic_d97b.edi, /EDIFACT/invoic_d97b.edi" }) void testExtraneousCharactersRemovedMatchesOriginal(String wrapped, String original) throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); List<Object>[] results1 = readFully(factory, original); factory.setProperty(EDIInputFactory.EDI_IGNORE_EXTRANEOUS_CHARACTERS, "true"); List<Object>[] results2 = readFully(factory, wrapped); assertEquals(0, results1[1].size(), () -> "Expected none, but got: " + results1[1]); assertEquals(results1[0], results2[0]); assertEquals(results1[1], results2[1]); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIInputFactoryTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIInputFactoryTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.InputStream; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputErrorReporter; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; @SuppressWarnings("resource") class StaEDIInputFactoryTest { @Test void testNewFactory() { EDIInputFactory factory = EDIInputFactory.newFactory(); assertTrue(factory instanceof StaEDIInputFactory); } @Test void testCreateEDIStreamReader() { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); EDIStreamReader reader = factory.createEDIStreamReader(stream); assertNotNull(reader, "Reader was null"); } @Test void testCreateEDIStreamReaderEncoded() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); String encoding = "US-ASCII"; EDIStreamReader reader = factory.createEDIStreamReader(stream, encoding); assertNotNull(reader, "Reader was null"); } @Test void testCreateEDIStreamReaderInvalidEncoding() { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); String encoding = "EBCDIC"; EDIStreamException e = assertThrows(EDIStreamException.class, () -> factory.createEDIStreamReader(stream, encoding)); assertEquals("Unsupported encoding: EBCDIC", e.getMessage()); } @Test void testCreateEDIStreamReaderValidated() throws EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.createSchema(getClass().getResourceAsStream("/x12/EDISchema997.xml")); EDIStreamReader reader = factory.createEDIStreamReader(stream, schema); assertNotNull(reader, "Reader was null"); } @Test void testCreateEDIStreamReaderEncodedValidated() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); String encoding = "US-ASCII"; SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.createSchema(getClass().getResourceAsStream("/x12/EDISchema997.xml")); EDIStreamReader reader = factory.createEDIStreamReader(stream, encoding, schema); assertNotNull(reader, "Reader was null"); } @Test void testCreateFilteredReader() { EDIInputFactory factory = EDIInputFactory.newFactory(); EDIStreamReader reader = null; // EDIStreamFilter is a functional interface reader = factory.createFilteredReader(reader, (r) -> false); assertNotNull(reader, "Reader was null"); } @Test void testIsPropertySupported() { EDIInputFactory factory = EDIInputFactory.newFactory(); assertFalse(factory.isPropertySupported("FOO"), "Reporter property not supported"); } @Test void testGetPropertyUnsupported() { EDIInputFactory factory = EDIInputFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> factory.getProperty("FOO")); } @Test void testSetPropertyUnsupported() { EDIInputFactory factory = EDIInputFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> factory.setProperty("FOO", null)); } @SuppressWarnings("deprecation") @Test void testDeprecatedReporterMethodUsesDeprecatedType() { io.xlate.edi.stream.EDIReporter deprecatedReporter = Mockito.mock(io.xlate.edi.stream.EDIReporter.class); EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setEDIReporter(deprecatedReporter); assertSame(deprecatedReporter, factory.getErrorReporter()); assertSame(deprecatedReporter, factory.getEDIReporter()); } @SuppressWarnings("deprecation") @Test void testDeprecatedReporterMethodThrowsException() { EDIInputErrorReporter reporter = Mockito.mock(EDIInputErrorReporter.class); EDIInputFactory factory = EDIInputFactory.newFactory(); factory.setErrorReporter(reporter); assertSame(reporter, factory.getErrorReporter()); assertThrows(ClassCastException.class, () -> factory.getEDIReporter()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/StaEDIStreamWriterTest.java
src/test/java/io/xlate/edi/internal/stream/StaEDIStreamWriterTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import static io.xlate.edi.test.StaEDITestUtil.normalizeLines; import static io.xlate.edi.test.StaEDITestUtil.write; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import io.xlate.edi.internal.schema.SchemaUtils; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIOutputErrorReporter; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamConstants; import io.xlate.edi.stream.EDIStreamConstants.Delimiters; import io.xlate.edi.stream.EDIStreamConstants.Standards; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.EDIStreamWriter; import io.xlate.edi.stream.EDIValidationException; import io.xlate.edi.stream.Location; import io.xlate.edi.test.StaEDITestUtil; @SuppressWarnings("resource") class StaEDIStreamWriterTest { private final String TEST_HEADER_X12 = "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~"; private void writeHeader(EDIStreamWriter writer) throws EDIStreamException { // TEST_HEADER_X12 writer.writeStartSegment("ISA"); writer.writeElement("00").writeElement(" "); writer.writeElement("00").writeElement(" "); writer.writeElement("ZZ").writeElement("ReceiverID "); writer.writeElement("ZZ").writeElement("Sender "); writer.writeElement("050812"); writer.writeElement("1953"); writer.writeElement("^"); writer.writeElement("00501"); writer.writeElement("508121953"); writer.writeElement("0"); writer.writeElement("P"); writer.writeElement(":"); writer.writeEndSegment(); } static void unconfirmedBufferEquals(String expected, EDIStreamWriter writer) { StaEDIStreamWriter writerImpl = (StaEDIStreamWriter) writer; writerImpl.unconfirmedBuffer.mark(); writerImpl.unconfirmedBuffer.flip(); assertEquals(expected, writerImpl.unconfirmedBuffer.toString()); } @Test void testGetProperty() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIStreamConstants.Delimiters.SEGMENT, '~'); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); Object segmentTerminator = writer.getProperty(EDIStreamConstants.Delimiters.SEGMENT); assertEquals(Character.valueOf('~'), segmentTerminator); } @Test void testGetNullProperty() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(1); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); assertThrows(IllegalArgumentException.class, () -> writer.getProperty(null)); } @Test void testInvalidBooleanPropertyIsFalse() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIOutputFactory.TRUNCATE_EMPTY_ELEMENTS, new Object()); OutputStream stream = new ByteArrayOutputStream(1); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); assertTrue(writer instanceof StaEDIStreamWriter); assertEquals(false, ((StaEDIStreamWriter) writer).emptyElementTruncation); } @Test void testGetDelimitersIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); assertThrows(IllegalStateException.class, () -> writer.getDelimiters()); } @Test void testStartInterchange() { try { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); } catch (Exception e) { fail("Unexpected exception: " + e.getMessage()); } } @ParameterizedTest @ValueSource(strings = { "ISA", "UNA", "UNB", "STX" }) void testStartInterchangeIllegal(String interchangeStartSegmentTag) throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment(interchangeStartSegmentTag); assertThrows(IllegalStateException.class, () -> writer.startInterchange()); } @Test void testEndInterchange() { try { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.endInterchange(); } catch (Exception e) { fail("Unexpected exception: " + e.getMessage()); } } @Test void testEndInterchangeIllegal() { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); assertThrows(IllegalStateException.class, () -> writer.endInterchange()); } @Test void testWriteStartSegment() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.flush(); unconfirmedBufferEquals("ISA", writer); } @Test void testWriteInvalidHeaderElement() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeElement("00").writeElement(" "); // Too long writer.writeElement("00").writeElement(" "); // Too long writer.writeElement("ZZ").writeElement("ReceiverID "); writer.writeElement("ZZ").writeElement("Sender "); writer.writeElement("050812"); writer.writeElement("1953"); writer.writeElement("^"); writer.writeElement("00501"); writer.writeElement("508121953"); writer.writeElement("0"); writer.writeElement("P"); EDIStreamException thrown = assertThrows(EDIStreamException.class, () -> writer.writeElement(":")); assertEquals("Failed writing X12 header: Element delimiter '*' required in position 18 of X12 header but not found", thrown.getMessage()); } @Test void testWriteStartSegmentIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); assertThrows(IllegalStateException.class, () -> writer.writeStartSegment("GS")); } @Test void testWriteEndSegment() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement().writeElementData("E1").endElement(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA*E1~", writer); } @Test void testWriteEndSegmentIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); assertThrows(IllegalStateException.class, () -> writer.writeEndSegment()); } @Test void testStartComponentIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); assertThrows(IllegalStateException.class, () -> writer.startComponent()); } @Test void testWriteStartElement() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement() .endElement() .writeStartElement() .endElement() .writeStartElement() .endElement() .writeStartElement() .endElement(); writer.flush(); unconfirmedBufferEquals("ISA****", writer); } @Test void testWriteStartElementIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); writer.startComponent(); assertThrows(IllegalStateException.class, () -> writer.writeStartElement()); } @Test void testWriteInvalidCharacter() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); EDIStreamException thrown = assertThrows(EDIStreamException.class, () -> writer.writeElementData("\u0008\u0010")); assertEquals("Invalid character: 0x0008 in segment ISA at position 1, element 1", thrown.getMessage()); } @Test void testWriteInvalidCharacterRepeatedComposite() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.writeStartSegment("FOO"); writer.writeElement("BAR1"); writer.writeRepeatElement(); // starts new element writer.writeComponent("BAR2"); writer.writeComponent("BAR3"); EDIStreamException thrown = assertThrows(EDIStreamException.class, () -> writer.writeComponent("\u0008\u0010")); assertEquals("Invalid character: 0x0008 in segment FOO at position 2, element 1 (occurrence 2), component 3", thrown.getMessage()); Location l = thrown.getLocation(); assertEquals("FOO", l.getSegmentTag()); assertEquals(2, l.getSegmentPosition()); assertEquals(1, l.getElementPosition()); assertEquals(2, l.getElementOccurrence()); assertEquals(3, l.getComponentPosition()); } @Test void testWriteInvalidSegmentTag() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.writeStartSegment("G"); EDIStreamException thrown = assertThrows(EDIStreamException.class, () -> writer.writeElement("FOO")); assertEquals("Invalid state: INVALID; output 0x002A", thrown.getMessage()); } @Test void testWriteStartElementBinary() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.flush(); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElementBinary().writeEndSegment(); writer.flush(); assertEquals("BIN*~", stream.toString()); } @Test void testWriteStartElementBinaryIllegal() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); assertThrows(IllegalStateException.class, () -> writer.writeStartElementBinary()); } @Test void testWriteBinaryDataIllegal() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); ByteBuffer binaryData = ByteBuffer.allocate(1); assertThrows(IllegalStateException.class, () -> writer.writeBinaryData(binaryData)); } @Test void testStartComponentIllegalInElementBinary() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.flush(); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElementBinary(); assertThrows(IllegalStateException.class, () -> writer.startComponent()); } @Test void testComponent() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement() .startComponent() .endComponent() .startComponent(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA*:~", writer); } @Test void testComponent_EmptyTruncated() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIOutputFactory.TRUNCATE_EMPTY_ELEMENTS, true); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement() .startComponent() .endComponent() .startComponent() .endComponent() .endElement() .writeEmptyElement(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA~", writer); } @Test void testComponentIllegal() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); writer.startComponent(); assertThrows(IllegalStateException.class, () -> writer.startComponent()); // Double } @Test void testWriteRepeatElement() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.flush(); stream.reset(); writer.writeStartSegment("SEG"); writer.writeStartElement() .writeElementData("R1") .writeRepeatElement() .writeElementData("R2") .writeEndSegment(); writer.flush(); assertEquals("SEG*R1^R2~", stream.toString()); } @Test void testWriteEmptyElement() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeEmptyElement(); writer.writeEmptyElement(); writer.writeEmptyElement(); writer.writeEmptyElement(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA****~", writer); } @Test void testWriteEmptyComponent() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA*:::~", writer); } @Test void testWriteEmptyElements_EmptyTruncated() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIOutputFactory.TRUNCATE_EMPTY_ELEMENTS, true); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.endElement(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA~", writer); } @Test void testWriteTruncatedElements() throws IllegalStateException, EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); factory.setProperty(EDIOutputFactory.TRUNCATE_EMPTY_ELEMENTS, true); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); // All components truncated writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.endElement(); // Components after "LAST" truncated writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeComponent("LAST"); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.endElement(); // All present writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.writeComponent("LAST"); writer.endElement(); // All present writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeComponent("SECOND"); writer.writeEmptyComponent(); writer.writeComponent("LAST"); writer.endElement(); writer.writeEmptyElement(); writer.writeEmptyElement(); writer.writeElement("LAST"); // All three elements truncated writer.writeEmptyElement(); writer.writeStartElement(); writer.writeEmptyComponent(); writer.writeEmptyComponent(); writer.endElement(); writer.writeEmptyElement(); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA**:LAST*:::LAST*:SECOND::LAST***LAST~", writer); } @Test void testWriteElementDataCharSequence() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); writer.writeElementData("TEST-ELEMENT"); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA*TEST-ELEMENT~", writer); } @Test void testWriteElementDataCharSequenceIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.writeStartSegment("GS"); writer.writeStartElement(); assertThrows(IllegalArgumentException.class, () -> writer.writeElementData("** BAD^ELEMENT **")); } @Test void testWriteElementDataCharArray() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA"); writer.writeStartElement(); writer.writeElementData(new char[] { 'C', 'H', 'A', 'R', 'S' }, 0, 5); assertThrows(EDIStreamException.class, () -> writer.writeEndSegment()); writer.flush(); unconfirmedBufferEquals("ISA*CHARS~", writer); } @Test void testWriteElementDataCharInvalidBoundaries() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.writeStartSegment("GS"); writer.writeStartElement(); assertThrows(IndexOutOfBoundsException.class, () -> writer.writeElementData(new char[] { 'F', 'A' }, -1, 2)); assertThrows(IndexOutOfBoundsException.class, () -> writer.writeElementData(new char[] { 'F', 'A' }, 2, 1)); assertThrows(IndexOutOfBoundsException.class, () -> writer.writeElementData(new char[] { 'F', 'A' }, 0, 3)); assertThrows(IllegalArgumentException.class, () -> writer.writeElementData(new char[] { 'F', 'A' }, 0, -1)); } @Test void testWriteElementDataCharArrayIllegal() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); OutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writeHeader(writer); writer.writeStartSegment("GS"); writer.writeStartElement(); assertThrows(IllegalArgumentException.class, () -> writer.writeElementData(new char[] { 'C', 'H', '~', 'R', 'S' }, 0, 5)); } @Test void testWriteBinaryDataInputStream() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); byte[] binary = { '\n', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, '\t' }; InputStream binaryStream = new ByteArrayInputStream(binary); writer.startInterchange(); writeHeader(writer); writer.flush(); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElement(); writer.writeElementData("8"); writer.endElement(); writer.writeStartElementBinary(); writer.writeBinaryData(binaryStream); writer.endElement(); writer.writeEndSegment(); writer.flush(); assertEquals("BIN*8*\n\u0000\u0001\u0002\u0003\u0004\u0005\t~", stream.toString()); } @Test void testWriteBinaryDataInputStreamReadIOException() throws Exception { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); InputStream binaryStream = Mockito.mock(InputStream.class); IOException ioException = new IOException(); Mockito.when(binaryStream.read()).thenThrow(ioException); writer.startInterchange(); writeHeader(writer); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElement(); writer.writeElementData("4"); writer.endElement(); writer.writeStartElementBinary(); EDIStreamException thrown = assertThrows(EDIStreamException.class, () -> writer.writeBinaryData(binaryStream)); assertEquals("Exception reading binary data source for output in segment BIN at position 2, element 2", thrown.getMessage()); assertSame(ioException, thrown.getCause()); } @Test void testWriteBinaryDataInputStreamWriteIOException() throws Exception { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = Mockito.spy(new ByteArrayOutputStream(4096)); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); byte[] binary = { '\n', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, '\t' }; InputStream binaryStream = new ByteArrayInputStream(binary); AtomicBoolean binaryElementStarted = new AtomicBoolean(false); IOException ioException = new IOException(); Mockito.doAnswer(args -> { if (binaryElementStarted.get()) { throw ioException; } args.callRealMethod(); return null; }).when(stream).write(0x00); // fail on second byte of binary stream writer.startInterchange(); writeHeader(writer); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElement(); writer.writeElementData("4"); writer.endElement(); writer.writeStartElementBinary(); binaryElementStarted.set(true); EDIStreamException thrown = assertThrows(EDIStreamException.class, () -> writer.writeBinaryData(binaryStream)); assertEquals("Exception writing binary element data in segment BIN at position 2, element 2", thrown.getMessage()); assertSame(ioException, thrown.getCause()); } @Test void testWriteBinaryDataByteArray() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); byte[] binary = { '\n', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, '\t' }; writer.startInterchange(); writeHeader(writer); writer.flush(); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElement(); writer.writeElementData("8"); writer.endElement(); writer.writeStartElementBinary(); writer.writeBinaryData(binary, 0, binary.length); writer.endElement(); writer.writeEndSegment(); writer.flush(); assertEquals("BIN*8*\n\u0000\u0001\u0002\u0003\u0004\u0005\t~", stream.toString()); } @Test void testWriteBinaryDataByteBuffer() throws EDIStreamException { EDIOutputFactory factory = EDIOutputFactory.newFactory(); ByteArrayOutputStream stream = new ByteArrayOutputStream(4096); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); byte[] binary = { '\n', 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, '\t' }; ByteBuffer buffer = ByteBuffer.wrap(binary); writer.startInterchange(); writeHeader(writer); writer.flush(); stream.reset(); writer.writeStartSegment("BIN"); writer.writeStartElement(); writer.writeElementData("8"); writer.endElement(); writer.writeStartElementBinary(); writer.writeBinaryData(buffer);
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/tokenization/DialectFactoryTest.java
src/test/java/io/xlate/edi/internal/stream/tokenization/DialectFactoryTest.java
package io.xlate.edi.internal.stream.tokenization; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class DialectFactoryTest { static char[] X12 = { '\0', 'I', 'S', 'A', '\0' }; static char[] EDIFACT_A = { '\0', 'U', 'N', 'A', '\0' }; static char[] EDIFACT_B = { '\0', 'U', 'N', 'B', '\0' }; static char[] BAD = { 'B', 'A', 'D', '\0' }; @Test void testX12() throws EDIException { Dialect d1 = DialectFactory.getDialect(X12, 1, 3); assertEquals("ISA", d1.getHeaderTag()); } @Test void testEDIFACT_A() throws EDIException { Dialect d1 = DialectFactory.getDialect(EDIFACT_A, 1, 3); assertEquals("UNA", d1.getHeaderTag()); } @Test void testEDIFACT_B() throws EDIException { Dialect d1 = DialectFactory.getDialect(EDIFACT_B, 1, 3); assertEquals("UNB", d1.getHeaderTag()); } @Test void testInvalidTag() { assertThrows(EDIException.class, () -> DialectFactory.getDialect(BAD, 1, 3)); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/tokenization/CharacterSetTest.java
src/test/java/io/xlate/edi/internal/stream/tokenization/CharacterSetTest.java
package io.xlate.edi.internal.stream.tokenization; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class CharacterSetTest { @Test void testGetClassAscii() { CharacterSet target = new CharacterSet(); assertEquals(CharacterClass.ALPHANUMERIC, target.getClass('Y')); } @Test void testGetClassUTF8() { CharacterSet target = new CharacterSet(); assertEquals(CharacterClass.OTHER, target.getClass('£')); } @Test void testSetClassAscii() { CharacterSet target = new CharacterSet(); target.setClass('\\', CharacterClass.RELEASE_CHARACTER); assertTrue(target.isCharacterClass('\\', CharacterClass.RELEASE_CHARACTER)); } @Test void testSetClassUTF8() { CharacterSet target = new CharacterSet(); target.setClass('£', CharacterClass.RELEASE_CHARACTER); assertTrue(target.isCharacterClass('£', CharacterClass.RELEASE_CHARACTER)); } @Test void testGetDelimiterValidClass() { CharacterSet target = new CharacterSet(); target.setClass('`', CharacterClass.ELEMENT_REPEATER); assertEquals(CharacterClass.ELEMENT_REPEATER, target.getClass('`')); } @Test void testIsReleaseAscii() { CharacterSet target = new CharacterSet(); target.setClass('\\', CharacterClass.RELEASE_CHARACTER); assertEquals(CharacterClass.RELEASE_CHARACTER, target.getClass('\\')); } @Test void testIsReleaseUTF8() { CharacterSet target = new CharacterSet(); assertNotEquals(CharacterClass.RELEASE_CHARACTER, target.getClass('£')); } @Test void testIsValidAscii() { assertTrue(CharacterSet.isValid('A')); } @Test void testIsValidUTF8() { assertTrue(CharacterSet.isValid('ü')); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/tokenization/X12DialectTest.java
src/test/java/io/xlate/edi/internal/stream/tokenization/X12DialectTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream.tokenization; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class X12DialectTest { @Test void testX12Dialect() throws EDIException { Dialect x12 = DialectFactory.getDialect("ISA".toCharArray(), 0, 3); assertTrue(x12 instanceof X12Dialect, "Incorrect type"); } @Test void testGetEnvelopeTag() throws EDIException { Dialect x12 = DialectFactory.getDialect("ISA".toCharArray(), 0, 3); assertEquals("ISA", x12.getHeaderTag(), "Incorrect header tag"); } @Test void testInitializeTrue() throws EDIException { X12Dialect x12 = (X12Dialect) DialectFactory.getDialect("ISA".toCharArray(), 0, 3); x12.header = "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~".toCharArray(); assertTrue(x12.initialize(new CharacterSet())); } @Test void testInitializeRejected() throws EDIException { X12Dialect x12 = (X12Dialect) DialectFactory.getDialect("ISA".toCharArray(), 0, 3); x12.header = "ISA*00* * *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~".toCharArray(); assertFalse(x12.initialize(new CharacterSet())); assertTrue(x12.isRejected()); assertEquals("Unexpected element delimiter value '*' in X12 header position 12", x12.getRejectionMessage()); } @Test void testGetVersion() throws EDIException { X12Dialect x12 = (X12Dialect) DialectFactory.getDialect("ISA".toCharArray(), 0, 3); x12.header = "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~".toCharArray(); x12.initialize(new CharacterSet()); assertArrayEquals(new String[] { "00501" }, x12.getVersion(), "Invalid version"); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/tokenization/EDIFACTDialectTest.java
src/test/java/io/xlate/edi/internal/stream/tokenization/EDIFACTDialectTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream.tokenization; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class EDIFACTDialectTest { @Test void testEDIFACTADialect() throws EDIException { Dialect edifact = DialectFactory.getDialect("UNA".toCharArray(), 0, 3); assertTrue(edifact instanceof EDIFACTDialect, "Incorrect type"); } @Test void testEDIFACTBDialect() throws EDIException { Dialect edifact = DialectFactory.getDialect("UNB".toCharArray(), 0, 3); assertTrue(edifact instanceof EDIFACTDialect, "Incorrect type"); } @Test void testGetEnvelopeTagA() throws EDIException { Dialect edifact = DialectFactory.getDialect("UNA".toCharArray(), 0, 3); assertEquals("UNA", edifact.getHeaderTag(), "Incorrect header tag"); } @Test void testGetEnvelopeTagB() throws EDIException { Dialect edifact = DialectFactory.getDialect("UNB".toCharArray(), 0, 3); assertEquals("UNB", edifact.getHeaderTag(), "Incorrect header tag"); } @Test void testGetVersionA() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+. *'UNB+UNOA:1+111111111:1+222222222:1+200726:1455+1'".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); edifact.initialize(characters); assertArrayEquals(new String[] { "UNOA", "1" }, edifact.getVersion(), "Invalid version"); } @Test void testGetVersionB() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNB".toCharArray(), 0, 3); edifact.header = new StringBuilder("UNB+UNOA:1+005435656:1+006415160:1+060515:1434+00000000000778'"); CharacterSet characters = new CharacterSet(); edifact.initialize(characters); assertArrayEquals(new String[] { "UNOA", "1" }, edifact.getVersion(), "Invalid version"); } @Test void testBlankReleaseCharPreVersion4() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+. *'UNB+UNOA:1+111111111:1+222222222:1+200726:1455+1'".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.initialize(characters)); assertEquals('\'', edifact.getSegmentTerminator()); assertEquals('+', edifact.getDataElementSeparator()); assertEquals(':', edifact.getComponentElementSeparator()); assertEquals('.', edifact.getDecimalMark()); assertEquals('\0', edifact.getRepetitionSeparator()); assertEquals('\0', edifact.getReleaseIndicator()); } @Test void testBlankReleaseCharVersion4() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+. *'UNB+UNOA:4+111111111:1+222222222:1+200726:1455+1'".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.initialize(characters)); assertEquals('\'', edifact.getSegmentTerminator()); assertEquals('+', edifact.getDataElementSeparator()); assertEquals(':', edifact.getComponentElementSeparator()); assertEquals('.', edifact.getDecimalMark()); // UNA value ignored, per spec assertEquals('*', edifact.getRepetitionSeparator()); assertEquals(' ', edifact.getReleaseIndicator()); } @Test void testDecimalMarkIgnoredVersion4() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+_ *'UNB+UNOA:4+111111111:1+222222222:1+200726:1455+1'".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.initialize(characters)); assertTrue(edifact.isDecimalMark('.')); assertTrue(edifact.isDecimalMark(',')); assertFalse(edifact.isDecimalMark('_')); } @Test void testBlankSegmentTermPreVersion4() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+.\\* UNB+UNOA:3+111111111:1+222222222:1+200726:1455+1 ".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.initialize(characters)); assertEquals(' ', edifact.getSegmentTerminator()); assertEquals('+', edifact.getDataElementSeparator()); assertEquals(':', edifact.getComponentElementSeparator()); assertEquals('.', edifact.getDecimalMark()); assertEquals('\0', edifact.getRepetitionSeparator()); assertEquals('\\', edifact.getReleaseIndicator()); } @Test void testDecimalMarkUsedPreVersion4() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+,\\* UNB+UNOA:3+111111111:1+222222222:1+200726:1455+1 ".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.initialize(characters)); assertFalse(edifact.isDecimalMark('.')); assertTrue(edifact.isDecimalMark(',')); } @Test void testBlankVersionUNA() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+.?*'UNB+".chars().forEach(c -> assertTrue(edifact.appendHeader(characters, (char) c))); assertFalse(edifact.appendHeader(characters, '+')); } @Test void testBlankVersionUNB() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNB".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNB++111111111:1+222222222:1+200726:1455+1".chars().forEach(c -> assertTrue(edifact.appendHeader(characters, (char) c))); assertFalse(edifact.appendHeader(characters, '\'')); } @Test void testInvalidState_HeaderUBN() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+.?*'".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.appendHeader(characters, 'U')); assertFalse(edifact.appendHeader(characters, 'B')); } @Test void testInvalidState_HeaderUNC() throws EDIException { EDIFACTDialect edifact = (EDIFACTDialect) DialectFactory.getDialect("UNA".toCharArray(), 0, 3); CharacterSet characters = new CharacterSet(); "UNA:+.?*'".chars().forEach(c -> edifact.appendHeader(characters, (char) c)); assertTrue(edifact.appendHeader(characters, 'U')); assertTrue(edifact.appendHeader(characters, 'N')); assertTrue(edifact.appendHeader(characters, 'C')); assertFalse(edifact.appendHeader(characters, '+')); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/tokenization/LexerTest.java
src/test/java/io/xlate/edi/internal/stream/tokenization/LexerTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream.tokenization; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.MalformedInputException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import io.xlate.edi.internal.stream.ConstantsTest; import io.xlate.edi.internal.stream.StaEDIStreamLocation; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; @SuppressWarnings("resource") class LexerTest { class TestLexerEventHandler implements EventHandler, ConstantsTest { final Map<String, Object> content = new HashMap<>(2); @Override public void interchangeBegin(Dialect dialect) { content.put("LAST", "interchangeBegin"); content.put("INTERCHANGE_START", true); } @Override public void interchangeEnd() { content.put("LAST", "interchangeEnd"); } @Override public void loopBegin(EDIReference typeReference) { content.put("LAST", "loopBegin"); } @Override public void loopEnd(EDIReference typeReference) { content.put("LAST", "loopEnd"); } @Override public boolean segmentBegin(String segmentTag) { content.put("LAST", "segmentBegin"); content.put("SEGMENT", segmentTag); return true; } @Override public boolean segmentEnd() { content.put("LAST", "segmentEnd"); return true; } @Override public boolean compositeBegin(boolean isNil, boolean derived) { content.put("LAST", "compositeBegin"); return true; } @Override public boolean compositeEnd(boolean isNil) { content.put("LAST", "compositeEnd"); return true; } @Override public boolean elementData(CharSequence text, boolean fromStream) { content.put("LAST", "elementData"); content.put("ELEMENT", text.toString()); return true; } @Override public boolean binaryData(InputStream binary) { return true; } @Override public void segmentError(CharSequence token, EDIReference typeReference, EDIStreamValidationError error) { } @Override public void elementError(EDIStreamEvent event, EDIStreamValidationError error, EDIReference typeReference, CharSequence data, int elem, int component, int repetition) { } } EventHandler handler = new EventHandler() { @Override public void interchangeBegin(Dialect dialect) { interchangeStarted = true; } @Override public void interchangeEnd() { interchangeEnded = true; } @Override public void loopBegin(EDIReference typeReference) { } @Override public void loopEnd(EDIReference typeReference) { } @Override public boolean segmentBegin(String segmentTag) { segment = segmentTag; return true; } @Override public boolean segmentEnd() { return true; } @Override public boolean compositeBegin(boolean isNil, boolean derived) { compositeStarted = true; return true; } @Override public boolean compositeEnd(boolean isNil) { compositeEnded = true; return true; } public boolean elementData(CharSequence text, boolean fromStream) { element = text.toString(); return true; } @Override public boolean binaryData(InputStream binary) { return true; } @Override public void segmentError(CharSequence token, EDIReference typeReference, EDIStreamValidationError error) { } @Override public void elementError(EDIStreamEvent event, EDIStreamValidationError error, EDIReference typeReference, CharSequence data, int elem, int component, int repetition) { } }; boolean interchangeStarted = false; boolean interchangeEnded = false; boolean compositeStarted = false; boolean compositeEnded = false; String segment; String element; @Test void testParseX12() throws EDIException, IOException { InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); interchangeStarted = false; interchangeEnded = false; compositeStarted = false; compositeEnded = false; segment = null; element = null; final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, handler, location, false); lexer.parse(); assertTrue(interchangeStarted, "Interchange not started"); lexer.parse(); assertEquals("ISA", segment, "ISA not received"); lexer.parse(); assertEquals("00", element, "00 not received"); } @Test void testParseEDIFACT() throws EDIException, IOException { InputStream stream = getClass().getResourceAsStream("/EDIFACT/invoic_d97b.edi"); interchangeStarted = false; interchangeEnded = false; compositeStarted = false; compositeEnded = false; segment = null; element = null; final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, handler, location, false); lexer.parse(); assertTrue(interchangeStarted, "Interchange not started"); lexer.parse(); assertEquals("UNB", segment, "UNB not received"); lexer.parse(); assertTrue(compositeStarted, "Composite not started"); lexer.parse(); assertEquals("UNOA", element, "UNOA not received"); } @Test void testParseTagsX12() throws EDIException, IOException { InputStream stream = getClass().getResourceAsStream("/x12/simple997.edi"); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); String last; int s = -1; do { lexer.parse(); last = (String) eventHandler.content.get("LAST"); if ("segmentBegin".equals(last)) { String tag = (String) eventHandler.content.get("SEGMENT"); if (++s < ConstantsTest.simple997tags.length) { assertEquals(ConstantsTest.simple997tags[s], tag, "Unexpected segment"); } else { fail("Unexpected segment: " + tag); } } } while (!"interchangeEnd".equals(last)); assertTrue(s > 0, "No events"); } @Test void testParseTagsEDIFACTA() throws EDIException, IOException { InputStream stream = getClass().getResourceAsStream("/EDIFACT/invoic_d97b_una.edi"); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); String last; int s = -1; do { lexer.parse(); last = (String) eventHandler.content.get("LAST"); if ("segmentBegin".equals(last)) { String tag = (String) eventHandler.content.get("SEGMENT"); if (++s < ConstantsTest.invoic_d97b_unatags.length) { assertEquals(ConstantsTest.invoic_d97b_unatags[s], tag, "Unexpected segment"); } else { fail("Unexpected segment: " + tag); } } } while (!"interchangeEnd".equals(last)); assertTrue(s > 0, "No events"); } @Test void testParseTagsEDIFACTB() throws EDIException, IOException { InputStream stream = getClass().getResourceAsStream("/EDIFACT/invoic_d97b.edi"); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); String last; int s = -1; do { lexer.parse(); last = (String) eventHandler.content.get("LAST"); if ("segmentBegin".equals(last)) { String tag = (String) eventHandler.content.get("SEGMENT"); if (++s < ConstantsTest.invoic_d97btags.length) { assertEquals(ConstantsTest.invoic_d97btags[s], tag, "Unexpected segment"); } else { fail("Unexpected segment: " + tag); } } } while (!"interchangeEnd".equals(last)); assertTrue(s > 0, "No events"); } @ParameterizedTest @CsvSource({ "X12 (bad element delimiter), ISA*00? *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~", "TRADACOMS (simple version), STX=1+5000000000000:SOME STORES LTD+5010000000000:SUPPLIER UK LTD+070315:130233+000007+PASSW+ORDHDR+B'" }) void testRejectedDialect(String dialect, String segment) { InputStream stream = new ByteArrayInputStream(segment.getBytes()); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); EDIException thrown = assertThrows(EDIException.class, lexer::parse); assertTrue(thrown.getMessage().contains("EDIE003")); } @Test void testInvalidCharacter() throws Exception { InputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "TA\u0008").getBytes()); // Backspace char in segment tag TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); for (int i = 0; i < 19; i++) { lexer.parse(); // Interchange start through end of ISA } EDIException thrown = assertThrows(EDIException.class, lexer::parse); assertTrue(thrown.getMessage().contains("EDIE004")); assertEquals(109, thrown.getLocation().copy().getCharacterOffset()); } @Test void testIncompleteInputText() throws Exception { InputStream stream = new ByteArrayInputStream("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~".getBytes()); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); for (int i = 0; i < 19; i++) { lexer.parse(); // Interchange start through end of ISA } EDIException thrown = assertThrows(EDIException.class, lexer::parse); assertTrue(thrown.getMessage().contains("EDIE005")); } @Test void testIncompleteInputTextEndingWithDoubleByteChar() throws Exception { byte[] data1 = "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~GS*".getBytes(); byte[] data2 = new byte[data1.length + 1]; System.arraycopy(data1, 0, data2, 0, data1.length); data2[data2.length - 1] = (byte) 195; InputStream stream = new ByteArrayInputStream(data2); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.UTF_8, eventHandler, location, false); for (int i = 0; i < 20; i++) { lexer.parse(); // Interchange start through end of ISA + GS start tag } EDIException thrown = assertThrows(EDIException.class, lexer::parse); assertTrue(thrown.getMessage().contains("EDIE005")); } @Test void testUnmappabledCharacter() throws EDIException, IOException { InputStream stream = new ByteArrayInputStream("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~😀".getBytes(StandardCharsets.UTF_8)); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.US_ASCII, eventHandler, location, false); for (int i = 0; i < 19; i++) { lexer.parse(); // Interchange start through end of ISA } MalformedInputException thrown = assertThrows(MalformedInputException.class, lexer::parse); assertEquals("Input length = 1", thrown.getMessage()); } @Test void testPreviousStateRetainedWhenInvalidateInvoked() { InputStream stream = new ByteArrayInputStream(new byte[0]); TestLexerEventHandler eventHandler = new TestLexerEventHandler(); final StaEDIStreamLocation location = new StaEDIStreamLocation(); final Lexer lexer = new Lexer(stream, StandardCharsets.US_ASCII, eventHandler, location, false); assertEquals(State.INITIAL, lexer.currentState()); assertNull(lexer.previousState()); for (int i = 0; i < 2; i++) { lexer.invalidate(); assertEquals(State.INVALID, lexer.currentState()); assertEquals(State.INITIAL, lexer.previousState()); } } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/ConditionSyntaxValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/ConditionSyntaxValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule.Type; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; class ConditionSyntaxValidatorTest extends SyntaxValidatorTestBase { ConditionSyntaxValidator validator; @BeforeEach void setUp() { validator = (ConditionSyntaxValidator) SyntaxValidator.getInstance(Type.CONDITIONAL); super.setUp(); } @Test void testValidateConditionalAllUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(true, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateConditionalAnchorUnused() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(true, 3)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateConditionalMissingRequired() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(false, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(1, count.get()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/DateValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/DateValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import io.xlate.edi.internal.stream.tokenization.CharacterSet; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.DialectFactory; import io.xlate.edi.internal.stream.tokenization.EDIException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.stream.EDIStreamValidationError; class DateValidatorTest implements ValueSetTester { Dialect dialect; DateValidator v; @BeforeEach void setUp() throws EDIException { dialect = DialectFactory.getDialect("UNA"); v = new DateValidator(); CharacterSet chars = new CharacterSet(); "UNA=*.?^~UNB*UNOA=3*005435656=1*006415160=1*060515=1434*00000000000778~".chars() .forEach(c -> dialect.appendHeader(chars, (char) c)); } @Test void testValidateLengthTooShort() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "0901", errors); assertEquals(2, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT, errors.get(0)); assertEquals(EDIStreamValidationError.INVALID_DATE, errors.get(1)); } @ParameterizedTest @ValueSource( strings = { "0901000" /* Length 7 */, "AAAA0901", "20001301" /* Invalid month*/ }) void testValidateInvalidValues(String param) { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, param, errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_DATE, errors.get(0)); } @Test void testValidateValidValue() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "20190901", errors); assertEquals(0, errors.size()); } @Test void testValidateSixDigitDate() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "191201", errors); assertEquals(0, errors.size()); } @Test void testValidateSixDigitDatePreviousCentury() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "991231", errors); v.validate(dialect, element, "990228", errors); assertEquals(0, errors.size()); } @Test void testValidateDayAfterMonthEnd() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "00000132", errors); v.validate(dialect, element, "00000431", errors); v.validate(dialect, element, "00000230", errors); v.validate(dialect, element, "00010229", errors); assertEquals(4, errors.size()); IntStream.range(0, 3).forEach(i -> assertEquals(EDIStreamValidationError.INVALID_DATE, errors.get(i))); } @Test void testValidateFebruaryLeapYears() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "20000229", errors); v.validate(dialect, element, "19960229", errors); assertEquals(0, errors.size()); v.validate(dialect, element, "19000229", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_DATE, errors.get(0)); } @Test void testFormatValueTooShort() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "20000", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT); } @Test void testFormatValueTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "200001011", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG); } @Test void testFormatInvalidDate() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "20000100", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.INVALID_DATE); } @Test void testFormatValidDate() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "20000101", output); assertEquals("20000101", output.toString()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/TimeValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/TimeValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.stream.tokenization.CharacterSet; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.DialectFactory; import io.xlate.edi.internal.stream.tokenization.EDIException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.stream.EDIStreamValidationError; class TimeValidatorTest implements ValueSetTester { Dialect dialect; TimeValidator v; @BeforeEach void setUp() throws EDIException { dialect = DialectFactory.getDialect("UNA"); v = new TimeValidator(); CharacterSet chars = new CharacterSet(); "UNA=*.?^~UNB*UNOA=3*005435656=1*006415160=1*060515=1434*00000000000778~".chars().forEach(c -> dialect.appendHeader(chars, (char) c)); } @Test void testValidateValueTooShort() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "09", errors); assertEquals(2, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT, errors.get(0)); assertEquals(EDIStreamValidationError.INVALID_TIME, errors.get(1)); } @Test void testValidateValueTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "1230599999", errors); assertEquals(2, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, errors.get(0)); assertEquals(EDIStreamValidationError.INVALID_TIME, errors.get(1)); } @Test void testValidateInvalidValue() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "123059AA", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_TIME, errors.get(0)); } @Test void testValidateInvalidPartialSeconds() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "12305", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_TIME, errors.get(0)); } @Test void testValidateValidValue() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "12305900", errors); assertEquals(0, errors.size()); } @Test void testValidateValidValueFractionalSeconds() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "1230591", errors); assertEquals(0, errors.size()); } @Test void testValidValues() { assertTrue(TimeValidator.validValue("003059")); assertTrue(TimeValidator.validValue("00305999")); } @Test void testInvalidValues() { assertFalse(TimeValidator.validValue("A03059")); assertFalse(TimeValidator.validValue("003060")); assertFalse(TimeValidator.validValue("006059")); assertFalse(TimeValidator.validValue("245959")); } @Test void testFormatValueTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); StringBuilder output = new StringBuilder(); v.format(dialect, element, "1230599999", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG); } @Test void testFormatInvalidTime() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); StringBuilder output = new StringBuilder(); v.format(dialect, element, "123059AA", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.INVALID_TIME); } @Test void testFormatValidTime() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); StringBuilder output = new StringBuilder(); v.format(dialect, element, "123059", output); assertEquals("123059", output.toString()); } @Test void testFormatValidTimePadded() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); StringBuilder output = new StringBuilder(); v.format(dialect, element, "1230", output); assertEquals("123000", output.toString()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/PairedSyntaxValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/PairedSyntaxValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule.Type; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; class PairedSyntaxValidatorTest extends SyntaxValidatorTestBase { PairedSyntaxValidator validator; @BeforeEach void setUp() { validator = (PairedSyntaxValidator) SyntaxValidator.getInstance(Type.PAIRED); super.setUp(); } @Test void testValidatePairedAllUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(true, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidatePairedNoneUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(false, 3), mockUsageNode(false, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidatePairedAnchorUnused() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode("E001", false, 1), mockUsageNode(false, 2), mockUsageNode(true, 3)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), argThat((arg -> arg == null || "E001".equals(arg.getReferencedType().getCode()))), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(2, count.get()); // Positions 1 and 4 unused } @Test void testValidatePairedMissingRequired() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(false, 3)/*, mockUsageNode(false, 4)*/); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(2, count.get()); // Error for both positions 3 and 4 } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/RequiredSyntaxValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/RequiredSyntaxValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule.Type; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; class RequiredSyntaxValidatorTest extends SyntaxValidatorTestBase { RequiredSyntaxValidator validator; @BeforeEach void setUp() { validator = (RequiredSyntaxValidator) SyntaxValidator.getInstance(Type.REQUIRED); super.setUp(); } @Test void testValidateRequiredAllUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(true, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateRequiredNoneUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode("E001", false, 1), mockUsageNode("E002", false, 2), mockUsageNode("E003", false, 3), mockUsageNode("E004", false, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), argThat(arg -> arg.getReferencedType().getCode().matches("E00[13-4]")), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(3, count.get()); } @Test void testValidateRequiredAnchorUnused() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(true, 3)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateRequiredNonmemberUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(true, 2), mockUsageNode(false, 3), mockUsageNode(false, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(3, count.get()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/NumericValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/NumericValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.stream.tokenization.CharacterSet; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.DialectFactory; import io.xlate.edi.internal.stream.tokenization.EDIException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.stream.EDIStreamValidationError; class NumericValidatorTest implements ValueSetTester { Dialect dialect; @BeforeEach void setUp() throws EDIException { dialect = DialectFactory.getDialect("UNA"); CharacterSet chars = new CharacterSet(); "UNA=*.?^~UNB*UNOA=3*005435656=1*006415160=1*060515=1434*00000000000778~".chars().forEach(c -> dialect.appendHeader(chars, (char) c)); } @Test void testValidateInvalidNegative() { assertEquals(-2, new NumericValidator().validate(dialect, "20-")); } @Test void testValidateValidNegative() { assertEquals(2, new NumericValidator().validate(dialect, "-20")); } @Test void testValidateLengthTooShort() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(5L); when(element.getMaxLength()).thenReturn(10L); when(element.getValueSet()).thenReturn(setOf()); ElementValidator v = new NumericValidator(); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "1234", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT, errors.get(0)); } @Test void testValidateLengthTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(5L); when(element.getMaxLength()).thenReturn(10L); when(element.getValueSet()).thenReturn(setOf()); ElementValidator v = new NumericValidator(); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "12345678901", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, errors.get(0)); } @Test void testValidateInvalidCharacter() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(5L); when(element.getMaxLength()).thenReturn(10L); when(element.getValueSet()).thenReturn(setOf()); ElementValidator v = new NumericValidator(); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "1234F", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_CHARACTER_DATA, errors.get(0)); } @Test void testFormatValueTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(5L); ElementValidator v = new NumericValidator(); StringBuilder output = new StringBuilder(); v.format(dialect, element, "123456", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG); } @Test void testFormatInvalidCharacterData() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(5L); ElementValidator v = new NumericValidator(); StringBuilder output = new StringBuilder(); v.format(dialect, element, "1234F", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.INVALID_CHARACTER_DATA); } @Test void testFormatValidNumber() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); ElementValidator v = new NumericValidator(); StringBuilder output = new StringBuilder(); v.format(dialect, element, "1234", output); assertEquals("1234", output.toString()); } @Test void testFormatValidNumberPadded() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(6L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf()); ElementValidator v = new NumericValidator(); StringBuilder output = new StringBuilder(); v.format(dialect, element, "123", output); assertEquals("000123", output.toString()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/DecimalValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/DecimalValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.stream.tokenization.CharacterSet; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.DialectFactory; import io.xlate.edi.internal.stream.tokenization.EDIException; class DecimalValidatorTest { Dialect dialectEdifact; Dialect dialectX12; @BeforeEach void setUp() throws EDIException { dialectEdifact = DialectFactory.getDialect("UNA"); CharacterSet charsEdifact = new CharacterSet(); "UNA=*,?^~UNB*UNOA=3*005435656=1*006415160=1*060515=1434*00000000000778~".chars().forEach(c -> dialectEdifact.appendHeader(charsEdifact, (char) c)); dialectX12 = DialectFactory.getDialect("ISA"); CharacterSet charsX12 = new CharacterSet(); "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~".chars().forEach(c -> dialectX12.appendHeader(charsX12, (char) c)); } @Test void testValidateInvalidNegative() { assertEquals(-2, new DecimalValidator().validate(dialectEdifact, "20-")); } @Test void testValidateValidNegative() { assertEquals(10, new DecimalValidator().validate(dialectEdifact, "-1234567890")); } @Test void testValidateValidDecimal() { assertEquals(4, new DecimalValidator().validate(dialectEdifact, "20,00")); assertEquals(4, new DecimalValidator().validate(dialectX12, "20.00")); } @Test void testValidateInvalidTooManyDecimalPoints() { assertEquals(-4, new DecimalValidator().validate(dialectEdifact, "20,00,")); assertEquals(-4, new DecimalValidator().validate(dialectX12, "20.00.")); } @Test void testValidateExponentialsValid() { DecimalValidator v = new DecimalValidator(); assertEquals(6, v.validate(dialectEdifact, "1,234E-56")); assertEquals(6, v.validate(dialectEdifact, "-1,234E-56")); assertEquals(2, v.validate(dialectEdifact, "1E2")); assertEquals(6, v.validate(dialectX12, "1.234E-56")); assertEquals(6, v.validate(dialectX12, "-1.234E-56")); assertEquals(2, v.validate(dialectX12, "1E2")); } @Test void testValidateExponentialsInvalid() { DecimalValidator v = new DecimalValidator(); assertEquals(-6, v.validate(dialectEdifact, "1,234E-5,6")); assertEquals(-6, v.validate(dialectEdifact, "-1,234E-5E-6")); assertEquals(-2, v.validate(dialectEdifact, "1E--2,")); assertEquals(-6, v.validate(dialectEdifact, "1E,234E-5,6")); assertEquals(-6, v.validate(dialectX12, "1.234E-5.6")); assertEquals(-6, v.validate(dialectX12, "-1.234E-5E-6")); assertEquals(-2, v.validate(dialectX12, "1E--2.")); assertEquals(-6, v.validate(dialectX12, "1E.234E-5.6")); } @Test void testValidateBadExponentialCharacter() { DecimalValidator v = new DecimalValidator(); assertEquals(-7, v.validate(dialectEdifact, "1,234e56")); assertEquals(-7, v.validate(dialectX12, "1.234e56")); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/ValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/ValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIStreamConstants.Standards; class ValidatorTest { static final ValidatorConfig CONFIG = new ValidatorConfig() { @Override public boolean validateControlCodeValues() { return true; } @Override public boolean formatElements() { return false; } @Override public boolean trimDiscriminatorValues() { return false; } }; @Test void testValidatorRootAttributes() throws EDISchemaException { SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.getControlSchema(Standards.X12, new String[] { "00801" }); Validator validator = new Validator(schema, null, CONFIG); EDIReference interchangeReference = validator.root.getLink(); assertSame(schema.getStandard(), interchangeReference.getReferencedType()); assertEquals(1, interchangeReference.getMinOccurs()); assertEquals(1, interchangeReference.getMaxOccurs()); // Title value specified in v00704.xml schema assertEquals("X12 Interchange (minimum version 00704)", interchangeReference.getTitle()); // No description specified in schema assertNull(interchangeReference.getDescription()); } @Test void testValidatorRootNoParent() throws EDISchemaException { SchemaFactory schemaFactory = SchemaFactory.newFactory(); Schema schema = schemaFactory.getControlSchema(Standards.X12, new String[] { "00801" }); Validator validator = new Validator(schema, null, CONFIG); UsageNode root = validator.root; assertNull(root.getParent()); assertNull(root.getFirstSibling()); assertNull(root.getNextSibling()); assertNull(root.getSiblingById("TEST")); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/SingleSyntaxValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/SingleSyntaxValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule.Type; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; class SingleSyntaxValidatorTest extends SyntaxValidatorTestBase { SingleSyntaxValidator validator; @BeforeEach void setUp() { validator = (SingleSyntaxValidator) SyntaxValidator.getInstance(Type.SINGLE); super.setUp(); } @Test void testValidateExclusionAllUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(true, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), any(EDIStreamValidationError.class), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(2, count.get()); } @Test void testValidateExclusionNonAnchorUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(true, 3)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), any(EDIStreamValidationError.class), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateExclusionNoneUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(false, 3)/*, mockUsageNode(false, 4)*/); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(3, count.get()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/SyntaxValidatorTestBase.java
src/test/java/io/xlate/edi/internal/stream/validation/SyntaxValidatorTestBase.java
package io.xlate.edi.internal.stream.validation; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.jupiter.api.BeforeEach; import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule; import io.xlate.edi.schema.EDIType; abstract class SyntaxValidatorTestBase { protected EDISyntaxRule syntax; protected ValidationEventHandler handler; protected UsageNode structure; protected EDIReference structureRef; protected EDIType structureType; @BeforeEach void setUp() { syntax = mock(EDISyntaxRule.class); handler = mock(ValidationEventHandler.class); structureType = mock(EDIType.class); when(structureType.getType()).thenReturn(EDIType.Type.SEGMENT); structureRef = mock(EDIReference.class); when(structureRef.getReferencedType()).thenReturn(structureType); structure = mock(UsageNode.class); when(structure.isNodeType(EDIType.Type.SEGMENT, EDIType.Type.COMPOSITE)).thenReturn(true); when(structure.isNodeType(EDIType.Type.SEGMENT)).thenReturn(true); } protected UsageNode mockUsageNode(String referenceCode, boolean used, int index) { UsageNode node = mock(UsageNode.class); EDIReference typeReference = mock(EDIReference.class); EDIType type = mock(EDIType.class); when(type.getCode()).thenReturn(referenceCode); when(typeReference.getReferencedType()).thenReturn(type); when(node.getLink()).thenReturn(typeReference); when(node.isUsed()).thenReturn(used); when(node.getIndex()).thenReturn(index); return node; } protected UsageNode mockUsageNode(boolean used, int index) { return mockUsageNode(null, used, index); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/ValueSetTester.java
src/test/java/io/xlate/edi/internal/stream/validation/ValueSetTester.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.stream.EDIStreamValidationError; interface ValueSetTester { default Set<String> setOf() { return Collections.emptySet(); } default Set<String> setOf(String... values) { return new HashSet<>(Arrays.asList(values)); } default Map<String, String> mapOf(String... values) { Map<String, String> map = new HashMap<>(values.length / 2); for (int i = 0; i < values.length; i+=2) { map.put(values[i], values[i + 1]); } return map; } default void assertHasError(ElementValidator v, Dialect dialect, EDISimpleType element, CharSequence value, EDIStreamValidationError expected) { List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, value, errors); assertTrue(errors.contains(expected)); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/ExclusionSyntaxValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/ExclusionSyntaxValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule.Type; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; class ExclusionSyntaxValidatorTest extends SyntaxValidatorTestBase { ExclusionSyntaxValidator validator; @BeforeEach void setUp() { validator = (ExclusionSyntaxValidator) SyntaxValidator.getInstance(Type.EXCLUSION); super.setUp(); } @Test void testValidateExclusionAllUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(true, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.EXCLUSION_CONDITION_VIOLATED), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(2, count.get()); } @Test void testValidateExclusionNonAnchorUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(true, 3)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.EXCLUSION_CONDITION_VIOLATED), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateExclusionNoneUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(false, 3)/*, mockUsageNode(false, 4)*/); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.EXCLUSION_CONDITION_VIOLATED), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/AlphaNumericValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/AlphaNumericValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.stream.tokenization.CharacterSet; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.DialectFactory; import io.xlate.edi.internal.stream.tokenization.EDIException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.stream.EDIStreamValidationError; class AlphaNumericValidatorTest implements ValueSetTester { Dialect dialect; AlphaNumericValidator v; @BeforeEach void setUp() throws EDIException { dialect = DialectFactory.getDialect("UNA"); v = new AlphaNumericValidator(); CharacterSet chars = new CharacterSet(); "UNA=*.?^~UNB*UNOA=3*005435656=1*006415160=1*060515=1434*00000000000778~".chars().forEach(c -> dialect.appendHeader(chars, (char) c)); } @Test void testValidateLengthTooShort() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(5L); when(element.getMaxLength()).thenReturn(5L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "TEST", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_SHORT, errors.get(0)); } @Test void testValidateLengthTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(5L); when(element.getMaxLength()).thenReturn(5L); when(element.getValueSet()).thenReturn(setOf()); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "TESTTEST", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.DATA_ELEMENT_TOO_LONG, errors.get(0)); } @Test void testValidateValueNotInSet() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getValues(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(5L); when(element.getValues()).thenReturn(mapOf("VAL1", "Title1", "VAL2", "Title2")); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "TEST", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_CODE_VALUE, errors.get(0)); } @Test void testValidateValueInSetBadCharacter() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(5L); when(element.getValueSet()).thenReturn(setOf("VAL1", "VAL\u0008")); List<EDIStreamValidationError> errors = new ArrayList<>(); v.validate(dialect, element, "VAL\u0008", errors); assertEquals(1, errors.size()); assertEquals(EDIStreamValidationError.INVALID_CHARACTER_DATA, errors.get(0)); } @Test void testFormatValueTooLong() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(5L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "TESTTEST", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.DATA_ELEMENT_TOO_LONG); } @Test void testFormatValueNotInSet() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getValues(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValues()).thenReturn(mapOf("VAL1", "Title1", "VAL2", "Title2")); StringBuilder output = new StringBuilder(); v.format(dialect, element, "TESTTEST", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.INVALID_CODE_VALUE); } @Test void testFormatValueInSet() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(8L); when(element.getValueSet()).thenReturn(setOf("VAL1", "VAL2")); StringBuilder output = new StringBuilder(); v.format(dialect, element, "VAL1", output); assertEquals("VAL1", output.toString()); } @Test void testFormatInvalidCharacterData() { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(4L); when(element.getMaxLength()).thenReturn(4L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "TES\u0008", output); assertHasError(v, dialect, element, output, EDIStreamValidationError.INVALID_CHARACTER_DATA); } @Test void testFormatValidValuePaddedLength() throws EDIException { EDISimpleType element = mock(EDISimpleType.class); when(element.getMinLength(anyString())).thenCallRealMethod(); when(element.getMaxLength(anyString())).thenCallRealMethod(); when(element.getValueSet(anyString())).thenCallRealMethod(); when(element.getMinLength()).thenReturn(10L); when(element.getMaxLength()).thenReturn(10L); StringBuilder output = new StringBuilder(); v.format(dialect, element, "TEST", output); assertEquals("TEST ", output.toString()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/validation/ListSyntaxValidatorTest.java
src/test/java/io/xlate/edi/internal/stream/validation/ListSyntaxValidatorTest.java
package io.xlate.edi.internal.stream.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.stubbing.Answer; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule.Type; import io.xlate.edi.schema.EDIType; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamValidationError; class ListSyntaxValidatorTest extends SyntaxValidatorTestBase { ListSyntaxValidator validator; @BeforeEach void setUp() { validator = (ListSyntaxValidator) SyntaxValidator.getInstance(Type.LIST); super.setUp(); } @Test void testValidateListConditionalAllUsed() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(true, 3), mockUsageNode(true, 4)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateListConditionalAnchorUnused() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(false, 1), mockUsageNode(false, 2), mockUsageNode(true, 3)); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(0, count.get()); } @Test void testValidateListConditionalMissingRequired() { when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(false, 3)/*, mockUsageNode(false, 4)*/); when(structure.getChildren()).thenReturn(children); final AtomicInteger count = new AtomicInteger(0); doAnswer((Answer<Void>) invocation -> { count.incrementAndGet(); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), any(Integer.class), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(2, count.get()); // Error for both positions 3 and 4 } @Test void testValidateListConditionalMissingRequired_Composite() { when(structure.isNodeType(EDIType.Type.COMPOSITE)).thenReturn(true); when(structure.getIndex()).thenReturn(2); // composite is the third element in the parent segment when(syntax.getPositions()).thenReturn(Arrays.asList(1, 3, 4)); List<UsageNode> children = Arrays.asList(mockUsageNode(true, 1), mockUsageNode(false, 2), mockUsageNode(false, 3)/*, mockUsageNode(false, 4)*/); when(structure.getChildren()).thenReturn(children); final List<Integer> elements = new ArrayList<>(); doAnswer((Answer<Void>) invocation -> { elements.add(invocation.getArgument(5)); return null; }).when(handler) .elementError(eq(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), eq(EDIStreamValidationError.CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING), nullable(EDIReference.class), nullable(CharSequence.class), eq(3), any(Integer.class), any(Integer.class)); validator.validate(syntax, structure, handler); assertEquals(2, elements.size()); // Error for both positions 3 and 4 assertEquals(3, elements.get(0)); assertEquals(4, elements.get(1)); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/json/StaEDIJsonParserTest.java
src/test/java/io/xlate/edi/internal/stream/json/StaEDIJsonParserTest.java
package io.xlate.edi.internal.stream.json; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jakarta.json.Json; import jakarta.json.stream.JsonGenerator; import jakarta.json.stream.JsonParser; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.skyscreamer.jsonassert.JSONAssert; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIValidationException; import io.xlate.edi.test.StaEDIReaderTestBase; class StaEDIJsonParserTest extends StaEDIReaderTestBase implements JsonParserInvoker { void copyParserToGenerator(EDIStreamReader ediReader, Object jsonParser, OutputStream buffer) throws Throwable { Map<String, Object> jsonConfig = new HashMap<>(); jsonConfig.put(JsonGenerator.PRETTY_PRINTING, Boolean.TRUE); JsonGenerator jsonGenerator = Json.createGeneratorFactory(jsonConfig).createGenerator(buffer); while (invoke(jsonParser, "hasNext", Boolean.class)) { String eventName = invoke(jsonParser, "next", Object.class).toString(); switch (eventName) { case "END_ARRAY": jsonGenerator.writeEnd(); break; case "END_OBJECT": jsonGenerator.writeEnd(); break; case "FIELD_NAME": // Jackson only assertTrue(invoke(jsonParser, "hasTextCharacters", Boolean.class)); // fall-through case "KEY_NAME": jsonGenerator.writeKey(invoke(jsonParser, "getString", String.class)); break; case "START_ARRAY": jsonGenerator.writeStartArray(); break; case "START_OBJECT": jsonGenerator.writeStartObject(); break; case "VALUE_NULL": jsonGenerator.writeNull(); break; case "VALUE_NUMBER": if (invoke(jsonParser, "isIntegralNumber", Boolean.class)) { jsonGenerator.write(invoke(jsonParser, "getLong", Long.class)); } else { jsonGenerator.write(invoke(jsonParser, "getBigDecimal", BigDecimal.class)); } break; case "VALUE_NUMBER_INT": // Jackson only assertFalse(invoke(jsonParser, "hasTextCharacters", Boolean.class)); jsonGenerator.write(invoke(jsonParser, "getLongValue", Long.class)); break; case "VALUE_NUMBER_FLOAT": // Jackson only assertFalse(invoke(jsonParser, "hasTextCharacters", Boolean.class)); jsonGenerator.write(invoke(jsonParser, "getDecimalValue", BigDecimal.class)); break; case "VALUE_STRING": jsonGenerator.write(invoke(jsonParser, "getString", String.class)); break; default: fail("Unexpected event type: " + eventName); } jsonGenerator.flush(); Object location = invoke(jsonParser, "getLocation", Object.class); assertEquals(ediReader.getLocation().getCharacterOffset(), invoke(location, "getStreamOffset", Long.class)); assertEquals(ediReader.getLocation().getLineNumber(), invoke(location, "getLineNumber", Long.class)); assertEquals(ediReader.getLocation().getColumnNumber(), invoke(location, "getColumnNumber", Long.class)); } invoke(jsonParser, "close", Void.class); jsonGenerator.close(); } @Test void testInvalidParserType() { EDIInputFactory factory = EDIInputFactory.newFactory(); IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> factory.createJsonParser(null, Object.class)); assertEquals("Unsupported JSON parser type: " + Object.class.toString(), thrown.getMessage()); } @ParameterizedTest @CsvSource({ "jakarta.json.stream.JsonParser, /x12/005010/837.xml, false, /x12/sample837-original.json", "jakarta.json.stream.JsonParser, /x12/005010/837.xml, true, /x12/sample837-original.json", "jakarta.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, true, /x12/sample837-original-nestHL.json", "jakarta.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, false, /x12/sample837-original.json", "javax.json.stream.JsonParser, /x12/005010/837.xml, false, /x12/sample837-original.json", "javax.json.stream.JsonParser, /x12/005010/837.xml, true, /x12/sample837-original.json", "javax.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, true, /x12/sample837-original-nestHL.json", "javax.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, false, /x12/sample837-original.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837.xml, false, /x12/sample837-original.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837.xml, true, /x12/sample837-original.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, true, /x12/sample837-original-nestHL.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, false, /x12/sample837-original.json" }) void testNullElementsAsArray(Class<?> parserInterface, String schemaPath, boolean nestHL, String expectedResource) throws Throwable { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); ediReaderConfig.put(EDIInputFactory.EDI_NEST_HIERARCHICAL_LOOPS, nestHL); setupReader("/x12/sample837-original.edi", schemaPath); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Object jsonParser = ediInputFactory.createJsonParser(ediReader, parserInterface); copyParserToGenerator(ediReader, jsonParser, buffer); List<String> expected = Files.readAllLines(Paths.get(getClass().getResource(expectedResource).toURI())); System.out.println(buffer.toString()); JSONAssert.assertEquals(String.join("", expected), buffer.toString(), true); } @ParameterizedTest @CsvSource({ "jakarta.json.stream.JsonParser, /x12/005010/837.xml, false, /x12/sample837-original-object-elements.json", "jakarta.json.stream.JsonParser, /x12/005010/837.xml, true, /x12/sample837-original-object-elements.json", "jakarta.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, true, /x12/sample837-original-object-elements-nestHL.json", "jakarta.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, false, /x12/sample837-original-object-elements.json", "javax.json.stream.JsonParser, /x12/005010/837.xml, false, /x12/sample837-original-object-elements.json", "javax.json.stream.JsonParser, /x12/005010/837.xml, true, /x12/sample837-original-object-elements.json", "javax.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, true, /x12/sample837-original-object-elements-nestHL.json", "javax.json.stream.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, false, /x12/sample837-original-object-elements.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837.xml, false, /x12/sample837-original-object-elements.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837.xml, true, /x12/sample837-original-object-elements.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, true, /x12/sample837-original-object-elements-nestHL.json", "com.fasterxml.jackson.core.JsonParser, /x12/005010/837-hierarchical-level-enabled.xml, false, /x12/sample837-original-object-elements.json" }) void testElementsAsObjects(Class<?> parserInterface, String schemaPath, boolean nestHL, String expectedResource) throws Throwable { ediReaderConfig.put(EDIInputFactory.JSON_OBJECT_ELEMENTS, true); ediReaderConfig.put(EDIInputFactory.EDI_NEST_HIERARCHICAL_LOOPS, nestHL); setupReader("/x12/sample837-original.edi", schemaPath); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); copyParserToGenerator(ediReader, jsonParser, buffer); List<String> expected = Files.readAllLines(Paths.get(getClass().getResource(expectedResource).toURI())); System.out.println(buffer.toString()); JSONAssert.assertEquals(String.join("", expected), buffer.toString(), true); } @ParameterizedTest @CsvSource({ "jakarta.json.stream.JsonParser, jakarta.json.JsonObject, /x12/005010/837.xml, false, true, /x12/sample837-original-object-elements.json", "jakarta.json.stream.JsonParser, jakarta.json.JsonObject, /x12/005010/837.xml, true, true, /x12/sample837-original-object-elements.json", "jakarta.json.stream.JsonParser, jakarta.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, true, true, /x12/sample837-original-object-elements-nestHL.json", "jakarta.json.stream.JsonParser, jakarta.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, false, true, /x12/sample837-original-object-elements.json", "jakarta.json.stream.JsonParser, jakarta.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, true, false, /x12/sample837-original-nestHL.json", "jakarta.json.stream.JsonParser, jakarta.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, false, false, /x12/sample837-original.json", "javax.json.stream.JsonParser, javax.json.JsonObject, /x12/005010/837.xml, false, true, /x12/sample837-original-object-elements.json", "javax.json.stream.JsonParser, javax.json.JsonObject, /x12/005010/837.xml, true, true, /x12/sample837-original-object-elements.json", "javax.json.stream.JsonParser, javax.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, true, true, /x12/sample837-original-object-elements-nestHL.json", "javax.json.stream.JsonParser, javax.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, false, true, /x12/sample837-original-object-elements.json", "javax.json.stream.JsonParser, javax.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, true, false, /x12/sample837-original-nestHL.json", "javax.json.stream.JsonParser, javax.json.JsonObject, /x12/005010/837-hierarchical-level-enabled.xml, false, false, /x12/sample837-original.json" }) <P, O> void testInputAsJsonObject(Class<P> parserInterface, Class<O> resultInterface, String schemaPath, boolean nestHL, boolean objectElements, String expectedResource) throws Throwable { ediReaderConfig.put(EDIInputFactory.EDI_NEST_HIERARCHICAL_LOOPS, nestHL); ediReaderConfig.put(EDIInputFactory.JSON_OBJECT_ELEMENTS, objectElements); ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, !objectElements); setupReader("/x12/sample837-original.edi", schemaPath); P jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); String eventName = invoke(jsonParser, "next", Object.class).toString(); assertEquals("START_OBJECT", eventName); O result = invoke(jsonParser, "getObject", resultInterface); JsonParser parser = Json.createParser(getClass().getResourceAsStream(expectedResource)); parser.next(); assertEquals(parser.getObject().toString(), result.toString()); IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> invoke(jsonParser, "getValue", resultInterface)); assertEquals("getValue illegal when at current position", thrown.getMessage()); } @ParameterizedTest @CsvSource({ "jakarta.json.stream.JsonParser, getArray, getArray illegal when not at start of array", "jakarta.json.stream.JsonParser, getObject, getObject illegal when not at start of object", "jakarta.json.stream.JsonParser, getValue, getValue illegal when data stream has not yet been read", "javax.json.stream.JsonParser, getArray, getArray illegal when not at start of array", "javax.json.stream.JsonParser, getObject, getObject illegal when not at start of object", "javax.json.stream.JsonParser, getValue, getValue illegal when data stream has not yet been read" }) void testGetStructureIllegalAtStart(Class<?> parserInterface, String structureMethod, String message) throws Throwable { setupReader("/x12/simple810.edi", "/x12/EDISchema810.xml"); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> invoke(jsonParser, structureMethod, Object.class)); assertEquals(message, thrown.getMessage()); } @ParameterizedTest @ValueSource( classes = { jakarta.json.stream.JsonParser.class, javax.json.stream.JsonParser.class }) void testNumbersAllComparable(Class<?> parserInterface) throws Throwable { setupReader("/x12/simple810.edi", "/x12/EDISchema810.xml"); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); while (invoke(jsonParser, "hasNext", Boolean.class)) { String eventName = invoke(jsonParser, "next", Object.class).toString(); switch (eventName) { case "VALUE_NUMBER": int intValue = invoke(jsonParser, "getInt", Integer.class); long longValue = invoke(jsonParser, "getLong", Long.class); BigDecimal decimalValue = invoke(jsonParser, "getBigDecimal", BigDecimal.class); assertEquals(longValue, intValue); if (invoke(jsonParser, "isIntegralNumber", Boolean.class)) { assertEquals(0, decimalValue.compareTo(BigDecimal.valueOf(intValue)), decimalValue + " failed comparison with " + intValue); assertEquals(0, decimalValue.compareTo(BigDecimal.valueOf(longValue)), decimalValue + " failed comparison with " + longValue); } else { assertEquals(decimalValue.longValue(), intValue, decimalValue + " failed comparison with " + intValue); assertEquals(decimalValue.longValue(), longValue, decimalValue + " failed comparison with " + longValue); } break; default: break; } } invoke(jsonParser, "close", Void.class); } @ParameterizedTest @ValueSource( classes = { jakarta.json.stream.JsonParser.class, javax.json.stream.JsonParser.class, com.fasterxml.jackson.core.JsonParser.class }) void testTextStatesNotIllegal(Class<?> parserInterface) throws Throwable { setupReader("/x12/sample837-original.edi", "/x12/005010/837.xml"); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); while (invoke(jsonParser, "hasNext", Boolean.class)) { String eventName = invoke(jsonParser, "next", Object.class).toString(); switch (eventName) { case "KEY_NAME": case "FIELD_NAME": // Jackson only case "VALUE_STRING": case "VALUE_NUMBER": case "VALUE_NUMBER_INT": // Jackson only case "VALUE_NUMBER_FLOAT": // Jackson only assertDoesNotThrow(() -> invoke(jsonParser, "getString", String.class)); break; default: assertThrows(IllegalStateException.class, () -> invoke(jsonParser, "getString", String.class)); break; } } invoke(jsonParser, "close", Void.class); } @ParameterizedTest @ValueSource( classes = { jakarta.json.stream.JsonParser.class, javax.json.stream.JsonParser.class, com.fasterxml.jackson.core.JsonParser.class }) void testTextStatesIllegalForNumber(Class<?> parserInterface) throws Throwable { setupReader("/x12/sample837-original.edi", "/x12/005010/837.xml"); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); while (invoke(jsonParser, "hasNext", Boolean.class)) { String eventName = invoke(jsonParser, "next", Object.class).toString(); switch (eventName) { case "VALUE_NUMBER": case "VALUE_NUMBER_INT": // Jackson only case "VALUE_NUMBER_FLOAT": // Jackson only assertDoesNotThrow(() -> invoke(jsonParser, "getInt", Integer.class)); break; default: assertThrows(IllegalStateException.class, () -> invoke(jsonParser, "getInt", Integer.class)); break; } } invoke(jsonParser, "close", Void.class); } @ParameterizedTest @ValueSource( classes = { jakarta.json.stream.JsonParser.class, javax.json.stream.JsonParser.class, com.fasterxml.jackson.core.JsonParser.class }) void testInvalidNumberThrowsException(Class<?> parserInterface) throws Throwable { setupReader("/x12/invalid997_min.edi", null); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); List<Exception> errors = new ArrayList<>(); while (invoke(jsonParser, "hasNext", Boolean.class)) { try { invoke(jsonParser, "next", Object.class).toString(); } catch (Exception e) { errors.add(e); } } invoke(jsonParser, "close", Void.class); assertEquals(5, errors.size()); /* * 1 Invalid GS time * 2 invalid GS date * 3 GE02 too long * 4 GE02 invalid chars * 5 GE02 does not match GS06 */ // GS date reported after time due to version of GS date element selected EDIValidationException cause = (EDIValidationException) errors.get(3).getCause(); assertEquals("GE", cause.getLocation().getSegmentTag()); assertEquals(2, cause.getLocation().getElementPosition()); } @ParameterizedTest @CsvSource({ "jakarta.json.stream.JsonParser , jakarta.json.JsonException", "javax.json.stream.JsonParser , javax.json.JsonException", "com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.core.JsonParseException" }) void testIOExceptionThrowsCorrectJsonException(String parserName, String exceptionName) throws Throwable { InputStream stream = getClass().getResourceAsStream("/x12/sample837-original.edi"); ediReaderConfig.forEach(ediInputFactory::setProperty); ediReader = ediInputFactory.createEDIStreamReader(new FilterInputStream(stream) { @Override public int read() throws IOException { if (ediReader.getLocation().getCharacterOffset() > 50) { throw new IOException("Fatal stream error"); } return super.read(); } }); Class<?> parserInterface = Class.forName(parserName); Class<?> exceptionType = Class.forName(exceptionName); Object jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); List<Exception> errors = new ArrayList<>(); while (invoke(jsonParser, "hasNext", Boolean.class)) { try { invoke(jsonParser, "next", Object.class).toString(); } catch (Exception e) { errors.add(e); break; } } assertEquals(1, errors.size()); assertEquals(exceptionType, errors.get(0).getClass()); } @ParameterizedTest @ValueSource( classes = { jakarta.json.stream.JsonParser.class, javax.json.stream.JsonParser.class, com.fasterxml.jackson.core.JsonParser.class }) <T> void testBinaryDataReadAsEncodedString(Class<T> parserInterface) throws Throwable { ediReaderConfig.forEach(ediInputFactory::setProperty); setupReader("/x12/simple_with_binary_segment.edi", "/x12/EDISchemaBinarySegment.xml"); T jsonParser = JsonParserFactory.createJsonParser(ediReader, parserInterface, ediReaderConfig); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); copyParserToGenerator(ediReader, jsonParser, buffer); List<String> expected = Files.readAllLines(Paths.get(getClass().getResource("/x12/simple_with_binary_segment.json").toURI())); System.out.println(buffer.toString()); JSONAssert.assertEquals(String.join("", expected), buffer.toString(), true); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/json/JsonParserInvoker.java
src/test/java/io/xlate/edi/internal/stream/json/JsonParserInvoker.java
package io.xlate.edi.internal.stream.json; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.stream.Stream; interface JsonParserInvoker { @SuppressWarnings("unchecked") default <T> T invoke(Object instance, String methodName, Class<T> returnType) throws Throwable { Class<?> clazz = instance.getClass(); try { Method method = Stream.of(clazz.getMethods(), clazz.getDeclaredMethods()) .flatMap(Arrays::stream) .filter(m -> m.getName().equals(methodName)) .filter(m -> m.getParameterCount() == 0) .findFirst() .orElseThrow(() -> new NoSuchMethodException(methodName)); return (T) method.invoke(instance); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException(e); } } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/stream/json/StaEDIJacksonJsonParserTest.java
src/test/java/io/xlate/edi/internal/stream/json/StaEDIJacksonJsonParserTest.java
package io.xlate.edi.internal.stream.json; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.skyscreamer.jsonassert.JSONAssert; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonParser.NumberType; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.test.StaEDIReaderTestBase; class StaEDIJacksonJsonParserTest extends StaEDIReaderTestBase implements JsonParserInvoker { static byte[] TINY_X12 = ("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "IEA*1*508121953~").getBytes(); @Test void testJacksonParserVersion() throws Throwable { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); setupReader(TINY_X12, null); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); Version version = jsonParser.version(); assertNotNull(version); assertFalse(version.isUnknownVersion()); } @Test void testReadValueAsTree() throws Throwable { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); setupReader("/x12/sample837-original.edi", "/x12/005010/837.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); assertFalse(jsonParser.isClosed()); jsonParser.setCodec(new ObjectMapper()); JsonNode tree = jsonParser.readValueAsTree(); assertNotNull(tree); assertNull(jsonParser.nextToken()); jsonParser.close(); assertTrue(jsonParser.isClosed()); List<String> expected = Files.readAllLines(Paths.get(getClass().getResource("/x12/sample837-original.json").toURI())); JSONAssert.assertEquals(String.join("", expected), tree.toString(), true); } @ParameterizedTest @CsvSource({ " 1 , INT , java.lang.Integer , getIntValue", " -1 , INT , java.lang.Integer , getIntValue", " 9999999999 , LONG , java.lang.Long , getLongValue", " -9999999999 , LONG , java.lang.Long , getLongValue", " 99999999999999999999 , BIG_INTEGER, java.math.BigInteger, getBigIntegerValue", "-99999999999999999999 , BIG_INTEGER, java.math.BigInteger, getBigIntegerValue", }) <T> void testNumericTypes(String inputValue, NumberType expectedType, Class<T> expectedClass, String directMethod) throws Throwable { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); setupReader(("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*AA*ReceiverDept*SenderDept*20200101*000000*1*X*005010~\n" + "ST*000*0001*005010~\n" + String.format("INT*%s~", inputValue) + "FLT*1~" + "SE*4*0001~\n" + "GE*1*1~\n" + "IEA*1*508121953~").getBytes(), "/x12/EDISchema000-numeric-types.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); JsonToken token; boolean matched = false; while ((token = jsonParser.nextToken()) != null) { String pointer = jsonParser.getParsingContext().pathAsPointer().toString(); if ("/data/1/data/1/data/1/data/0".equals(pointer)) { matched = true; assertEquals(JsonToken.VALUE_NUMBER_INT, token); assertEquals(expectedType, jsonParser.getNumberType()); Number actualValue = jsonParser.getNumberValue(); assertEquals(expectedClass, actualValue.getClass()); assertEquals(inputValue, String.valueOf(actualValue)); T directValue = invoke(jsonParser, directMethod, expectedClass); assertEquals(actualValue, directValue); } } assertTrue(matched); } @ParameterizedTest @CsvSource({ "1, 1, FLOAT, java.lang.Float, getFloatValue", "34028234663852886, 38, DOUBLE, java.lang.Double, getDoubleValue", "18976931348623157, 308, BIG_DECIMAL, java.math.BigDecimal, getDecimalValue", }) <T> void testDecimalTypesLargeValue(String prefix, int exp, NumberType expectedType, Class<T> expectedClass, String directMethod) throws Throwable { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); BigDecimal inputValue = new BigDecimal(prefix + String.join("", Collections.nCopies(exp, "0")) + ".1"); setupReader(("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*AA*ReceiverDept*SenderDept*20200101*000000*1*X*005010~\n" + "ST*000*0001*005010~\n" + "INT*1~" + String.format("FLT*%s~", inputValue.toPlainString()) + "SE*4*0001~\n" + "GE*1*1~\n" + "IEA*1*508121953~").getBytes(), "/x12/EDISchema000-numeric-types.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); JsonToken token; boolean matched = false; while ((token = jsonParser.nextToken()) != null) { String pointer = jsonParser.getParsingContext().pathAsPointer().toString(); if ("/data/1/data/1/data/2/data/0".equals(pointer)) { matched = true; assertEquals(JsonToken.VALUE_NUMBER_FLOAT, token); assertEquals(expectedType, jsonParser.getNumberType()); Number actualValue = jsonParser.getNumberValue(); assertEquals(expectedClass, actualValue.getClass()); T directValue = invoke(jsonParser, directMethod, expectedClass); assertEquals(actualValue, directValue); } } assertTrue(matched); } @ParameterizedTest @CsvSource({ "1, FLOAT, java.lang.Float", "128, DOUBLE, java.lang.Double", "1024, BIG_DECIMAL, java.math.BigDecimal", "-1, FLOAT, java.lang.Float", "-128, DOUBLE, java.lang.Double", "-1024, BIG_DECIMAL, java.math.BigDecimal", }) void testDecimalTypesLargeExponent(int exp, NumberType expectedType, Class<?> expectedClass) throws Exception { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); BigDecimal inputValue; if (exp > 0) { inputValue = new BigDecimal("1" + String.join("", Collections.nCopies(exp, "0")) + ".1"); } else { inputValue = new BigDecimal("0." + String.join("", Collections.nCopies(Math.abs(exp), "0")) + "1"); } setupReader(("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*AA*ReceiverDept*SenderDept*20200101*000000*1*X*005010~\n" + "ST*000*0001*005010~\n" + "INT*1~" + String.format("FLT*%s~", inputValue.toPlainString()) + "SE*4*0001~\n" + "GE*1*1~\n" + "IEA*1*508121953~").getBytes(), "/x12/EDISchema000-numeric-types.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); JsonToken token; boolean matched = false; while ((token = jsonParser.nextToken()) != null) { String pointer = jsonParser.getParsingContext().pathAsPointer().toString(); if ("/data/1/data/1/data/2/data".equals(pointer)) { // Segment FLT assertNull(jsonParser.getNumberType()); assertThrows(JsonParseException.class, () -> jsonParser.getNumberValue()); } if ("/data/1/data/1/data/2/data/0".equals(pointer)) { // Element FLT01 matched = true; assertEquals(JsonToken.VALUE_NUMBER_FLOAT, token); assertEquals(expectedType, jsonParser.getNumberType()); Number actualValue = jsonParser.getNumberValue(); assertEquals(expectedClass, actualValue.getClass()); } } assertTrue(matched); } @Test void testPointersUnique() throws Exception { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); setupReader(("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*AA*ReceiverDept*SenderDept*20200101*000000*1*X*005010~\n" + "ST*000*0001*005010~\n" + "INT*1~" + "FLT*1~" + "SE*4*0001~\n" + "GE*1*1~\n" + "IEA*1*508121953~").getBytes(), "/x12/EDISchema000-numeric-types.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); JsonToken token; Map<String, List<JsonToken>> pointers = new LinkedHashMap<>(); while ((token = jsonParser.nextToken()) != null) { JsonToken tok = token; String pointer = jsonParser.getParsingContext().pathAsPointer().toString(); List<JsonToken> tokens = pointers.computeIfAbsent(pointer, k -> new ArrayList<>()); assertFalse(tokens.contains(token), () -> "pointers already contains " + pointer + " for token " + tok); assertTrue(tokens.size() <= 2, () -> "pointer " + pointer +" has too many tokens:" + tokens); tokens.add(token); } assertFalse(pointers.isEmpty()); } @Test void testTextRetrieval() throws Exception { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); setupReader(("ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *050812*1953*^*00501*508121953*0*P*:~" + "GS*AA*ReceiverDept*SenderDept*20200101*000000*1*X*005010~\n" + "ST*000*0001*005010~\n" + "INT*1~" + "FLT*1~" + "SE*4*0001~\n" + "GE*1*1~\n" + "IEA*1*508121953~").getBytes(), "/x12/EDISchema000-numeric-types.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); boolean matched = false; while (jsonParser.nextToken() != null) { String pointer = jsonParser.getParsingContext().pathAsPointer().toString(); if ("/data/1/data/0/data/0".equals(pointer)) { matched = true; // Element GS01 assertEquals("AA", jsonParser.getText()); assertEquals(2, jsonParser.getTextLength()); assertArrayEquals(new char[] { 'A', 'A' }, Arrays.copyOfRange( jsonParser.getTextCharacters(), jsonParser.getTextOffset(), jsonParser.getTextLength())); } } assertTrue(matched); } @Test void testBinaryElementRetrieval() throws Exception { ediReaderConfig.put(EDIInputFactory.JSON_NULL_EMPTY_ELEMENTS, true); setupReader("/x12/simple_with_binary_segment.edi", "/x12/EDISchemaBinarySegment.xml"); JsonParser jsonParser = JsonParserFactory.createJsonParser(ediReader, JsonParser.class, ediReaderConfig); int matched = 0; while (jsonParser.nextToken() != null) { String pointer = jsonParser.getParsingContext().pathAsPointer().toString(); if ("/data/1/data/1/data/1/data/1".equals(pointer)) { matched++; assertArrayEquals("1234567890123456789012345".getBytes(), jsonParser.getBinaryValue()); } if ("/data/1/data/1/data/2/data/1".equals(pointer)) { matched++; assertArrayEquals("12345678901234567890\n1234".getBytes(), jsonParser.getBinaryValue()); } if ("/data/1/data/1/data/3/data/1".equals(pointer)) { matched++; assertArrayEquals("1234567890\n1234567890\n12\n".getBytes(), jsonParser.getBinaryValue()); } } assertEquals(3, matched); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/bind/AcknowledgementBindTest.java
src/test/java/io/xlate/edi/internal/bind/AcknowledgementBindTest.java
package io.xlate.edi.internal.bind; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; import org.junit.jupiter.api.Test; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDINamespaces; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamWriter; class AcknowledgementBindTest { @Test void testEDIBinding() throws Exception { JAXBContext context = JAXBContext.newInstance(Interchange.class); Marshaller m = context.createMarshaller(); EDIOutputFactory oFactory = EDIOutputFactory.newFactory(); oFactory.setProperty(EDIOutputFactory.PRETTY_PRINT, Boolean.TRUE); oFactory.setErrorReporter((error, writer, location, data, typeReference) -> { // ignore }); ByteArrayOutputStream out = new ByteArrayOutputStream(); EDIStreamWriter writer = oFactory.createEDIStreamWriter(out); XMLStreamWriter xmlWriter = oFactory.createXMLStreamWriter(writer); ISA header = new ISA(); //ISA*00* *00* *ZZ*Receiver *ZZ*Sender *200301*1430*^*00501*000000001*0*P*:~ header.ISA01 = "00"; header.ISA02 = " "; header.ISA03 = "00"; header.ISA04 = " "; header.ISA05 = "ZZ"; header.ISA06 = "Receiver "; header.ISA07 = "ZZ"; header.ISA08 = "Sender "; header.ISA09 = "200301"; header.ISA10 = "1430"; header.ISA11 = "^"; header.ISA12 = "00704"; header.ISA13 = "000000001"; header.ISA14 = "0"; header.ISA15 = "P"; header.ISA16 = ":"; ISX syntaxExtension = new ISX(); syntaxExtension.ISX01 = "\\"; syntaxExtension.ISX02 = ""; IEA trailer = new IEA(); trailer.IEA01 = "0"; trailer.IEA02 = "000000001"; Interchange interchange = new Interchange(); interchange.header = header; interchange.syntaxExtension = syntaxExtension; interchange.trailer = trailer; m.marshal(interchange, xmlWriter); EDIInputFactory iFactory = EDIInputFactory.newFactory(); Interchange interchange2; try (EDIStreamReader reader = iFactory.createEDIStreamReader(new ByteArrayInputStream(out.toByteArray()))) { assertEquals(EDIStreamEvent.START_INTERCHANGE, reader.next()); XMLStreamReader xmlReader = iFactory.createXMLStreamReader(reader); Unmarshaller u = context.createUnmarshaller(); interchange2 = (Interchange) u.unmarshal(xmlReader); } assertEquals(interchange.header.ISA01, interchange2.header.ISA01); assertEquals(interchange.header.ISA02, interchange2.header.ISA02); assertEquals(interchange.header.ISA03, interchange2.header.ISA03); assertEquals(interchange.header.ISA04, interchange2.header.ISA04); assertEquals(interchange.header.ISA05, interchange2.header.ISA05); assertEquals(interchange.header.ISA06, interchange2.header.ISA06); assertEquals(interchange.header.ISA07, interchange2.header.ISA07); assertEquals(interchange.header.ISA08, interchange2.header.ISA08); assertEquals(interchange.header.ISA09, interchange2.header.ISA09); assertEquals(interchange.header.ISA10, interchange2.header.ISA10); assertEquals(interchange.header.ISA11, interchange2.header.ISA11); assertEquals(interchange.header.ISA12, interchange2.header.ISA12); assertEquals(interchange.header.ISA13, interchange2.header.ISA13); assertEquals(interchange.header.ISA14, interchange2.header.ISA14); assertEquals(interchange.header.ISA15, interchange2.header.ISA15); assertEquals(interchange.header.ISA16, interchange2.header.ISA16); assertEquals(interchange.trailer.IEA01, interchange2.trailer.IEA01); assertEquals(interchange.trailer.IEA02, interchange2.trailer.IEA02); } @XmlType @XmlRootElement(name = "INTERCHANGE", namespace = EDINamespaces.LOOPS) static class Interchange { @XmlElement(name = "ISA", namespace = EDINamespaces.SEGMENTS) ISA header; @XmlElement(name = "ISX", namespace = EDINamespaces.SEGMENTS) ISX syntaxExtension; @XmlElement(name = "IEA", namespace = EDINamespaces.SEGMENTS) IEA trailer; } @XmlType(namespace = EDINamespaces.SEGMENTS, propOrder = {}) static class ISA { @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA01; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA02; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA03; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA04; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA05; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA06; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA07; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA08; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA09; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA10; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA11; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA12; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA13; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA14; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA15; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISA16; } @XmlType(namespace = EDINamespaces.SEGMENTS, propOrder = {}) static class ISX { @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISX01; @XmlElement(namespace = EDINamespaces.ELEMENTS) String ISX02; } @XmlType(namespace = EDINamespaces.SEGMENTS, propOrder = {}) static class IEA { @XmlElement(namespace = EDINamespaces.ELEMENTS) String IEA01; @XmlElement(namespace = EDINamespaces.ELEMENTS) String IEA02; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/bind/TransactionBindTest.java
src/test/java/io/xlate/edi/internal/bind/TransactionBindTest.java
package io.xlate.edi.internal.bind; import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.io.StringWriter; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; import java.math.BigDecimal; import java.util.Arrays; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.xml.namespace.QName; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.SchemaOutputResolver; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; import jakarta.xml.bind.annotation.XmlValue; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import io.xlate.edi.stream.EDINamespaces; class TransactionBindTest { final String XSD = "http://www.w3.org/2001/XMLSchema"; Map<String, Element> complexTypes; Map<String, Element> simpleTypes; @Test void testElementBinding() throws Exception { JAXBContext context = JAXBContext.newInstance(TestTx.class); final Map<String, DOMResult> results = new HashMap<>(); context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String ns, String file) throws IOException { DOMResult result = new DOMResult(); result.setSystemId(file); results.put(ns, result); return result; } }); //assertEquals(1, results.size()); //QName rootElementName = getRootElementName(TestTx.class); for (DOMResult result : results.values()) { StringWriter writer = new StringWriter(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(new DOMSource(result.getNode()), new StreamResult(writer)); String xml = writer.toString(); System.out.println(xml); } catch (Exception e) { fail("Unexpected exception: " + e.getMessage()); } } //Document doc = (Document) results.get(rootElementName.getNamespaceURI()).getNode(); /*Element rootElement = elementStream(doc.getElementsByTagNameNS(XSD, "element")) .filter(e -> rootElementName.getLocalPart().equals(e.getAttribute("name"))) .findFirst() .orElse(null);*/ complexTypes = results.values() .stream() .map(result -> result.getNode()) .map(Document.class::cast) .map(document -> document.getElementsByTagNameNS(XSD, "complexType")) .flatMap(this::elementStream) .collect(Collectors.toMap(e -> e.getAttribute("name"), e -> e)); simpleTypes = results.values() .stream() .map(result -> result.getNode()) .map(Document.class::cast) .map(document -> document.getElementsByTagNameNS(XSD, "simpleType")) .flatMap(this::elementStream) .collect(Collectors.toMap(e -> e.getAttribute("name"), e -> e)); //Element rootType = complexTypes.get(rootElement.getAttribute("type")); //print("", elementStream(rootType.getElementsByTagNameNS(XSD, "element")), new ArrayDeque<>(Arrays.asList(TestTx.class))); } QName getRootElementName(Class<?> type) { XmlRootElement rootElement = type.getAnnotation(XmlRootElement.class); String ns; String localName; if (rootElement != null) { if ("##default".equals(rootElement.name())) { localName = decapitalize(type.getSimpleName()); } else { localName = rootElement.name(); } if ("##default".equals(rootElement.namespace())) { ns = ""; } else { ns = rootElement.namespace(); } return new QName(ns, localName); } throw new IllegalStateException("Missing XmlRootElement annotation on root class"); } /** * Utility method to take a string and convert it to normal Java variable * name capitalization. This normally means converting the first * character from upper case to lower case, but in the (unusual) special * case when there is more than one character and both the first and * second characters are upper case, we leave it alone. * <p> * Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays * as "URL". * * COPYIED FROM java.beans.Introspector * * @param name The string to be decapitalized. * @return The decapitalized version of the string. */ static String decapitalize(String name) { if (name == null || name.length() == 0) { return name; } if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))){ return name; } char chars[] = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } Stream<Element> elementStream(NodeList nodes) { return IntStream.range(0, nodes.getLength()).mapToObj(nodes::item).map(Element.class::cast); } Element getElement(Element parent, String ns, String name) { return elementStream(parent.getElementsByTagNameNS(ns, name)).findFirst().orElse(null); } void print(String pad, Stream<Element> nodes, Deque<Class<?>> stack) { nodes.forEach(node -> { String typeName = node.getAttribute("type"); boolean isStructure = complexTypes.containsKey(typeName); boolean isSimpleType = simpleTypes.containsKey(typeName); boolean isExtension = node.hasAttribute("base"); Class<?> clazz = null; if (isExtension) { clazz = classForValue(stack.peekFirst()); System.out.printf("%s%s: %s\n", pad, node.getAttribute("base"), clazz); } else { String name = node.getAttribute("name"); clazz = classForElement(stack.peekFirst(), name); System.out.printf("%s%s: %s (%s)\n", pad, name, isStructure ? "***" : typeName, clazz); } if (isStructure || isSimpleType) { Element type = isStructure ? complexTypes.get(typeName) : simpleTypes.get(typeName); if (clazz != null) stack.offerFirst(clazz); if (isStructure) print(pad + " ", elementStream(type.getElementsByTagNameNS(XSD, "element")), stack); else print(pad + " ", elementStream(type.getElementsByTagNameNS(XSD, "restriction")), stack); if (clazz != null) stack.removeFirst(); } }); } Class<?> classForElement(Class<?> bean, String name) { return getAnnotatedClass(bean, XmlElement.class, a -> a.getAnnotation(XmlElement.class).name().equals(name)); } Class<?> classForValue(Class<?> bean) { return getAnnotatedClass(bean, XmlValue.class, a -> true); } <A extends Annotation> Class<?> getAnnotatedClass(Class<?> bean, Class<A> annotation, Predicate<AccessibleObject> filter) { Class<?> type = fieldType(bean, annotation, filter); if (type != null) { return type; } return methodType(bean, annotation, filter); } <A extends Annotation> Class<?> fieldType(Class<?> bean, Class<A> anno, Predicate<AccessibleObject> filter) { return Arrays.stream(bean.getDeclaredFields()) .filter(f -> f.isAnnotationPresent(anno)) .filter(filter) .map(f -> f.getType()) .findFirst() .orElse(null); } <A extends Annotation> Class<?> methodType(Class<?> bean, Class<A> anno, Predicate<AccessibleObject> filter) { return Arrays.stream(bean.getDeclaredMethods()) .filter(m -> !m.getReturnType().equals(Void.class)) .filter(m -> m.isAnnotationPresent(anno)) .filter(filter) .map(m -> m.getReturnType()) .findFirst() .orElse(null); } @XmlRootElement(namespace = EDINamespaces.LOOPS) @XmlType(propOrder = { "aa1", "aa2", "loop" }, namespace = EDINamespaces.LOOPS) public static class TestTx { @XmlElement(name = "AA1", namespace = EDINamespaces.SEGMENTS) Aa1 aa1; @XmlElement(name = "AA2", namespace = EDINamespaces.SEGMENTS) Aa2 aa2; @XmlElement(name = "L9000", namespace = EDINamespaces.LOOPS) Loop9000 loop; } @XmlType(namespace = EDINamespaces.LOOPS, propOrder = { "aa1", "aa2" }) public static class Loop9000 { @XmlElement(name = "AA1", namespace = EDINamespaces.SEGMENTS) Aa1 aa1; @XmlElement(name = "AA2", namespace = EDINamespaces.SEGMENTS) Aa2 aa2; } @XmlType(namespace = EDINamespaces.SEGMENTS, propOrder = { "aa101", "aa102", "aa103" }) public static class Aa1 { @XmlElement(name = "AA101", namespace = EDINamespaces.ELEMENTS) private String aa101; @XmlElement(name = "AA102", namespace = EDINamespaces.ELEMENTS) private Integer aa102; @XmlElement(name = "AA103", namespace = EDINamespaces.ELEMENTS) @XmlSchemaType(name = "date") private Date aa103; } @XmlType(namespace = EDINamespaces.SEGMENTS, propOrder = { "aa201", "aa202", "aa203" }) public static class Aa2 { @XmlElement(name = "AA201", namespace = EDINamespaces.ELEMENTS) private String aa201; @XmlElement(name = "AA202", namespace = EDINamespaces.ELEMENTS) private List<Integer> aa202; @XmlElement(name = "AA203", namespace = EDINamespaces.COMPOSITES) private Comp1 aa203; } @XmlType(namespace = EDINamespaces.COMPOSITES, name = "COMP1", propOrder = { "comp11", "comp12", "comp13" }) public static class Comp1 { @XmlElement(name = "COMP1-1", namespace = EDINamespaces.ELEMENTS) private String comp11; @XmlElement(name = "COMP1-2", namespace = EDINamespaces.ELEMENTS) private Integer comp12; @XmlElement(name = "COMP1-3", namespace = EDINamespaces.ELEMENTS) private NumberType comp13; } @XmlType(name = "E600", namespace = EDINamespaces.ELEMENTS) public static class NumberType { @XmlValue BigDecimal value; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/wiki/WriteEdifactExampleTest.java
src/test/java/io/xlate/edi/internal/wiki/WriteEdifactExampleTest.java
package io.xlate.edi.internal.wiki; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamConstants; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamWriter; class WriteEdifactExampleTest { @Test void testEdifactExample() throws EDIStreamException, IOException { // (1) Create an EDIOutputFactory EDIOutputFactory factory = EDIOutputFactory.newFactory(); int messageCount = 0; // Counter for the UNH/UNT messages contained in the interchange int messageSegmentCount = 0; // Counter for the segments in a UNH/UNT message // (2) Optionally specify delimiters - here the given values are the same as default factory.setProperty(EDIStreamConstants.Delimiters.SEGMENT, '\''); factory.setProperty(EDIStreamConstants.Delimiters.DATA_ELEMENT, '+'); factory.setProperty(EDIStreamConstants.Delimiters.COMPONENT_ELEMENT, ':'); factory.setProperty(EDIStreamConstants.Delimiters.RELEASE, '?'); factory.setProperty(EDIStreamConstants.Delimiters.REPETITION, ' '); // Write each segment on a new line (optional) // factory.setProperty(EDIOutputFactory.PRETTY_PRINT, true); // (3) Create an EDIStreamWriter. Any OutputStream may be used - here we are writing to a file OutputStream stream = new FileOutputStream("target/edifact.out"); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); // (4) Start the interchange writer.startInterchange(); // Optionally write a UNA segment. When delimiters are specified via the `EDIOutputFactory`'s // properties, a UNA segment will be automatically written. writer.writeStartSegment("UNA").writeEndSegment(); // (5) Write the beginning segment for the interchange. writer.writeStartSegment("UNB"); // Writing composite elements is done by first starting the element, // then writing the components. Finally, the element is ended. writer.writeStartElement() .writeComponent("UNOC") .writeComponent("3") .endElement(); writer.writeStartElement() .writeComponent("0123456789012") .writeComponent("14") .endElement(); writer.writeStartElement() .writeComponent("0123456789012") .writeComponent("14") .endElement(); writer.writeStartElement() .writeComponent("200702") .writeComponent("0734") .endElement(); // A simple data element may be written with a single method call. writer.writeElement("00000563"); // Complete the UNB segment writer.writeEndSegment(); // (6) Write the message header segment writer.writeStartSegment("UNH"); // Keep track of the message count for the UNZ trailer segment messageCount++; // Keep track of the segment count for this message messageSegmentCount++; writer.writeElement("0001"); writer.writeStartElement() .writeComponent("INVOIC") .writeComponent("D") .writeComponent("96A") .writeComponent("UN") .writeComponent("EAN008") .endElement(); writer.writeEndSegment(); // Begin Message BGM writer.writeStartSegment("BGM"); messageSegmentCount++; writer.writeElement("380"); writer.writeElement("1676245"); writer.writeElement("9"); writer.writeEndSegment(); // From Here do further INVOIC related segments like DTM and so on // (7) Write the message trailer segment writer.writeStartSegment("UNT") .writeElement(String.valueOf(++messageSegmentCount)) .writeElement("0001") .writeEndSegment(); // (8) Write the message trailer segment writer.writeStartSegment("UNZ") .writeElement(String.valueOf(messageCount)) .writeElement("00000563") .writeEndSegment(); // (9) End the interchange writer.endInterchange(); // (10) Close the EDIStreamWriter. This must be done to ensure the output is flushed and written writer.close(); assertEquals("" + "UNA:+.? '" + "UNB+UNOC:3+0123456789012:14+0123456789012:14+200702:0734+00000563'" + "UNH+0001+INVOIC:D:96A:UN:EAN008'" + "BGM+380+1676245+9'" + "UNT+3+0001'" + "UNZ+1+00000563'", String.join("", Files.readAllLines(Paths.get("target/edifact.out")))); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/wiki/package-info.java
src/test/java/io/xlate/edi/internal/wiki/package-info.java
package io.xlate.edi.internal.wiki;
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/wiki/ReadInterchangeAcknowledgementTest.java
src/test/java/io/xlate/edi/internal/wiki/ReadInterchangeAcknowledgementTest.java
package io.xlate.edi.internal.wiki; import static org.junit.jupiter.api.Assertions.assertTrue; // import java.io.FileInputStream; import java.io.InputStream; import org.junit.jupiter.api.Test; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamReader; class ReadInterchangeAcknowledgementTest { @Test void testAcknowledgementSuccess() throws Exception { assertTrue(isAcknowledgementSuccess()); } private boolean isAcknowledgementSuccess() throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); String ta104 = null; String ta105 = null; //InputStream stream = new FileInputStream("x12_interchange_ack.txt"); try (InputStream stream = getClass().getResource("/wiki/x12_interchange_ack.txt").openStream(); EDIStreamReader reader = factory.createEDIStreamReader(stream)) { EDIStreamEvent event; String segment = null; while (reader.hasNext()) { event = reader.next(); if (event == EDIStreamEvent.START_SEGMENT) { segment = reader.getText(); } else if (event == EDIStreamEvent.ELEMENT_DATA) { if ("TA1".equals(segment)) { if (reader.getLocation().getElementPosition() == 4) { ta104 = reader.getText(); } else if (reader.getLocation().getElementPosition() == 5) { ta105 = reader.getText(); } } } } } return "A".equals(ta104) && "000".equals(ta105); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/wiki/WriteInterchangeAcknowledgementTest.java
src/test/java/io/xlate/edi/internal/wiki/WriteInterchangeAcknowledgementTest.java
package io.xlate.edi.internal.wiki; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import org.junit.jupiter.api.Test; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamConstants; import io.xlate.edi.stream.EDIStreamWriter; class WriteInterchangeAcknowledgementTest { @Test void testAcknowledgementWrite() throws Exception { EDIOutputFactory factory = EDIOutputFactory.newFactory(); // Optionally specify delimiters - here the given values are the same as default factory.setProperty(EDIStreamConstants.Delimiters.SEGMENT, '~'); factory.setProperty(EDIStreamConstants.Delimiters.DATA_ELEMENT, '*'); factory.setProperty(EDIOutputFactory.PRETTY_PRINT, true); ByteArrayOutputStream stream = new ByteArrayOutputStream(); EDIStreamWriter writer = factory.createEDIStreamWriter(stream); writer.startInterchange(); writer.writeStartSegment("ISA") .writeElement("00") .writeElement(" ") .writeElement("00") .writeElement(" ") .writeElement("ZZ") .writeElement("Receiver ") .writeElement("ZZ") .writeElement("Sender ") .writeElement("200301") .writeElement("1430") .writeElement("^") .writeElement("00501") .writeElement("000000001") .writeElement("0") .writeElement("P") .writeElement(":") .writeEndSegment(); writer.writeStartSegment("TA1") .writeElement("000000050") .writeElement("200229") .writeElement("1200") .writeElement("A") .writeElement("000") .writeEndSegment(); writer.writeStartSegment("IEA") .writeElement("1") .writeElement("000000001") .writeEndSegment(); writer.endInterchange(); writer.close(); assertEquals(new String(Files.readAllBytes(Paths.get("./src/test/resources/wiki/x12_interchange_ack.txt"))), stream.toString().trim()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/wiki/ReadFuncAcknowledgementTest.java
src/test/java/io/xlate/edi/internal/wiki/ReadFuncAcknowledgementTest.java
package io.xlate.edi.internal.wiki; import java.io.InputStream; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.stream.JsonGenerator; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; class ReadFuncAcknowledgementTest { @SuppressWarnings("unused") @Test void testReadFuncAcknowledgement() throws Exception { EDIInputFactory factory = EDIInputFactory.newFactory(); JsonObject result = null; // Any InputStream can be used to create an `EDIStreamReader` try (InputStream stream = getClass().getResource("/x12/simple997.edi").openStream(); EDIStreamReader reader = factory.createEDIStreamReader(stream)) { EDIStreamEvent event; boolean transactionBeginSegment = false; Deque<JsonObjectBuilder> buildStack = new ArrayDeque<>(); JsonObjectBuilder builder = null; JsonArrayBuilder transactions = null; Deque<Set<String>> activeLoops = new ArrayDeque<>(); Set<String> peerLoops; Map<String, JsonArrayBuilder> loopBuilders = new HashMap<>(); JsonArrayBuilder currentLoop; JsonArrayBuilder segmentBuilder = null; JsonArrayBuilder compositeBuilder = null; while (reader.hasNext()) { event = reader.next(); switch (event) { case START_INTERCHANGE: // Called at the beginning of the EDI stream once the X12 dialect is confirmed builder = Json.createObjectBuilder(); buildStack.offer(builder); break; case END_INTERCHANGE: // Called following the IEA segment result = builder.build(); break; case START_GROUP: // Called prior to the start of the GS segment builder = Json.createObjectBuilder(); buildStack.offer(builder); transactions = Json.createArrayBuilder(); break; case END_GROUP: // Called following the GE segment JsonObjectBuilder groupBuilder = buildStack.removeLast(); groupBuilder.add("TRANSACTIONS", transactions); builder = buildStack.peekLast(); builder.add(reader.getReferenceCode(), groupBuilder); break; case START_TRANSACTION: // Called prior to the start of the ST segment builder = Json.createObjectBuilder(); buildStack.offer(builder); // Set a boolean so that when the ST segment is complete, our code // can set a transaction schema to use with the reader. This boolean // allows the END_SEGMENT code to know the current context of the // segment. transactionBeginSegment = true; break; case END_TRANSACTION: // Called following the SE segment JsonObjectBuilder transactionBuilder = buildStack.removeLast(); transactions.add(transactionBuilder); builder = buildStack.peekLast(); break; case START_LOOP: // Called before the start of the segment that begins a loop. // The loop's `code` from the schema can be obtained by a call // to `reader.getReferenceCode()` builder = Json.createObjectBuilder(); buildStack.offer(builder); break; case END_LOOP: // Called following the end of the segment that ends a loop. // The loop's `code` from the schema can be obtained by a call // to `reader.getReferenceCode()` JsonObjectBuilder loopBuilder = buildStack.removeLast(); builder = buildStack.peekLast(); builder.add(reader.getReferenceCode(), loopBuilder); break; case START_SEGMENT: segmentBuilder = Json.createArrayBuilder(); break; case END_SEGMENT: if (transactionBeginSegment) { /* * At the end of the ST segment, load the schema for use to validate * the transaction. */ SchemaFactory schemaFactory = SchemaFactory.newFactory(); // Any InputStream or URL can be used to create a `Schema` Schema schema = schemaFactory.createSchema(getClass().getResource("/x12/EDISchema997.xml")); reader.setTransactionSchema(schema); } transactionBeginSegment = false; builder.add(reader.getText(), segmentBuilder); segmentBuilder = null; break; case START_COMPOSITE: compositeBuilder = Json.createArrayBuilder(); break; case END_COMPOSITE: segmentBuilder.add(compositeBuilder); compositeBuilder = null; break; case ELEMENT_DATA: if (compositeBuilder != null) { compositeBuilder.add(reader.getText()); } else { segmentBuilder.add(reader.getText()); } break; case SEGMENT_ERROR: // Handle a segment error EDIStreamValidationError segmentErrorType = reader.getErrorType(); // ... break; case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: // Handle a segment error EDIStreamValidationError elementErrorType = reader.getErrorType(); // ... break; default: break; } } } Assertions.assertNotNull(result); Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, "true")) .createGenerator(System.out) .write(result) .close(); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/StaEDISchemaTest.java
src/test/java/io/xlate/edi/internal/schema/StaEDISchemaTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.InputStream; import java.net.URL; import java.util.Collections; import java.util.Map; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDIComplexType; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.SchemaFactory; @SuppressWarnings("resource") class StaEDISchemaTest { @Test void testSetTypesNullTypes() { StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID); assertThrows(NullPointerException.class, () -> schema.setTypes(null)); } @Test void testRootTypeIsInterchange_00200() throws Exception { StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID); URL schemaLocation = getClass().getResource("/X12/v00200.xml"); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(schemaLocation.openStream()); reader.nextTag(); // Pass by <schema> element Map<String, EDIType> types = new SchemaReaderV4(reader, Collections.singletonMap(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, schemaLocation.toURI().resolve(".").toURL())).readTypes(); schema.setTypes(types); assertEquals(EDIType.Type.INTERCHANGE, schema.getType(StaEDISchema.INTERCHANGE_ID).getType()); } @Test void testRootTypeIsInterchange_00402() throws Exception { StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID); URL schemaLocation = getClass().getResource("/X12/v00402.xml"); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(schemaLocation.openStream()); reader.nextTag(); // Pass by <schema> element Map<String, EDIType> types = new SchemaReaderV4(reader, Collections.singletonMap(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, schemaLocation.toURI().resolve(".").toURL())).readTypes(); schema.setTypes(types); assertEquals(EDIType.Type.INTERCHANGE, schema.getType(StaEDISchema.INTERCHANGE_ID).getType()); } @Test void testLoadV3TransactionMultipleSyntaxElements_EDIFACT_CONTRL() throws EDISchemaException, XMLStreamException, FactoryConfigurationError { StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID); InputStream schemaStream = getClass().getResourceAsStream("/EDIFACT/CONTRL-v4r02.xml"); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(schemaStream); reader.nextTag(); // Pass by <schema> element Map<String, EDIType> types = new SchemaReaderV4(reader, Collections.emptyMap()).readTypes(); schema.setTypes(types); assertEquals(EDIType.Type.TRANSACTION, schema.getType(StaEDISchema.TRANSACTION_ID).getType()); assertEquals(4, ((EDIComplexType) schema.getType("UCF")).getSyntaxRules().size()); assertEquals(4, ((EDIComplexType) schema.getType("UCI")).getSyntaxRules().size()); assertEquals(7, ((EDIComplexType) schema.getType("UCM")).getSyntaxRules().size()); } @Test void testLoadV4_TestSimpleTypes() throws EDISchemaException, XMLStreamException, FactoryConfigurationError { StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID); InputStream schemaStream = getClass().getResourceAsStream("/x12/IG-999-standard-included.xml"); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(schemaStream); reader.nextTag(); // Pass by <schema> element Map<String, EDIType> types = new SchemaReaderV4(reader, Collections.emptyMap()).readTypes(); schema.setTypes(types); assertEquals(EDIType.Type.TRANSACTION, schema.getType(StaEDISchema.TRANSACTION_ID).getType()); assertFalse(schema.containsSegment("DE0479")); EDIType ak101 = schema.getType("DE0479"); assertEquals(EDIType.Type.ELEMENT, ak101.getType()); assertEquals(ak101, schema.getType("DE0479")); assertFalse(schema.containsSegment("DE0715")); EDIType ak901 = schema.getType("DE0715"); assertEquals(EDIType.Type.ELEMENT, ak901.getType()); assertNotEquals(ak101, ak901); assertTrue(schema.containsSegment("AK9")); EDIType ak9 = schema.getType("AK9"); assertEquals(EDIType.Type.SEGMENT, ak9.getType()); assertNotEquals(ak101, ak9); } @Test void testEmptyTypesMapThrowsException() throws Exception { StaEDISchema schema = new StaEDISchema(StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID); Map<String, EDIType> types = Collections.emptyMap(); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> schema.setTypes(types)); assertEquals(String.format("Schema must contain either %s or %s", StaEDISchema.INTERCHANGE_ID, StaEDISchema.TRANSACTION_ID), thrown.getMessage()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/StructureTypeTest.java
src/test/java/io/xlate/edi/internal/schema/StructureTypeTest.java
package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISyntaxRule; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.EDIType.Type; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; class StructureTypeTest { @Test void testStructureConstruction() { EDIReference ref = new Reference("E1", EDIType.Type.ELEMENT, 1, 1, null, null); EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.EXCLUSION, Arrays.asList(1, 8)); StructureType s = new StructureType("SEG", Type.SEGMENT, "SEG", Arrays.asList(ref), Arrays.asList(rule), null, null); assertEquals("id: SEG, type: SEGMENT, code: SEG, references: [{refId: E1, minOccurs: 1, maxOccurs: 1, type: { null }}], syntaxRestrictions: [{type: EXCLUSION, positions: [1, 8]}]", s.toString()); } @Test void testStructureTypeDescriptionAccess() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "TA1*000000050*200229*1200*A*000~" + "IEA*0*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); EDIReference ta1reference = null; while (reader.hasNext()) { switch (reader.next()) { case END_SEGMENT: if ("TA1".equals(reader.getReferenceCode())) { ta1reference = reader.getSchemaTypeReference(); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(0, errors.size()); assertNotNull(ta1reference); // Value set in v00402.xml assertEquals("Interchange Acknowledgment", ta1reference.getTitle()); assertNull(ta1reference.getDescription()); assertNotNull(ta1reference.getReferencedType()); // Values set in common.xml assertEquals("Interchange Acknowledgment", ta1reference.getReferencedType().getTitle()); assertEquals("To report the status of processing a received interchange header and trailer or the non-delivery by a network provider", ta1reference.getReferencedType().getDescription()); // Expect the titles to be different String instances assertNotSame(ta1reference.getTitle(), ta1reference.getReferencedType().getTitle()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/ClasspathURLStreamHandlerTest.java
src/test/java/io/xlate/edi/internal/schema/ClasspathURLStreamHandlerTest.java
package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ClasspathURLStreamHandlerTest { ClasspathURLStreamHandler cut; @BeforeEach void setup() { cut = new ClasspathURLStreamHandler(getClass().getClassLoader()); } @Test void testResourceUrlResolvesNull() throws MalformedURLException { URL target = new URL(null, "classpath:does/not/exist.txt", cut); @SuppressWarnings("unused") FileNotFoundException ex = assertThrows(FileNotFoundException.class, () -> { target.openConnection(); }); } @Test void testResourceUrlFound() throws IOException { URL target = new URL(null, "classpath:logging.properties", cut); URLConnection connection = target.openConnection(); assertNotNull(connection); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/ElementTypeTest.java
src/test/java/io/xlate/edi/internal/schema/ElementTypeTest.java
package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.schema.EDISimpleType.Base; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; class ElementTypeTest { static final byte[] INTERCHANGE_RESPONSE = ("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "TA1*000000050*200229*1200*A*000~" + "IEA*0*000000001~").getBytes(); @Test void testElementContructorNoValues() { ElementType e = new ElementType("E1", Base.STRING, -1, "1", 1, 0L, 5L, Collections.emptyMap(), Collections.emptyList(), null, null); assertEquals("id: E1, type: ELEMENT, base: STRING, code: 1, minLength: 0, maxLength: 5, values: {}", e.toString()); } @Test void testElementContructorWithValues() { Map<String, String> values = new HashMap<>(); values.put("ABCDE", "Title 1"); values.put("FGHIJ", "Title 2"); ElementType e = new ElementType("E1", Base.STRING, -1, "1", 1, 0L, 5L, values, Collections.emptyList(), null, null); assertEquals("id: E1, type: ELEMENT, base: STRING, code: 1, minLength: 0, maxLength: 5, values: {ABCDE=Title 1, FGHIJ=Title 2}", e.toString()); } @SuppressWarnings("deprecation") @Test void testElementTypeNumberDefault() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(INTERCHANGE_RESPONSE); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); EDIReference i03reference = null; while (reader.hasNext()) { switch (reader.next()) { case ELEMENT_DATA: if ("I03".equals(reader.getReferenceCode())) { i03reference = reader.getSchemaTypeReference(); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(0, errors.size()); assertNotNull(i03reference); assertNotNull(i03reference.getReferencedType()); assertEquals(-1, ((EDISimpleType) i03reference.getReferencedType()).getNumber()); } @Test void testElementTypeDescriptionAccess() throws EDIStreamException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(INTERCHANGE_RESPONSE); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); EDIReference i03reference = null; while (reader.hasNext()) { switch (reader.next()) { case ELEMENT_DATA: if ("I03".equals(reader.getReferenceCode())) { i03reference = reader.getSchemaTypeReference(); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); break; default: break; } } assertEquals(0, errors.size()); assertNotNull(i03reference); assertNull(i03reference.getTitle()); assertNull(i03reference.getDescription()); assertNotNull(i03reference.getReferencedType()); // Values set in common.xml assertEquals("Security Information Qualifier", i03reference.getReferencedType().getTitle()); assertEquals("Code identifying the type of information in the Security Information", i03reference.getReferencedType().getDescription()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/StaEDISchemaFactoryTest.java
src/test/java/io/xlate/edi/internal/schema/StaEDISchemaFactoryTest.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.xml.stream.XMLStreamException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import io.xlate.edi.schema.EDIComplexType; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.schema.implementation.LoopImplementation; import io.xlate.edi.stream.EDIStreamConstants.Standards; @SuppressWarnings("resource") class StaEDISchemaFactoryTest { @Test void testCreateSchemaByURL() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory instanceof StaEDISchemaFactory, "Not an instance"); URL schemaURL = getClass().getResource("/x12/EDISchema997.xml"); Schema schema = factory.createSchema(schemaURL); assertEquals(StaEDISchema.TRANSACTION_ID, schema.getStandard().getId(), "Incorrect root id"); assertTrue(schema.containsSegment("AK9"), "Missing AK9 segment"); } @Test void testCreateSchemaByURL_NoSuchFile() throws MalformedURLException { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory instanceof StaEDISchemaFactory, "Not an instance"); URL schemaURL = new URL("file:./src/test/resources/x12/missing.xml"); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(schemaURL)); assertEquals("Unable to read URL stream", thrown.getOriginalMessage()); assertTrue(thrown.getCause() instanceof FileNotFoundException); } @Test void testCreateSchemaByStream() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory instanceof StaEDISchemaFactory, "Not an instance"); InputStream schemaStream = getClass().getResourceAsStream("/x12/EDISchema997.xml"); Schema schema = factory.createSchema(schemaStream); assertEquals(StaEDISchema.TRANSACTION_ID, schema.getStandard().getId(), "Incorrect root id"); assertTrue(schema.containsSegment("AK9"), "Missing AK9 segment"); } @Test void testCreateEdifactInterchangeSchema() throws EDISchemaException { Schema schema = SchemaUtils.getControlSchema(Standards.EDIFACT, new String[] { "UNOA", "4", "", "", "02" }); assertNotNull(schema, "schema was null"); assertEquals(StaEDISchema.INTERCHANGE_ID, schema.getStandard().getId(), "Incorrect root id"); } @Test void testIsPropertySupportedTrue() { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory.isPropertySupported(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT)); } @Test void testIsPropertySupportedFalse() { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(!factory.isPropertySupported("FOO"), "FOO *is* supported"); } @Test void testPropertySupported() throws MalformedURLException { SchemaFactory factory = SchemaFactory.newFactory(); URL workDir = new File(System.getProperty("user.dir")).toURI().toURL(); // Set to current working directory factory.setProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, new File("").toURI().toURL()); assertEquals(workDir, factory.getProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT)); } @Test void testGetPropertyUnsupported() { SchemaFactory factory = SchemaFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> factory.getProperty("FOO")); } @Test void testSetProperty() { SchemaFactory factory = SchemaFactory.newFactory(); assertThrows(IllegalArgumentException.class, () -> factory.setProperty("BAR", "BAZ")); } @Test void testExceptionThrownWithoutSchema() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream("<noschema></noschema>".getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Unexpected XML element [noschema]", thrown.getOriginalMessage()); } @Test void testExceptionThrownWithoutInterchangeAndTransactionV2() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("<schema xmlns='" + StaEDISchemaFactory.XMLNS_V2 + "'><random/></schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Unexpected XML element [{" + StaEDISchemaFactory.XMLNS_V2 + "}random]", thrown.getOriginalMessage()); } @Test void testInterchangeRequiredAttributesV2() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream1 = new ByteArrayInputStream(("<schema xmlns='" + StaEDISchemaFactory.XMLNS_V2 + "'><interchange _header='ABC' trailer='XYZ' /></schema>").getBytes()); EDISchemaException thrown1 = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream1)); assertEquals("Missing required attribute: [header]", thrown1.getOriginalMessage()); InputStream stream2 = new ByteArrayInputStream(("<schema xmlns='" + StaEDISchemaFactory.XMLNS_V2 + "'><interchange header='ABC' _trailer='XYZ' /></schema>").getBytes()); EDISchemaException thrown2 = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream2)); assertEquals("Missing required attribute: [trailer]", thrown2.getOriginalMessage()); } @Test void testInvalidStartOfSchema() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V2 + "'" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Exception checking start of schema XML", thrown.getOriginalMessage()); } @Test void testUnexpectedElementBeforeSequenceV2() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V2 + "'>" + "<interchange header='ABC' trailer='XYZ'>" + "<description><![CDATA[TEXT ALLOWED]]></description>" + "<unexpected></unexpected>" + "<sequence></sequence>" + "</interchange>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Unexpected XML element [{" + StaEDISchemaFactory.XMLNS_V2 + "}unexpected]", thrown.getOriginalMessage()); } @Test void testCreateSchemaByStreamV3() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory instanceof StaEDISchemaFactory, "Not an instance"); InputStream schemaStream = getClass().getResourceAsStream("/x12/IG-999.xml"); Schema schema = factory.createSchema(schemaStream); assertEquals(StaEDISchema.TRANSACTION_ID, schema.getStandard().getId(), "Incorrect root id"); assertEquals(StaEDISchema.IMPLEMENTATION_ID, schema.getImplementation().getId(), "Incorrect impl id"); assertTrue(schema.containsSegment("AK9"), "Missing AK9 segment"); } @Test void testCreateSchemaByStreamV4_with_include_equals_V3Schema() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory instanceof StaEDISchemaFactory, "Not an instance"); InputStream schemaStreamV4 = getClass().getResourceAsStream("/x12/IG-999-standard-included.xml"); Schema schemaV4 = factory.createSchema(schemaStreamV4); assertEquals(StaEDISchema.TRANSACTION_ID, schemaV4.getStandard().getId(), "Incorrect root id"); assertEquals(StaEDISchema.IMPLEMENTATION_ID, schemaV4.getImplementation().getId(), "Incorrect impl id"); assertTrue(schemaV4.containsSegment("AK9"), "Missing AK9 segment"); InputStream schemaStreamV3 = getClass().getResourceAsStream("/x12/IG-999.xml"); Schema schemaV3 = factory.createSchema(schemaStreamV3); List<EDIType> missingV4 = StreamSupport.stream(schemaV3.spliterator(), false) .filter(type -> !(type.equals(schemaV4.getType(type.getId())) && type.hashCode() == Objects.hashCode(schemaV4.getType(type.getId())) && type.toString().equals(String.valueOf(schemaV4.getType(type.getId()))))) .collect(Collectors.toList()); List<EDIType> missingV3 = StreamSupport.stream(schemaV4.spliterator(), false) .filter(type -> !(type.equals(schemaV3.getType(type.getId())) && type.hashCode() == Objects.hashCode(schemaV3.getType(type.getId())) && type.toString().equals(String.valueOf(schemaV3.getType(type.getId()))))) .collect(Collectors.toList()); assertTrue(missingV4.isEmpty(), () -> "V3 schema contains types not in V4: " + missingV4); assertTrue(missingV3.isEmpty(), () -> "V4 schema contains types not in V3: " + missingV3); } @SuppressWarnings("deprecation") @Test void testCreateSchemaByStreamV4_with_include_relative_equals_V3Schema() throws Exception { SchemaFactory factory = SchemaFactory.newFactory(); // Reading URL as String factory.setProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, new File("src/test/resources/x12/").toURI().toString()); Schema schema1 = factory.createSchema(getClass().getResourceAsStream("/x12/IG-999-standard-included-relative.xml")); // Reading URL factory.setProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, new File("src/test/resources/x12/").toURI().toURL()); Schema schema2 = factory.createSchema(getClass().getResourceAsStream("/x12/IG-999-standard-included-relative.xml")); factory.setProperty(SchemaFactory.SCHEMA_LOCATION_URL_CONTEXT, null); Schema schema3 = factory.createSchema(getClass().getResourceAsStream("/x12/IG-999.xml")); assertNotEquals(schema1, factory); assertNotEquals(factory, schema1); assertEquals(schema3, schema1); assertEquals(schema1, schema2); assertEquals(schema1.hashCode(), schema2.hashCode()); assertEquals(schema2.hashCode(), schema3.hashCode()); assertEquals(schema3.getMainLoop(), schema1.getStandard()); } @ParameterizedTest @CsvSource({ "/x12/implSchemaDuplicatePosition.xml, Duplicate value for position 1", "/x12/discriminators/element-too-large.xml, Discriminator element position invalid: 3.1", "/x12/discriminators/element-too-small.xml, Discriminator element position invalid: 0.1", "/x12/discriminators/element-not-specified.xml, Discriminator position is unused (not specified): 2.1", "/x12/discriminators/component-too-large.xml, Discriminator component position invalid: 2.3", "/x12/discriminators/component-too-small.xml, Discriminator component position invalid: 2.0", "/x12/discriminators/element-without-enumeration.xml, Discriminator element does not specify value enumeration: 2.2", "/EDIFACT/fragment-uci-invalid-syntax-type.xml, Invalid syntax 'type': [conditional-junk]", "/EDIFACT/fragment-uci-invalid-min-occurs.xml, Invalid minOccurs", "/EDIFACT/fragment-uci-duplicate-element-names.xml, duplicate name: DE0004" }) void testSchemaExceptions(String resourceName, String exceptionMessage) { SchemaFactory factory = SchemaFactory.newFactory(); assertTrue(factory instanceof StaEDISchemaFactory, "Not an instance"); InputStream stream = getClass().getResourceAsStream(resourceName); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); Throwable cause = thrown.getCause(); assertNotNull(cause); assertEquals(exceptionMessage, cause.getMessage()); } @Test void testDuplicateElementTypeNames_v4_override() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V4 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <group header='SG3' trailer='SG4'>" + " <transaction header='SG5' trailer='SG6'/>" + " </group>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" minLength='2' maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG4\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG5\"><sequence><element type='E1'/></sequence></segmentType>" + "<elementType name=\"E1\" base=\"string\" minLength='1' maxLength=\"10\" />" + "<segmentType name=\"SG6\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); Schema schema = factory.createSchema(stream); Stream.of("SG1","SG2","SG3","SG4","SG5","SG6") .forEach(segmentTag -> { assertEquals(1, ((EDISimpleType) ((EDIComplexType) schema.getType(segmentTag)).getReferences().get(0).getReferencedType()).getMinLength()); assertEquals(10, ((EDISimpleType) ((EDIComplexType) schema.getType(segmentTag)).getReferences().get(0).getReferencedType()).getMaxLength()); }); } @Test void testGetControlSchema() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); Schema schema = factory.getControlSchema(Standards.X12, new String[] { "00501" }); assertNotNull(schema); assertEquals(EDIType.Type.SEGMENT, schema.getType("ISA").getType()); assertEquals(EDIType.Type.SEGMENT, schema.getType("GS").getType()); assertEquals(EDIType.Type.SEGMENT, schema.getType("ST").getType()); } @Test void testGetControlSchema_NotFound() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); Schema schema = factory.getControlSchema(Standards.EDIFACT, new String[] { "UNOA", "0" }); assertNull(schema); } @Test void testReferenceUndeclared() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='ABC' trailer='XYZ'>" + "<sequence>" + " <segment type='NUL'/>" + "</sequence>" + "</interchange>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Type " + StaEDISchema.INTERCHANGE_ID + " references undeclared segment with ref='ABC'", thrown.getOriginalMessage()); } @Test void testReferenceIncorrectType() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <segment type='E1'/>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Type 'E1' must not be referenced as 'segment' in definition of type '" + StaEDISchema.INTERCHANGE_ID + "'", thrown.getOriginalMessage()); } @Test void testUnexpectedUnknownTypeElement() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <segment type='SG3'/>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<unknownType xmlns='http://xlate.io'/>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Unexpected XML element [{http://xlate.io}unknownType]", thrown.getOriginalMessage()); } @Test void testMissingRequiredTransactionElement() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <group header='SG3' trailer='SG4' use='prohibited'></group>" + "</sequence>" + "</interchange>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Expected XML element [{" + StaEDISchemaFactory.XMLNS_V3 + "}transaction] not found", thrown.getOriginalMessage()); } @Test void testProhibitedUseType() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <group header='SG3' trailer='SG4' use='prohibited'>" + " <transaction header='SG5' trailer='SG6' use='prohibited'></transaction>" + " </group>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG4\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG5\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG6\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); Schema schema = factory.createSchema(stream); EDIComplexType interchange = schema.getStandard(); assertEquals(0, interchange.getReferences().get(1).getMinOccurs()); assertEquals(0, interchange.getReferences().get(1).getMaxOccurs()); } @Test void testInvalidUseType() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <group header='SG3' trailer='SG4' use='junk'>" + " <transaction header='SG5' trailer='SG6' use='prohibited'></transaction>" + " </group>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG4\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG5\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG6\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Invalid value for 'use': junk", thrown.getOriginalMessage()); } @Test void testInvalidSegmentName() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='sg1' trailer='SG2'>" + "<sequence>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"sg1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Invalid segment name [sg1]", thrown.getOriginalMessage()); } @Test void testInvalidCountType() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2' trailerCountPosition='1' countType='invalid'>" + "<sequence>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"numeric\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Invalid countType", thrown.getOriginalMessage()); } @Test void testAnyCompositeType() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <group header='SG3' trailer='SG4'>" + " <transaction header='SG5' trailer='SG6'></transaction>" + " </group>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence>" + "<element type='E1'/>" + "<any minOccurs='0' maxOccurs='2'/>" + "</sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG4\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG5\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG6\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); Schema schema = factory.createSchema(stream); EDIComplexType segmentSG1 = (EDIComplexType) schema.getType("SG1"); assertEquals(3, segmentSG1.getReferences().size()); // Two "ANY" references refer to the same object assertSame(segmentSG1.getReferences().get(1), segmentSG1.getReferences().get(2)); } @Test void testAnyElementType() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<interchange header='SG1' trailer='SG2'>" + "<sequence>" + " <group header='SG3' trailer='SG4'>" + " <transaction header='SG5' trailer='SG6'></transaction>" + " </group>" + "</sequence>" + "</interchange>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<compositeType name=\"C001\"><sequence><any maxOccurs='5'/></sequence></compositeType>" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG4\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG5\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG6\"><sequence><composite type='C001'/></sequence></segmentType>" + "</schema>").getBytes()); Schema schema = factory.createSchema(stream); EDIComplexType segmentSG6 = (EDIComplexType) schema.getType("SG6"); assertEquals(1, segmentSG6.getReferences().size()); // Two "ANY" references refer to the same object assertEquals("C001", segmentSG6.getReferences().get(0).getReferencedType().getId()); assertEquals(5, ((EDIComplexType) segmentSG6.getReferences().get(0).getReferencedType()).getReferences().size()); } @Test void testAnySegmentTypeInvalid() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + "<transaction header='SG1' trailer='SG2'>" + "<sequence>" + " <segment type='SG3'/>" + " <any maxOccurs='2' />" + "</sequence>" + "</transaction>" + "<elementType name=\"E1\" base=\"string\" maxLength=\"5\" />" + "<segmentType name=\"SG1\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG2\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG3\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG4\"><sequence><element type='E1'/></sequence></segmentType>" + "<segmentType name=\"SG5\"><sequence><element type='E1'/></sequence></segmentType>" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Element {" + StaEDISchemaFactory.XMLNS_V3 + "}any may only be present for segmentType and compositeType", thrown.getOriginalMessage()); } @Test void testInvalidIncludeV2() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V2 + "'>" + " <include schemaLocation='./src/test/x12/EDISchema997.xml' />" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Unexpected XML element [{" + StaEDISchemaFactory.XMLNS_V2 + "}include]", thrown.getOriginalMessage()); } @Test void testInvalidIncludeV3() { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V3 + "'>" + " <include schemaLocation='./src/test/x12/EDISchema997.xml' />" + "</schema>").getBytes()); EDISchemaException thrown = assertThrows(EDISchemaException.class, () -> factory.createSchema(stream)); assertEquals("Unexpected XML element [{" + StaEDISchemaFactory.XMLNS_V3 + "}include]", thrown.getOriginalMessage()); } @Test void testValidIncludeV4() throws EDISchemaException { SchemaFactory factory = SchemaFactory.newFactory(); InputStream stream = new ByteArrayInputStream(("" + "<schema xmlns='" + StaEDISchemaFactory.XMLNS_V4 + "'>" + " <include schemaLocation='file:./src/test/resources/x12/EDISchema997.xml' />" + " <elementType name=\"DUMMY\" base=\"string\" maxLength=\"5\" />"
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/SyntaxRestrictionTest.java
src/test/java/io/xlate/edi/internal/schema/SyntaxRestrictionTest.java
package io.xlate.edi.internal.schema; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDISyntaxRule; class SyntaxRestrictionTest { @Test void testConstructorEmptyList() { List<Integer> positions = Collections.emptyList(); assertThrows(IllegalArgumentException.class, () -> new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, positions)); } @Test void testToString() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals("type: PAIRED, positions: [1, 2]", rule.toString()); } @Test void testGetType() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals(EDISyntaxRule.Type.PAIRED, rule.getType()); } @Test void testGetPositions() { EDISyntaxRule rule = new SyntaxRestriction(EDISyntaxRule.Type.PAIRED, Arrays.asList(1, 2)); assertEquals(Arrays.asList(1, 2), rule.getPositions()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/implementation/SegmentImplTest.java
src/test/java/io/xlate/edi/internal/schema/implementation/SegmentImplTest.java
package io.xlate.edi.internal.schema.implementation; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.schema.implementation.ElementImplementation; import io.xlate.edi.schema.implementation.SegmentImplementation; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; class SegmentImplTest { @Test void testElementTypeDescriptionAccess() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "GS*HC*99999999999*888888888888*20111219*1340*1*X*005010X222~" + "ST*837*0001*005010X222~" + "BHT*0019*00*565743*20110523*154959*CH~" + "NM1*41*2*SAMPLE INC*****46*496103~" + "PER*IC*EDI DEPT*EM*FEEDBACK@example.com*TE*3305551212~" + "NM1*40*2*PPO BLUE*****46*54771~" + "HL*1**20*1~" + "SE*7*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); List<EDIReference> nm1references = new ArrayList<>(); while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: reader.setTransactionSchema(SchemaFactory.newFactory() .createSchema(getClass().getResource("/x12/005010X222/837_loop1000_only.xml"))); break; case START_SEGMENT: if ("NM1".equals(reader.getReferenceCode())) { nm1references.add(reader.getSchemaTypeReference()); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); System.out.println("Unexpected error: " + reader.getErrorType() + "; " + reader.getText() + "; " + reader.getLocation()); break; default: break; } } assertEquals(0, errors.size(), () -> errors.toString()); assertEquals(2, nm1references.size()); // Values set in 837_loop1000_only.xml assertEquals("Submitter Name", nm1references.get(0).getTitle()); assertEquals(Collections.singletonMap("41", "Submitter"), getElementValues(nm1references.get(0), 0)); assertEquals("Receiver Name", nm1references.get(1).getTitle()); assertEquals(Collections.singletonMap("40", "Receiver"), getElementValues(nm1references.get(1), 0)); // Values of NM1 standard set in 837.xml assertEquals("Individual or Organizational Name", nm1references.get(0).getReferencedType().getTitle()); assertEquals("Individual or Organizational Name", nm1references.get(1).getReferencedType().getTitle()); } Map<String, String> getElementValues(EDIReference segRef, int position) { SegmentImplementation impl = (SegmentImplementation) segRef; ElementImplementation ele = (ElementImplementation) impl.getSequence().get(position); return ele.getValues(); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/implementation/ElementImplTest.java
src/test/java/io/xlate/edi/internal/schema/implementation/ElementImplTest.java
package io.xlate.edi.internal.schema.implementation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNull; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.Test; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.EDISimpleType; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.SchemaFactory; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.test.StaEDITestUtil; class ElementImplTest { final int DFLT_MIN_OCCURS = 1; final int DFLT_MAX_OCCURS = 9; final String DFLT_ID = "E0001"; final int DFLT_POSITION = 1; final Map<String, String> DFLT_VALUES = Collections.emptyMap(); final String DFLT_TITLE = "Test Element"; final String DFLT_DESCR = "Just for testing"; @Test void testHashCode() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); ElementImpl e2 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); ElementImpl e3 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, 2, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); assertNotSame(e2, e1); assertEquals(e1.hashCode(), e2.hashCode()); assertNotEquals(e1.hashCode(), e3.hashCode()); } @Test void testEquals() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); ElementImpl e2 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); assertEquals(e1, e2); } @Test void testEquals_Identity() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); assertEquals(e1, e1); } @Test void testEquals_NotInstances() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); for (Object other : Arrays.asList(new Object(), null)) { assertNotEquals(e1, other); } } @Test void testEquals_DifferentPosition() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); ElementImpl e2 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, 2, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); assertNotEquals(e1, e2); } @Test void testEquals_DifferentValueSet() { Map<String, String> v1 = Collections.singletonMap("A", "Title A"); Map<String, String> v2 = Collections.singletonMap("B", "Title B"); ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, v1, DFLT_TITLE, DFLT_DESCR); ElementImpl e2 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, v2, DFLT_TITLE, DFLT_DESCR); assertNotEquals(e1, e2); } @Test void testEquals_DifferentBaseImplValues() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); assertNotEquals(e1, new ElementImpl(2, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR)); assertNotEquals(e1, new ElementImpl(DFLT_MIN_OCCURS, 10, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR)); assertNotEquals(e1, new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, "E0002", DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR)); assertNotEquals(e1, new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, "Another Title", DFLT_DESCR)); assertNotEquals(e1, new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, "Do not use!")); EDISimpleType standard = new EDISimpleType() { @Override public String getId() { return "E0003"; } @Override public String getCode() { return "3"; } @Override public Type getType() { return Type.ELEMENT; } @Override public Base getBase() { return Base.STRING; } @Override public int getNumber() { return 3; } @Override public long getMinLength() { return 0; } @Override public long getMaxLength() { return 5; } @Override public Set<String> getValueSet() { return Collections.emptySet(); } @Override public Map<String, String> getValues() { return Collections.emptyMap(); } @Override public String getTitle() { return null; } @Override public String getDescription() { return null; } }; EDIReference reference = new EDIReference() { @Override public EDIType getReferencedType() { return standard; } @Override public int getMinOccurs() { return DFLT_MIN_OCCURS; } @Override public int getMaxOccurs() { return DFLT_MAX_OCCURS; } @Override public String getTitle() { return null; } @Override public String getDescription() { return null; } }; ElementImpl e3 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); e3.setStandardReference(reference); assertNotEquals(e1, e3); } @Test void testToString() { ElementImpl e1 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); ElementImpl e2 = new ElementImpl(DFLT_MIN_OCCURS, DFLT_MAX_OCCURS, DFLT_ID, DFLT_POSITION, DFLT_VALUES, DFLT_TITLE, DFLT_DESCR); assertEquals(e1.toString(), e2.toString()); } @Test void testElementTypeDescriptionAccess() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "GS*HC*99999999999*888888888888*20111219*1340*1*X*005010X222~" + "ST*837*0001*005010X222~" + "BHT*0019*00*565743*20110523*154959*CH~" + "NM1*41*2*SAMPLE INC*****46*496103~" + "PER*IC*EDI DEPT*EM*FEEDBACK@example.com*TE*3305551212~" + "NM1*40*2*PPO BLUE*****46*54771~" + "HL*1**20*1~" + "HL*2*1*22*0~" + "SE*8*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); List<EDIReference> nm103references = new ArrayList<>(); while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: reader.setTransactionSchema(SchemaFactory.newFactory() .createSchema(getClass().getResource("/x12/005010X222/837_loop1000_only.xml"))); break; case ELEMENT_DATA: if ("NM103".equals(reader.getReferenceCode())) { nm103references.add(reader.getSchemaTypeReference()); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); System.out.println("Unexpected error: " + reader.getErrorType() + "; " + reader.getText() + "; " + reader.getLocation()); break; default: break; } } assertEquals(0, errors.size(), () -> errors.toString()); // Values set in 837_loop1000_only.xml assertEquals(2, nm103references.size()); assertEquals("Submitter Last or Organization Name", nm103references.get(0).getTitle()); assertEquals("Receiver Name", nm103references.get(1).getTitle()); // Values of NM103 standard set in 837.xml assertEquals("Name Last or Organization Name", nm103references.get(0).getReferencedType().getTitle()); assertEquals("Name Last or Organization Name", nm103references.get(1).getReferencedType().getTitle()); } @Test void testElementTypeDescriptionAccessOnDescriminator() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "GS*HC*99999999999*888888888888*20111219*1340*1*X*005010X222~" + "ST*837*0001*005010X222~" + "BHT*0019*00*565743*20110523*154959*CH~" + "NM1*41*2*SAMPLE INC*****46*496103~" + "PER*IC*EDI DEPT*EM*FEEDBACK@example.com*TE*3305551212~" + "NM1*40*2*PPO BLUE*****46*54771~" + "HL*1**20*1~" + "SE*7*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); List<EDIReference> nm101references = new ArrayList<>(); while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: reader.setTransactionSchema(SchemaFactory.newFactory() .createSchema(getClass().getResource("/x12/005010X222/837_loop1000_only.xml"))); break; case ELEMENT_DATA: if ("NM101".equals(reader.getReferenceCode())) { nm101references.add(reader.getSchemaTypeReference()); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); System.out.println("Unexpected error: " + reader.getErrorType() + "; " + reader.getText() + "; " + reader.getLocation()); break; default: break; } } assertEquals(0, errors.size(), () -> errors.toString()); // Values set in 837_loop1000_only.xml assertEquals(2, nm101references.size()); assertEquals("Entity Identifier Code (Submitter)", nm101references.get(0).getTitle()); assertEquals("Entity Identifier Code (Receiver)", nm101references.get(1).getTitle()); // Values of NM101 standard set in 837.xml assertEquals("Entity Identifier Code", nm101references.get(0).getReferencedType().getTitle()); assertEquals("Entity Identifier Code", nm101references.get(1).getReferencedType().getTitle()); } @Test void testElementTypeDescriptionAccessPriorToDescriminator() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "GS*HC*99999999999*888888888888*20111219*1340*1*X*005010X222~" + "ST*837*0001*005010X222~" + "BHT*0019*00*565743*20110523*154959*CH~" + "NM1*41*2*SAMPLE INC*****46*496103~" + "PER*IC*EDI DEPT*EM*FEEDBACK@example.com*TE*3305551212~" + "NM1*40*2*PPO BLUE*****46*54771~" + "HL*1**20*1~" + "SE*7*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = factory.createEDIStreamReader(stream); List<EDIStreamValidationError> errors = new ArrayList<>(); List<EDIReference> hlReferences = new ArrayList<>(); while (reader.hasNext()) { switch (reader.next()) { case START_TRANSACTION: reader.setTransactionSchema(SchemaFactory.newFactory() .createSchema(getClass().getResource("/x12/005010X222/837_loop1000_only.xml"))); break; case ELEMENT_DATA: if ("HL".equals(reader.getLocation().getSegmentTag())) { hlReferences.add(reader.getSchemaTypeReference()); } break; case SEGMENT_ERROR: case ELEMENT_OCCURRENCE_ERROR: case ELEMENT_DATA_ERROR: errors.add(reader.getErrorType()); System.out.println("Unexpected error: " + reader.getErrorType() + "; " + reader.getText() + "; " + reader.getLocation()); break; default: break; } } assertEquals(0, errors.size(), () -> errors.toString()); // Values set in 837_loop1000_only.xml, except for offset `1` assertEquals(4, hlReferences.size()); assertEquals("Hierarchical ID Number (20)", hlReferences.get(0).getTitle()); assertNull(hlReferences.get(1).getTitle()); assertEquals("Hierarchical Level Code (20)", hlReferences.get(2).getTitle()); assertEquals("Hierarchical Child Code (20)", hlReferences.get(3).getTitle()); // Values of NM101 standard set in 837.xml assertEquals("Hierarchical ID Number", hlReferences.get(0).getReferencedType().getTitle()); assertEquals("Hierarchical Parent ID Number", hlReferences.get(1).getReferencedType().getTitle()); assertEquals("Hierarchical Level Code", hlReferences.get(2).getReferencedType().getTitle()); assertEquals("Hierarchical Child Code", hlReferences.get(3).getReferencedType().getTitle()); } @Test void testImplElementsPriorToDiscriminatorAreValidated() throws EDIStreamException, EDISchemaException { EDIInputFactory factory = EDIInputFactory.newFactory(); ByteArrayInputStream stream = new ByteArrayInputStream(("" + "ISA*00* *00* *ZZ*ReceiverID *ZZ*Sender *200711*0100*^*00501*000000001*0*T*:~" + "GS*HC*99999999999*888888888888*20111219*1340*1*X*005010X222~" + "ST*837*0001*005010X222~" + "BHT*0019*00*565743*20110523*154959*CH~" + "NM1*41*2*SAMPLE INC*****46*496103~" + "PER*IC*EDI DEPT*EM*FEEDBACK@example.com*TE*3305551212~" + "NM1*40*2*PPO BLUE*****46*54771~" + "HL*1*BAD*20*1~" + "HL*2**22*0~" + "SE*6*0001~" + "GE*1*1~" + "IEA*1*000000001~").getBytes()); EDIStreamReader reader = StaEDITestUtil.filterEvents(factory, factory.createEDIStreamReader(stream), EDIStreamEvent.START_TRANSACTION, EDIStreamEvent.SEGMENT_ERROR, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamEvent.ELEMENT_DATA_ERROR); assertEquals(EDIStreamEvent.START_TRANSACTION, reader.next()); reader.setTransactionSchema(SchemaFactory.newFactory() .createSchema(getClass().getResource("/x12/005010X222/837_loop1000_only.xml"))); assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.next()); assertEquals(EDIStreamValidationError.IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT, reader.getErrorType()); assertEquals("BAD", reader.getText()); assertEquals(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, reader.next()); assertEquals(EDIStreamValidationError.REQUIRED_DATA_ELEMENT_MISSING, reader.getErrorType()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/test/java/io/xlate/edi/internal/schema/implementation/DiscriminatorImplTest.java
src/test/java/io/xlate/edi/internal/schema/implementation/DiscriminatorImplTest.java
package io.xlate.edi.internal.schema.implementation; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import io.xlate.edi.internal.schema.ElementPosition; import io.xlate.edi.schema.EDIElementPosition; class DiscriminatorImplTest { DiscriminatorImpl target; @BeforeEach void setUp() throws Exception { target = new DiscriminatorImpl(position(1, 2), Collections.singleton("50")); } ElementPosition position(int e, int c) { return new ElementPosition(e, c); } @Test void testHashCode() { int expected = new DiscriminatorImpl(position(1, 2), Collections.singleton("50")).hashCode(); assertEquals(expected, target.hashCode()); } @Test void testEquals_Same() { assertEquals(target.position, target.position); assertEquals(target, target); } @Test void testEquals_Identical() { DiscriminatorImpl identical = new DiscriminatorImpl(position(1, 2), Collections.singleton("50")); assertEquals(target.position, identical.position); assertEquals(target, identical); } @Test void testEquals_NotInstance() { for (Object other : Arrays.asList(new Object(), null)) { assertNotEquals(target, other); } } @Test void testEquals_PositionNotInstance() { DiscriminatorImpl actual = new DiscriminatorImpl(new EDIElementPosition() { @Override public int getComponentPosition() { return 1; } @Override public int getElementPosition() { return 2; } }, Collections.singleton("50")); assertNotEquals(target, actual); } @Test void testEquals_Different() { assertNotEquals(new DiscriminatorImpl(position(1, 2), Collections.singleton("60")), target); assertNotEquals(new DiscriminatorImpl(position(2, 2), Collections.singleton("50")), target); assertNotEquals(new DiscriminatorImpl(position(1, 3), Collections.singleton("50")), target); } @Test void testToString() { String expected = new DiscriminatorImpl(position(1, 2), Collections.singleton("50")).toString(); assertEquals(expected, target.toString()); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java9/module-info.java
src/main/java9/module-info.java
/** * StAEDI is a streaming API for EDI reading, writing, and validation in Java. * * @author Michael Edgar * @see <a href="https://github.com/xlate/staedi" target="_blank">StAEDI on GitHub</a> */ module io.xlate.staedi { requires java.base; requires java.logging; requires transitive java.xml; exports io.xlate.edi.schema; exports io.xlate.edi.schema.implementation; exports io.xlate.edi.stream; }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/PropertySupport.java
src/main/java/io/xlate/edi/stream/PropertySupport.java
/******************************************************************************* * Copyright 2020 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Abstract parent class for factories that support setting, retrieving, and checking * whether properties are supported. */ public abstract class PropertySupport { /** * Set of property keys/names supported by the subclass. */ protected final Set<String> supportedProperties; /** * Map of properties actually configured by the subclass. */ protected final Map<String, Object> properties; /** * Default constructor, initialize fields to empty collections. */ protected PropertySupport() { this.supportedProperties = new HashSet<>(); this.properties = new HashMap<>(); } /** * Query the set of properties that this factory supports. * * @param name * - The name of the property (may not be null) * @return true if the property is supported and false otherwise */ public boolean isPropertySupported(String name) { return supportedProperties.contains(name); } /** * Get the value of a feature/property from the underlying implementation * * @param name * - The name of the property (may not be null) * @return The value of the property * @throws IllegalArgumentException * if the property is not supported */ public Object getProperty(String name) { if (!isPropertySupported(name)) { throw new IllegalArgumentException("Unsupported property: " + name); } return properties.get(name); } /** * Allows the user to set specific feature/property on the underlying * implementation. The underlying implementation is not required to support * every setting of every property in the specification and may use * IllegalArgumentException to signal that an unsupported property may not * be set with the specified value. * * @param name * - The name of the property (may not be null) * @param value * - The value of the property * @throws IllegalArgumentException * if the property is not supported */ public void setProperty(String name, Object value) { if (!isPropertySupported(name)) { throw new IllegalArgumentException("Unsupported property: " + name); } properties.put(name, value); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamReader.java
src/main/java/io/xlate/edi/stream/EDIStreamReader.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.NoSuchElementException; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.Schema; import io.xlate.edi.schema.implementation.EDITypeImplementation; /** * The EDIStreamReader interface allows forward, read-only access to EDI. It is * designed to be the lowest level and most efficient way to read EDI data. * * <p> * The EDIStreamReader is designed to iterate over EDI using {@link #next()} and * {@link #hasNext()}. The data can be accessed using methods such as * {@link #getEventType()} and {@link #getText()}. */ public interface EDIStreamReader extends Closeable, EDIStreamConstants { /** * Get the value of a feature/property from the underlying implementation * * @param name * - The name of the property, may not be null * @return The value of the property * @throws IllegalArgumentException * if name is null */ Object getProperty(String name); /** * Retrieve a read-only map of delimiters in use for the stream being read. * * @return The value of the property * @throws IllegalStateException * if called outside of an interchange */ Map<String, Character> getDelimiters(); /** * Get next parsing event * * @return the event type corresponding to the current parse event * @throws NoSuchElementException * if this is called when hasNext() returns false * @throws EDIStreamException * if there is an error processing the underlying EDI source */ EDIStreamEvent next() throws EDIStreamException; /** * Skips any ELEMENT_DATA, START_COMPOSITE, and END_COMPOSITE until a * START_SEGMENT is reached. * * @return the event type of the element read - START_SEGMENT * @throws NoSuchElementException * if this is called when hasNext() returns false or there are * no additional START_SEGMENT events in the stream * @throws EDIStreamException * if the current event is not following START_INTERCHANGE and * preceding END_INTERCHANGE */ EDIStreamEvent nextTag() throws EDIStreamException; /** * Returns true if there are more parsing events and false if there are no * more events. This method will return false if the current state of the * EDIStreamReader is END_INTERCHANGE * * @return true if there are more events, false otherwise * @throws EDIStreamException * if there is a fatal error detecting the next state */ boolean hasNext() throws EDIStreamException; /** * Frees any resources associated with this Reader. This method does not * close the underlying input stream. * * @throws IOException * if there are errors freeing associated resources */ @Override void close() throws IOException; /** * Returns an integer code that indicates the type of the event the cursor * is pointing to. * * @return code that indicates the type of the event the cursor is pointing * to */ EDIStreamEvent getEventType(); /** * Get the EDI standard name. Calls to this method are only valid when the * interchange type has been determined, after START_INTERCHANGE. * * @return the name of the EDI standard * @throws IllegalStateException * when the standard has not yet been determined, prior to the * start of an interchange */ String getStandard(); /** * Get the interchange version declared on the interchange begin segment. * Calls to this method are only valid when interchange type has been * determined, after START_INTERCHANGE. * * The elements of the returned array are specific to the standard: * * <p> * For EDIFACT: * <ol> * <li>Syntax identifier: UNB01-1 * <li>Syntax version number: UNB01-2 * <li>Service code list directory version number: UNB01-3 (syntax version 4+) * <li>Character encoding, coded: UNB01-4 (syntax version 4+) * <li>Syntax release number: UNB01-5 (syntax version and release 4.1+) * </ol> * <p> * For X12: * <ol> * <li>Interchange Control Version Number: ISA12 * </ol> * <p> * For TRADACOMS: * <ol> * <li>Syntax rules identifier: STX01-1 * <li>Syntax rules version: STX01-2 * </ol> * * @return the version * @throws IllegalStateException * when the version has not yet been determined, prior to the * start of an interchange */ String[] getVersion(); /** * Get the transaction version declared on the transaction header segment or * the functional group header segment (X12 only). Calls to this method are * only valid when interchange type has been determined, after * START_INTERCHANGE, and the transaction version has been determined by * reading the dialect-specific data elements containing the version * value(s). * * The elements of the returned array are defined as: * <ol> * <li>Agency code * <li>Version * <li>Release * <li>Industry code * </ol> * * In practice, the values will be the following elements: * <p> * For EDIFACT: * <ol> * <li>Agency code: UNH02-4 * <li>Version: UNH02-2 * <li>Release: UNH02-3 * <li>Industry code: UNH02-5 * </ol> * <p> * For X12: * <ol> * <li>Agency code: GS07 * <li>Version/Release/Industry code: GS08 (or ST03, when used) * </ol> * * @return the transaction version * @throws IllegalStateException * when the version has not yet been determined, prior to the * start of a transaction (or functional group when in use) * * @since 1.9 */ String[] getTransactionVersion(); /** * The transaction version string elements as a single, period-delimited * value. This value may be used to obtain version-specific schema * information available from the {@link EDIReference} returned from * {@link #getSchemaTypeReference()}. * * @return the transaction version as a single, period-delimited value * @throws IllegalStateException * when the version has not yet been determined, prior to the * start of a transaction (or functional group when in use) * * @since 1.9 */ String getTransactionVersionString(); /** * The transaction type string as received in a standard-specific location. * For example, the ST01 or UNH02-1 elements. * * @return the transaction type * @throws IllegalStateException * when the type has not yet been determined, prior to the * parsing of the transaction begin segment * * @since 1.16 */ String getTransactionType(); /** * Returns the control schema currently set on the reader. If none has been * set, then null will be returned. * * @return the control schema current set on this reader, may be null * * @since 1.5 */ Schema getControlSchema(); /** * <p> * Sets the schema to be used for validation of the control structure for * this stream reader. This schema will be used to validate interchange, * group, and transaction/message envelopes. * <p> * Calls to this method are only valid when the current event type is * START_INTERCHANGE. * * @param schema * the schema instance to use for validation of control * structures * @throws IllegalStateException * when the current event type is not START_INTERCHANGE */ void setControlSchema(Schema schema); /** * Returns the schema currently set on the reader to be used for validation * of the business transaction. If none has been set, then null will be * returned. * * @return the transaction schema current set on this reader, may be null * * @since 1.5 */ Schema getTransactionSchema(); /** * <p> * Sets the schema to be used for validation of the business transaction for * this stream reader. This schema will be used to validate only the * contents of a transaction/message, <em>not including</em> the begin/end * control structures. * <p> * Calls to this method are only valid after a START_TRANSACTION event and * up to and including the END_SEGMENT event representing the beginning of * the transaction. * * @param schema * the schema instance to use for validation of business * transaction structures * @throws IllegalStateException * when the reader is not positioned on the start transaction * segment */ void setTransactionSchema(Schema schema); /** * Return the reference code for the current element if a schema has been * set and the current processing state is within an interchange. Otherwise, * an IllegalStateException will be thrown. * * If the reader encounters an unknown type, the reference code will be * null. * * @return the reference code from the schema for the current EDIType * @throws IllegalStateException * when the current event type is not within an interchange */ String getReferenceCode(); /** * Returns an integer code that indicates the type of error the cursor is * pointing to. Calls to this method are only valid when the current event * type is SEGMENT_ERROR or ELEMENT_ERROR. * * @return code that indicates the type of the error the cursor is pointing * to * @throws IllegalStateException * when the current event type is not SEGMENT_ERROR or * ELEMENT_ERROR */ EDIStreamValidationError getErrorType(); /** * Returns the current value of the parse event as a string. This returns * * <ul> * <li>the string value of an element for an * {@link EDIStreamEvent#ELEMENT_DATA ELEMENT_DATA} event * <li>the string value of a segment tag for a * {@link EDIStreamEvent#START_SEGMENT START_SEGMENT} event * <li>the string value of the current segment tag for an * {@link EDIStreamEvent#END_SEGMENT END_SEGMENT} event * <li>the invalid element text from an * {@link EDIStreamEvent#ELEMENT_DATA_ERROR ELEMENT_DATA_ERROR} (when * available) * <li>the invalid element text from an * {@link EDIStreamEvent#ELEMENT_OCCURRENCE_ERROR ELEMENT_OCCURRENCE_ERROR} * (when available) * <li>the string value of a segment tag for a * {@link EDIStreamEvent#SEGMENT_ERROR SEGMENT_ERROR} event * </ul> * * @return the current text or an empty {@link java.lang.String String} * @throws IllegalStateException * if this state is not a valid text state */ String getText(); /** * Returns an array which contains the characters from this event (as * specified by {@link #getText}). This array should be treated as read-only * and transient. I.e. the array will contain the text characters until the * EDIStreamReader moves on to the next event. Attempts to hold onto the * character array beyond that time or modify the contents of the array are * breaches of the contract for this interface. * * @return the current text or an empty array * @throws IllegalStateException * if this state is not a valid text state */ char[] getTextCharacters(); /** * Returns the the text associated with an event (as specified by * {@link #getText}). Text starting at "sourceStart" is copied into "target" * starting at "targetStart". Up to "length" characters are copied. The * number of characters actually copied is returned. The "sourceStart" * argument must be greater or equal to 0 and less than or equal to the * number of characters associated with the event. Usually, one requests * text starting at a "sourceStart" of 0. If the number of characters * actually copied is less than the "length", then there is no more text. * Otherwise, subsequent calls need to be made until all text has been * retrieved. * * For example: * * <pre> * int length = 1024; * char[] myBuffer = new char[length]; * * for (int sourceStart = 0;; sourceStart += length) { * int nCopied = stream.getTextCharacters(sourceStart, myBuffer, 0, length); * if (nCopied &lt; length) * break; * } * </pre> * * EDIStreamException may be thrown if there are any parsing errors in the * underlying source. The "targetStart" argument must be greater than or * equal to 0 and less than the length of "target", Length must be greater * than 0 and "targetStart + length" must be less than or equal to length of * "target". * * @param sourceStart * - the index of the first character in the source array to copy * @param target * - the destination array * @param targetStart * - the start offset in the target array * @param length * - the number of characters to copy * @return the number of characters actually copied * @throws IndexOutOfBoundsException * if targetStart &lt; 0 or &gt; than the length of target * @throws IndexOutOfBoundsException * if length &lt; 0 or targetStart + length &gt; length of * target * @throws NullPointerException * if target is null */ int getTextCharacters(int sourceStart, char[] target, int targetStart, int length); /** * Returns the offset into the text character array where the first * character (of this text event) is stored. * * @return offset into the text character array where the first character is * stored * @throws IllegalStateException * if this state is not a valid text state */ int getTextStart(); /** * Returns the length of the sequence of characters for this Text event * within the text character array. * * @return length of the sequence of characters for this Text event * @throws IllegalStateException * if this state is not a valid text state */ int getTextLength(); /** * Return the current location of the processor. If the Location is unknown * the processor should return an implementation of Location that returns -1 * for the location values. The location information is only valid until * next() is called. * * @return current location of the processor */ Location getLocation(); /** * Sets the number of bytes that should be read as binary data and not * interpreted as EDI data. This EDIStreamReader will return to normal EDI * parsing after reading this number of bytes. The byte immediately * following length bytes must be a delimiter valid in the scope of the * current interchange or an EDIStreamException will occur. * * This method must only be called immediately preceding a binary data * element. Attempts to call it while the reader is in any other state will * result in an IllegalStateException. * * <p> * Note: Applications parsing transactions which contain binary data * elements must call this method to avoid the binary data being parsed as * EDI content. The length of the binary data is typically found in a * companion data element preceding the binary element in the stream. * </p> * * @param length * - the number of bytes to read as binary data and not as * EDI-formatted * @throws IllegalStateException * if this state is not a state which may precede a data * element. * @throws EDIStreamException * if there are IO errors allocating resources for binary data * processing */ void setBinaryDataLength(long length) throws EDIStreamException; /** * Returns an InputStream for reading the binary element data for the current * element. The length of the input stream is determined by the value previously * passed to {@link #setBinaryDataLength(long)}. * * @return stream containing binary data * @throws IllegalStateException * if the stream reader did not complete the scanning of a * binary data element immediately preceding this call. */ InputStream getBinaryData(); /** * Returns an {@link EDIReference} for the schema type at the current point * in the reader's input stream. Information such as minimum and maximum * occurrences, as well as the {@link EDIType} may be obtained from the * reference. If the reader is utilizing an implementation schema and the * current schema type is an implemented type, the returned reference will * be an {@link EDITypeImplementation}. * * @return an {@link EDIReference} for the schema type at the current point * in the reader's input stream * * @since 1.9 */ EDIReference getSchemaTypeReference(); /** * Return true if the current event has text, false otherwise. The following * events have text: * <ul> * <li>START_SEGMENT * <li>END_SEGMENT * <li>ELEMENT_DATA * <li>ELEMENT_DATA_ERROR * <li>ELEMENT_OCCURRENCE_ERROR * <li>SEGMENT_ERROR * </ul> * * @return true if the current event has text, false otherwise * @since 1.20 */ boolean hasText(); }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIInputFactory.java
src/main/java/io/xlate/edi/stream/EDIInputFactory.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; import java.io.InputStream; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import io.xlate.edi.schema.Schema; /** * Defines an abstract implementation of a factory for getting EDIStreamReaders, * JSON parsers (wrapping an existing EDIStreamReader), and XMLStreamReaders * (wrapping an existing EDIStreamReader). An EDIInputErrorReporter may also be * configured via the factory for use with each new EDIStreamReader created. */ public abstract class EDIInputFactory extends PropertySupport { /** * When set to false, control structures, segments, elements, and codes will * not be validated unless a user-provided control schema has been set using * {@link EDIStreamReader#setControlSchema(Schema)}. * * When set to true AND no user-provided control schema has been set, the * reader will attempt to find a known control schema for the detected EDI * dialect and version to be used for control structure validation. * * Default value: true */ public static final String EDI_VALIDATE_CONTROL_STRUCTURE = "io.xlate.edi.stream.EDI_VALIDATE_CONTROL_STRUCTURE"; /** * When set to false, enumerated code values of control structure elements * will be ignore. Element size and type validation will still occur. */ public static final String EDI_VALIDATE_CONTROL_CODE_VALUES = "io.xlate.edi.stream.EDI_VALIDATE_CONTROL_CODE_VALUES"; /** * When set to true, XMLStreamReader instances created from an * EDIInputFactory will generate XMLNS attributes on the TRANSACTION element * in addition to the INTERCHANGE element. */ public static final String XML_DECLARE_TRANSACTION_XMLNS = "io.xlate.edi.stream.XML_DECLARE_TRANSACTION_XMLNS"; /** * When set to true, XMLStreamReader instances created from an * EDIInputFactory will generate an element wrapper around the transaction's * content element. The wrapper will not contain the elements representing * the transaction's header and trailer segments. * * The wrapper element will be in the {@link EDINamespaces#LOOPS LOOPS} XML * name space and the local name will be constructed as follows: <br> * {@code <Standard Name> + '-' + <Transaction Code> + '-' + <Transaction Version String>} * * @since 1.16 */ public static final String XML_WRAP_TRANSACTION_CONTENTS = "io.xlate.edi.stream.XML_WRAP_TRANSACTION_CONTENTS"; /** * When set to true, the XML elements representing segments in an EDI implementation schema * will be named according to the schema-defined {@code code} attribute for the segment. * * Default value: false * * @since 1.21 */ public static final String XML_USE_SEGMENT_IMPLEMENTATION_CODES = "io.xlate.edi.stream.XML_USE_SEGMENT_IMPLEMENTATION_CODES"; /** * When set to true, non-graphical, control characters will be ignored in * the EDI input stream. This includes characters ranging from 0x00 through * 0x1F and 0x7F. * * @since 1.13 */ public static final String EDI_IGNORE_EXTRANEOUS_CHARACTERS = "io.xlate.edi.stream.EDI_IGNORE_EXTRANEOUS_CHARACTERS"; /** * When set to true, hierarchical loops will be nested in the EDI input * stream. The nesting structure is determined by the linkage specified by * the EDI data itself using pointers given in the EDI schema for a loop. * * For example, the hierarchical information given by the X12 HL segment. * * Default value: true * * @since 1.18 */ public static final String EDI_NEST_HIERARCHICAL_LOOPS = "io.xlate.edi.stream.EDI_NEST_HIERARCHICAL_LOOPS"; /** * When set to true, functional group, transaction, and loop start/end * events will allow for {@link EDIStreamReader#getText()} to be called, * which is the legacy behavior. * * The default value is `true` and this property is deprecated. In the next * major release, the property's default value will be `false`. * * Default value: true * * @since 1.20 * @deprecated use {@link EDIStreamReader#getReferenceCode()} and * {@link EDIStreamReader#getSchemaTypeReference()} to retrieve * additional information for non-textual event types. */ @Deprecated public static final String EDI_ENABLE_LOOP_TEXT = "io.xlate.edi.stream.EDI_ENABLE_LOOP_TEXT"; // NOSONAR /** * When set to true, discriminator values from the EDI input will be trimmed * (leading and trailing whitespace removed) prior to testing whether the value * matches the enumerated values for a loop or segment defined in an implementation * schema. * * Default value: false * * @since 1.25 */ public static final String EDI_TRIM_DISCRIMINATOR_VALUES = "io.xlate.edi.stream.EDI_TRIM_DISCRIMINATOR_VALUES"; /** * When set to true, simple data elements not containing data will be * represented via the JSON parsers as a {@code null} value. * * Default value: false * * @since 1.14 */ public static final String JSON_NULL_EMPTY_ELEMENTS = "io.xlate.edi.stream.JSON_NULL_EMPTY_ELEMENTS"; /** * When set to true, simple data elements will be represented via the JSON * parsers as JSON objects. When false, simple elements will be JSON * primitive values (string, number) in the data array of their containing * structures. * * Default value: false * * @since 1.14 */ public static final String JSON_OBJECT_ELEMENTS = "io.xlate.edi.stream.JSON_OBJECT_ELEMENTS"; /** * Create a new instance of the factory. This static method creates a new * factory instance. * * Once an application has obtained a reference to an EDIInputFactory it can * use the factory to configure and obtain stream instances. * * @return the factory implementation */ public static EDIInputFactory newFactory() { return new io.xlate.edi.internal.stream.StaEDIInputFactory(); } /** * Default constructor */ protected EDIInputFactory() { } /** * Creates a new {@link EDIStreamReader} using the given {@link InputStream} * (with default encoding). * * @param stream * {@link InputStream} from which the EDI data will be read * @return a new {@link EDIStreamReader} which reads from the stream */ public abstract EDIStreamReader createEDIStreamReader(InputStream stream); /** * Creates a new {@link EDIStreamReader} using the given {@link InputStream} * and encoding. The encoding must be a valid * {@link java.nio.charset.Charset Charset}. * * @param stream * {@link InputStream} from which the EDI data will be read * @param encoding * character encoding of the stream, must be a valid * {@link java.nio.charset.Charset Charset}. * @return a new {@link EDIStreamReader} which reads from the stream * @throws EDIStreamException * when encoding is not supported */ public abstract EDIStreamReader createEDIStreamReader(InputStream stream, String encoding) throws EDIStreamException; /** * Creates a new {@link EDIStreamReader} using the given {@link InputStream} * (with default encoding) which uses the {@link Schema} for validation of * the input's control structures (interchange, group, transaction). * * Note that a separate schema for validation of messages/transactions may * be passed directly to the {@link EDIStreamReader} once the type and * version of the messages is known. * * @param stream * {@link InputStream} from which the EDI data will be read * @param schema * {@link Schema} for control structure validation * @return a new {@link EDIStreamReader} which reads from the stream */ public abstract EDIStreamReader createEDIStreamReader(InputStream stream, Schema schema); /** * Creates a new {@link EDIStreamReader} using the given {@link InputStream} * and encoding which uses the {@link Schema} for validation of the input's * control structures (interchange, group, transaction). The encoding must * be a valid {@link java.nio.charset.Charset Charset}. * * Note that a separate schema for validation of messages/transactions may * be passed directly to the {@link EDIStreamReader} once the type and * version of the messages is known. * * @param stream * {@link InputStream} from which the EDI data will be read * @param encoding * character encoding of the stream, must be a valid * {@link java.nio.charset.Charset Charset}. * @param schema * {@link Schema} for control structure validation * @return a new {@link EDIStreamReader} which reads from the stream * @throws EDIStreamException * when encoding is not supported */ public abstract EDIStreamReader createEDIStreamReader(InputStream stream, String encoding, Schema schema) throws EDIStreamException; /** * Creates a new {@link EDIStreamReader} by wrapping the given reader with * the {@link EDIStreamFilter} filter. * * @param reader * the reader to wrap * @param filter * a filter to wrap the given reader * @return a new {@link EDIStreamReader} which uses filter */ public abstract EDIStreamReader createFilteredReader(EDIStreamReader reader, EDIStreamFilter filter); /** * Creates a new {@link XMLStreamReader} that uses the given reader as its * data source. The reader should be positioned before the start of an * interchange or at the start of an interchange. * * XML generated by the XMLStreamReader consist exclusively of elements in * the namespaces declared by the constants in {@link EDINamespaces}. The * names of the elements will be as follows: * * <table> * <caption>EDI Event Namespace Cross Reference</caption> * <tr> * <td>Event</td> * <td>Element Local Name</td> * <td>Element Namespace</td> * <td></td> * </tr> * <tr> * <td>Start/End of interchange</td> * <td>INTERCHANGE</td> * <td>{@link EDINamespaces#LOOPS}</td> * </tr> * <tr> * <td>Start/End of functional group</td> * <td>GROUP</td> * <td>{@link EDINamespaces#LOOPS}</td> * </tr> * <tr> * <td>Start/End of message/transaction</td> * <td>TRANSACTION</td> * <td>{@link EDINamespaces#LOOPS}</td> * </tr> * <tr> * <td>Start/End of loop</td> * <td>Loop code from EDI schema</td> * <td>{@link EDINamespaces#LOOPS}</td> * </tr> * <tr> * <td>Start/End of segment</td> * <td>Segment tag from EDI data</td> * <td>{@link EDINamespaces#SEGMENTS}</td> * </tr> * <tr> * <td>Start/End of composite</td> * <td>Segment tag plus two digit element position from EDI data</td> * <td>{@link EDINamespaces#COMPOSITES}</td> * </tr> * <tr> * <td>Start/End of simple element</td> * <td>Segment tag plus two digit element position from EDI data</td> * <td>{@link EDINamespaces#ELEMENTS}</td> * </tr> * <tr> * <td>Start/End of component element in a composite</td> * <td>Segment tag plus two digit element position from EDI data plus hyphen * plus two digit component position</td> * <td>{@link EDINamespaces#ELEMENTS}</td> * </tr> * </table> * * Errors encountered in the EDI data will result in an XMLStreamException * with a message describing the error. * * @param reader * the reader to wrap * @return a new {@link XMLStreamReader} * @throws XMLStreamException * when the reader encounters an error in creation * * @see EDINamespaces */ public abstract XMLStreamReader createXMLStreamReader(EDIStreamReader reader) throws XMLStreamException; /** * Creates a new JSON parser of type <code>J</code> that uses the given * reader as its data source. The reader should be positioned before the * start of an interchange or at the start of an interchange. * * @param <J> * the type of the parser being created * @param reader * the reader to wrap * @param type * the type of the parser being created * @return a new JSON parser of type <code>J</code> * * @throws IllegalArgumentException * when type is an unsupported parser type * * @since 1.14 */ public abstract <J> J createJsonParser(EDIStreamReader reader, Class<J> type); /** * Retrieves the reporter that will be set on any EDIStreamReader created by * this factory instance. * * @return the reporter that will be set on any EDIStreamReader created by * this factory instance * * @throws ClassCastException * when reporter is not an instance of EDIReporter * * @since 1.4 * @deprecated use {@link #getErrorReporter()} instead */ @SuppressWarnings({ "java:S1123", "java:S1133" }) @Deprecated /*(forRemoval = true, since = "1.9")*/ public abstract EDIReporter getEDIReporter(); /** * The reporter that will be set on any EDIStreamReader created by this * factory instance. * * NOTE: When using an EDIReporter, errors found in the data stream that are * reported to the reporter will not appear in the stream of events returned * by the EDIStreamReader. * * @param reporter * the resolver to use to report non fatal errors * * @since 1.4 * @deprecated use {@link #setErrorReporter(EDIInputErrorReporter)} instead */ @SuppressWarnings({ "java:S1123", "java:S1133" }) @Deprecated /*(forRemoval = true, since = "1.9")*/ public abstract void setEDIReporter(EDIReporter reporter); /** * Retrieves the reporter that will be set on any EDIStreamReader created by * this factory instance. * * @return the reporter that will be set on any EDIStreamReader created by * this factory instance * * @since 1.9 */ public abstract EDIInputErrorReporter getErrorReporter(); /** * The reporter that will be set on any EDIStreamReader created by this * factory instance. * * NOTE: When using an EDIReporter, errors found in the data stream that are * reported to the reporter will not appear in the stream of events returned * by the EDIStreamReader. * * @param reporter * the resolver to use to report non fatal errors * * @since 1.9 */ public abstract void setErrorReporter(EDIInputErrorReporter reporter); }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/Location.java
src/main/java/io/xlate/edi/stream/Location.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; /** * Provides information on the location of an event. * * All the information provided by a Location is optional. For example an * application may only report line numbers. * * @version 1.0 */ public interface Location { /** * Return the line number where the current event ends, returns -1 if none * is available. * * @return the current line number */ int getLineNumber(); /** * Return the column number where the current event ends, returns -1 if none * is available. * * @return the current column number */ int getColumnNumber(); /** * Return the byte or character offset into the input source this location * is pointing to. If the input source is a file or a byte stream then this * is the byte offset into that stream, but if the input source is a * character media then the offset is the character offset. Returns -1 if * there is no offset available. * * @return the current offset */ int getCharacterOffset(); /** * Return the segment position within the current stream, returns -1 if none * is available. * * @return the current segment position */ int getSegmentPosition(); /** * Return the segment tag within the current stream, returns null if none is * available. * * @return the current segment tag */ String getSegmentTag(); /** * Return the element position within the current segment, returns -1 if * none is available. * * @return the current element position */ int getElementPosition(); /** * Return the current occurrence number of a repeating data element, returns * 1 for non-repeating elements and -1 if otherwise not available. * * @return the current element occurrence */ int getElementOccurrence(); /** * Return the component data element position within the current composite * data element, returns -1 if none is available. * * @return the current component element position */ int getComponentPosition(); /** * Create a new copy of this instance * * @return a new {@link Location } instance with the same values of the instance being copied * * @since 1.11 */ Location copy(); }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIReporter.java
src/main/java/io/xlate/edi/stream/EDIReporter.java
package io.xlate.edi.stream; /** * This interface is used to report non-fatal errors detected in an EDI input. * * @since 1.4 * @deprecated implement EDIInputErrorReporter instead. This interface will be * removed in a future version of StAEDI. */ @SuppressWarnings({ "java:S1123", "java:S1133" }) @Deprecated/*(forRemoval = true, since = "1.9")*/ public interface EDIReporter extends EDIInputErrorReporter { }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDINamespaces.java
src/main/java/io/xlate/edi/stream/EDINamespaces.java
package io.xlate.edi.stream; import java.util.Arrays; import java.util.List; /** * Defines the constant values of namespaces for each of the XML elements * generated by the XMLStreamReader (created via * {@link EDIInputFactory#createXMLStreamReader(EDIStreamReader)} and consumed * by the XMLStreamWriter (created via * {@link EDIOutputFactory#createXMLStreamWriter(EDIStreamWriter)}. */ public class EDINamespaces { private EDINamespaces() { } /** * XML namespace used for all loop types: INTERCHANGE, GROUP, TRANSACTIONS, * and internal message loops. */ public static final String LOOPS = "urn:xlate.io:staedi:names:loops"; /** * XML namespace used for EDI segments */ public static final String SEGMENTS = "urn:xlate.io:staedi:names:segments"; /** * XML namespace used for EDI composite elements - those elements containing * sub-elements, i.e. components. */ public static final String COMPOSITES = "urn:xlate.io:staedi:names:composites"; /** * XML namespace used for EDI simple elements and the components * of a composite element, */ public static final String ELEMENTS = "urn:xlate.io:staedi:names:elements"; /** * Obtain a list of all namespace constants declared by {@linkplain EDINamespaces}. * * @return the list of all namespace constants */ public static final List<String> all() { return Arrays.asList(LOOPS, SEGMENTS, COMPOSITES, ELEMENTS); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIInputErrorReporter.java
src/main/java/io/xlate/edi/stream/EDIInputErrorReporter.java
package io.xlate.edi.stream; /** * This interface is used to report non-fatal errors detected in an EDI input. * * @since 1.9 */ public interface EDIInputErrorReporter { /** * Report the desired message in an application specific format. Only * warnings and non-fatal errors should be reported through this interface. * * Fatal errors will be thrown as EDIStreamException. * * @param errorType * the type of error detected * @param reader * the EDIStreamReader that encountered the error * @throws EDIStreamException * when errors occur calling the reader */ void report(EDIStreamValidationError errorType, EDIStreamReader reader) throws EDIStreamException; }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamEvent.java
src/main/java/io/xlate/edi/stream/EDIStreamEvent.java
package io.xlate.edi.stream; /** * Enumeration of stream event types that may be encountered by the * EDIStreamReader. * * @see EDIStreamReader#next() * @see EDIStreamReader#nextTag() * @see EDIStreamReader#getEventType() */ public enum EDIStreamEvent { /** * Event for a simple element or component element (within a composite). */ ELEMENT_DATA, /** * Event for binary element data * * @see EDIStreamReader#getBinaryData() */ ELEMENT_DATA_BINARY, /** * Event for the start of a composite element. */ START_COMPOSITE, /** * Event for the end of a composite element. */ END_COMPOSITE, /** * Event for the start of a segment. */ START_SEGMENT, /** * Event for the end of a segment. */ END_SEGMENT, /** * Event for the start of an interchange. */ START_INTERCHANGE, /** * Event for the end of an interchange. */ END_INTERCHANGE, /** * Event for the start of a functional group. */ START_GROUP, /** * Event for the end of a functional group. */ END_GROUP, /** * Event for the start of a transaction. */ START_TRANSACTION, /** * Event for the end of a transaction. */ END_TRANSACTION, /** * Event for the start of a data loop (logical grouping of segments). */ START_LOOP, /** * Event for the end of a data loop (logical grouping of segments). */ END_LOOP, /** * Event for an error relating to a segment */ SEGMENT_ERROR(true), /** * Event for an error relating to the data received in an element. */ ELEMENT_DATA_ERROR(true), /** * Event for an error relating to the an occurrence of an element. E.g. a * missing required element. */ ELEMENT_OCCURRENCE_ERROR(true); private final boolean error; private EDIStreamEvent(boolean error) { this.error = error; } private EDIStreamEvent() { this(false); } /** * Indicates whether a particular EDIStreamEvent represents a validation * error. * * @return true when the event represents a validation error, otherwise * false. */ public boolean isError() { return error; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamValidationError.java
src/main/java/io/xlate/edi/stream/EDIStreamValidationError.java
package io.xlate.edi.stream; /** * Enumeration of validation error types that may be encountered by the * EDIStreamReader or EDIStreamWriter. * * @see EDIStreamReader#getErrorType() * @see EDIInputErrorReporter#report(EDIStreamValidationError, EDIStreamReader) * @see EDIOutputErrorReporter#report(EDIStreamValidationError, EDIStreamWriter, * Location, CharSequence, io.xlate.edi.schema.EDIReference) */ public enum EDIStreamValidationError { /** * No error */ NONE(null), /** * An unrecognized (undefined) segment was encountered in the data stream. * * @deprecated Not used by StAEDI - reserved for future use. */ UNRECOGNIZED_SEGMENT_ID(EDIStreamEvent.SEGMENT_ERROR), /** * Segment was received in an unexpected position in the data stream. This * error may occur when a segment is encountered in a loop for which it is * not defined. */ UNEXPECTED_SEGMENT(EDIStreamEvent.SEGMENT_ERROR), /** * Segment was defined (via a schema) with a minimum number of occurrences, * but the number of occurrences encountered in the data stream does not * meet the requirement. */ MANDATORY_SEGMENT_MISSING(EDIStreamEvent.SEGMENT_ERROR), /** * Loop encountered in the data stream has more occurrences than allowed by * the configured schema. */ LOOP_OCCURS_OVER_MAXIMUM_TIMES(EDIStreamEvent.SEGMENT_ERROR), /** * Segment encountered in the data stream has more occurrences than allowed * by the configured schema. */ SEGMENT_EXCEEDS_MAXIMUM_USE(EDIStreamEvent.SEGMENT_ERROR), /** * An unrecognized (undefined) segment was encountered in the data stream. */ SEGMENT_NOT_IN_DEFINED_TRANSACTION_SET(EDIStreamEvent.SEGMENT_ERROR), /** * Segment was encountered out of order. This will occur if the segment is * valid within the current data loop, otherwise the error will be * {@link #UNEXPECTED_SEGMENT}. */ SEGMENT_NOT_IN_PROPER_SEQUENCE(EDIStreamEvent.SEGMENT_ERROR), /** * Segment contains data element errors. * * @deprecated Not used by StAEDI - reserved for future use. */ SEGMENT_HAS_DATA_ELEMENT_ERRORS(EDIStreamEvent.SEGMENT_ERROR), /** * Segment is defined as unused (maximum use is zero) in the schema but was * encountered in the data stream. */ IMPLEMENTATION_UNUSED_SEGMENT_PRESENT(EDIStreamEvent.SEGMENT_ERROR), /** * @deprecated Not used by StAEDI - reserved for future use. */ IMPLEMENTATION_DEPENDENT_SEGMENT_MISSING(EDIStreamEvent.SEGMENT_ERROR), /** * Loop is defined with a minimum number of occurrences in the * implementation schema but too few were encountered in the data stream. */ IMPLEMENTATION_LOOP_OCCURS_UNDER_MINIMUM_TIMES(EDIStreamEvent.SEGMENT_ERROR), /** * Segment is defined with a minimum number of occurrences in the * implementation schema but too few were encountered in the data stream. */ IMPLEMENTATION_SEGMENT_BELOW_MINIMUM_USE(EDIStreamEvent.SEGMENT_ERROR), /** * @deprecated Not used by StAEDI - reserved for future use. */ IMPLEMENTATION_DEPENDENT_UNUSED_SEGMENT_PRESENT(EDIStreamEvent.SEGMENT_ERROR), /** * Segment is configured as conditionally required (relative to other * segments in the loop) in the schema but was not present in the data * stream. */ CONDITIONAL_REQUIRED_SEGMENT_MISSING(EDIStreamEvent.SEGMENT_ERROR), /** * Segment is configured as conditionally excluded (relative to other * segments in the loop) in the schema but was present in the data stream. */ SEGMENT_EXCLUSION_CONDITION_VIOLATED(EDIStreamEvent.SEGMENT_ERROR), /** * Element was defined (via a schema) with a minimum number of occurrences * but the number of occurrences encountered in the data stream does not * meet the requirement. */ REQUIRED_DATA_ELEMENT_MISSING(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element is configured as conditionally required (relative to other * elements in the segment) in the schema but was not present in the data * stream. */ CONDITIONAL_REQUIRED_DATA_ELEMENT_MISSING(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element is configured as conditionally required (relative to other * elements in the segment) in the schema but was not present in the data * stream. */ TOO_MANY_DATA_ELEMENTS(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element is configured as conditionally excluded (relative to other * elements in the segment) in the schema but was present in the data * stream. */ EXCLUSION_CONDITION_VIOLATED(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element repeats more times than allowed by the configured schema. */ TOO_MANY_REPETITIONS(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element contains more components than defined by the configured schema. */ TOO_MANY_COMPONENTS(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * @deprecated Not used by StAEDI - reserved for future use. */ IMPLEMENTATION_DEPENDENT_DATA_ELEMENT_MISSING(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element is defined as unused (maximum use is zero) in the schema but was * encountered in the data stream. */ IMPLEMENTATION_UNUSED_DATA_ELEMENT_PRESENT(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element is defined with a minimum number of occurrences in the * implementation schema but too few were encountered in the data stream. */ IMPLEMENTATION_TOO_FEW_REPETITIONS(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * @deprecated Not used by StAEDI - reserved for future use. */ IMPLEMENTATION_DEPENDENT_UNUSED_DATA_ELEMENT_PRESENT(EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR), /** * Element length is less than the minimum length required by the configured * schema. */ DATA_ELEMENT_TOO_SHORT(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Element length is greater than the maximum length allowed by the * configured schema. */ DATA_ELEMENT_TOO_LONG(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Element contains invalid character data. */ INVALID_CHARACTER_DATA(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Element contains a value that is not present in the set of values * configured in the schema. */ INVALID_CODE_VALUE(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Element is defined with type * {@linkplain io.xlate.edi.schema.EDISimpleType.Base#DATE} but the data * encountered does not match formatted as a date. */ INVALID_DATE(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Element is defined with type * {@linkplain io.xlate.edi.schema.EDISimpleType.Base#TIME} but the data * encountered does not match formatted as a time. */ INVALID_TIME(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Element contains a value that is not present in the set of values * configured in the implementation schema. */ IMPLEMENTATION_INVALID_CODE_VALUE(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * @deprecated Not used by StAEDI - reserved for future use. */ IMPLEMENTATION_PATTERN_MATCH_FAILURE(EDIStreamEvent.ELEMENT_DATA_ERROR), // Control number and counter validation errors /** * Control number/reference in the trailer segment does not match the value * encountered in the header. */ CONTROL_REFERENCE_MISMATCH(EDIStreamEvent.ELEMENT_DATA_ERROR), /** * Control count (e.g. count of segments, transactions, or functional * groups) encountered in the trailer does not match the actual count in the * stream. */ CONTROL_COUNT_DOES_NOT_MATCH_ACTUAL_COUNT(EDIStreamEvent.ELEMENT_DATA_ERROR); private EDIStreamEvent category; private EDIStreamValidationError(EDIStreamEvent category) { this.category = category; } /** * Provides the category of the validation error. The category is one of the * EDIStreamEvents where {@linkplain EDIStreamEvent#isError()} is true. * * @return the EDIStreamEvent category of the validation error. */ public EDIStreamEvent getCategory() { return category; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamException.java
src/main/java/io/xlate/edi/stream/EDIStreamException.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; /** * Checked exception that may be thrown by EDIInputFactory, EDIStreamReader, * EDIOutputFactory, and EDIStreamWriter in the processing of EDI data. */ public class EDIStreamException extends Exception { private static final long serialVersionUID = -1232370584780899896L; /** * {@linkplain Location} of the exception */ protected final transient Location location; /** * Build a readable message that includes a detail message together with the * location of the exception * * @param message * detail message for the exception * @param location * location of the exception * @return concatenation of the detail message and location if the message * does not already contain the location */ protected static String buildMessage(String message, Location location) { String locationString = location.toString(); if (message.contains(locationString)) { return message; } return message + " " + locationString; } /** * Construct an exception with the associated message. * * @param message * the message to report */ public EDIStreamException(String message) { super(message); location = null; } /** * Construct an exception with the associated exception * * @param cause * a nested exception * @deprecated */ @SuppressWarnings({ "java:S1133" }) @Deprecated/*(forRemoval = true, since = "1.11")*/ public EDIStreamException(Throwable cause) { super(cause); location = null; } /** * Construct an exception with the associated message, exception and * location. * * @param message * the message to report * @param location * the location of the error * @param cause * a nested error / exception */ public EDIStreamException(String message, Location location, Throwable cause) { super(buildMessage(message, location), cause); this.location = location; } /** * Construct an exception with the associated message, exception and * location. * * @param message * the message to report * @param location * the location of the error */ public EDIStreamException(String message, Location location) { super(buildMessage(message, location)); this.location = location; } /** * Gets the location of the exception * * @return the location of the exception, may be null if none is available */ public Location getLocation() { return location; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIValidationException.java
src/main/java/io/xlate/edi/stream/EDIValidationException.java
package io.xlate.edi.stream; /** * Runtime exception that may occur when reading or writing EDI any the EDI * error event would not otherwise be handled by an application. For example, * when writing EDI and no {@linkplain EDIOutputErrorReporter} is in use. */ public class EDIValidationException extends RuntimeException { private static final long serialVersionUID = 5811097042070037687L; /** * The stream event associated with the error, one of the events for which * {@linkplain EDIStreamEvent#isError()} is true. */ protected final EDIStreamEvent event; /** * The actual {@linkplain EDIStreamValidationError error} of this exception. */ protected final EDIStreamValidationError error; /** * {@linkplain Location} of the exception */ protected final transient Location location; /** * The data from the data stream (input for a reader or output for a writer) * associated with the validation error. */ protected final transient CharSequence data; /** * The next exception when more than one validation error occurred in * processing the stream. */ @SuppressWarnings("java:S1165") // Intentionally allow field to be set after instantiation private EDIValidationException nextException; /** * Construct an EDIValidationException with the given data elements. * * @param event * stream event (required) * @param error * validation error (required) * @param location * location of the validation error * @param data * data associated with the validation error */ public EDIValidationException(EDIStreamEvent event, EDIStreamValidationError error, Location location, CharSequence data) { super("Encountered " + event + " [" + error + "]" + (location != null ? " " + location.toString() : "")); this.event = event; this.error = error; this.location = location != null ? location.copy() : null; this.data = data; } /** * Get the stream event associated with the error * * @return event associated with the error */ public EDIStreamEvent getEvent() { return event; } /** * Get the type of validation error * * @return type of validation error */ public EDIStreamValidationError getError() { return error; } /** * Get the location of the validation error * * @return location of the validation error */ public Location getLocation() { return location; } /** * Get the data associated with the validation error * * @return character data associated with the validation error */ public CharSequence getData() { return data; } /** * Retrieves the exception chained to this * <code>EDIValidationException</code> object by setNextException(EDIValidationException ex). * * @return the next <code>EDIValidationException</code> object in the chain; * <code>null</code> if there are none * @see #setNextException */ public EDIValidationException getNextException() { return nextException; } /** * Adds an <code>EDIValidationException</code> object to the end of the chain. * * @param ex the new exception that will be added to the end of * the <code>EDIValidationException</code> chain * @see #getNextException */ public void setNextException(EDIValidationException ex) { EDIValidationException current = this; while (current.nextException != null) { current = current.nextException; } current.nextException = ex; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamFilter.java
src/main/java/io/xlate/edi/stream/EDIStreamFilter.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; /** * This interface declares a simple filter interface that one can create to * filter EDIStreamReaders * * @version 1.0 */ public interface EDIStreamFilter { /** * Tests whether the current state is part of this stream. This method will * return true if this filter accepts this event and false otherwise. * * The method should not change the state of the reader when accepting a * state. * * @param reader * the event to test * @return true if this filter accepts this event, false otherwise */ boolean accept(EDIStreamReader reader); }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIOutputErrorReporter.java
src/main/java/io/xlate/edi/stream/EDIOutputErrorReporter.java
package io.xlate.edi.stream; import io.xlate.edi.schema.EDIReference; /** * This interface is used to report non-fatal errors detected in an EDI input. * * @since 1.9 */ public interface EDIOutputErrorReporter { /** * Report the desired message in an application specific format. Only * warnings and non-fatal errors should be reported through this interface. * * Fatal errors will be thrown as {@link EDIStreamException}s. * * @param errorType * the type of error detected * @param writer * the EDIStreamWriter that encountered the error * @param location * the location of the error, may be different than the location * returned by the writer (e.g. for derived element positions) * @param data * the invalid data, may be null (e.g. for missing required * element errors) * @param typeReference * the schema type reference for the invalid data, if available * from the current schema used for validation */ void report(EDIStreamValidationError errorType, EDIStreamWriter writer, Location location, CharSequence data, EDIReference typeReference); }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIOutputFactory.java
src/main/java/io/xlate/edi/stream/EDIOutputFactory.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; import java.io.OutputStream; import javax.xml.stream.XMLStreamWriter; /** * Defines an abstract implementation of a factory for getting EDIStreamWriters * and XMLStreamWriters (wrapping an existing EDIStreamWriter). An EDIOutputErrorReporter * may also be configured via the factory for use with each new EDIStreamWriter * created. */ public abstract class EDIOutputFactory extends PropertySupport { /** * <p> * When set to true, the EDI output will have a platform specific line * separator written after each segment terminator. * * <p> * Default value is false. */ public static final String PRETTY_PRINT = "io.xlate.edi.stream.PRETTY_PRINT"; /** * <p> * When set to true, empty trailing elements in a segment and empty trailing * components in a composite element will be truncated. I.e, they will not * be written to the output. * * <p> * Default value is false. */ public static final String TRUNCATE_EMPTY_ELEMENTS = "io.xlate.edi.stream.TRUNCATE_EMPTY_ELEMENTS"; /** * <p> * When set to true and a schema has been provided, elements written to the output will * be padded to the minimum length required by the schema. * * <p> * Default value is false. * * @since 1.11 */ public static final String FORMAT_ELEMENTS = "io.xlate.edi.stream.FORMAT_ELEMENTS"; /** * Create a new instance of the factory. This static method creates a new * factory instance. * * Once an application has obtained a reference to an EDIOutputFactory it * can use the factory to configure and obtain stream instances. * * @return the factory implementation */ public static EDIOutputFactory newFactory() { return new io.xlate.edi.internal.stream.StaEDIOutputFactory(); } /** * Default constructor */ protected EDIOutputFactory() { } /** * Create a new EDIStreamWriter that writes to a stream * * @param stream * {@link OutputStream} to which the EDI data will be written * @return the writer instance */ public abstract EDIStreamWriter createEDIStreamWriter(OutputStream stream); /** * Create a new EDIStreamWriter that writes to a stream * * @param stream * {@link OutputStream} to which the EDI data will be written * @param encoding * character encoding of the stream, must be a valid * {@link java.nio.charset.Charset Charset}. * @return the writer instance * @throws EDIStreamException * when encoding is not supported */ public abstract EDIStreamWriter createEDIStreamWriter(OutputStream stream, String encoding) throws EDIStreamException; /** * Creates a new {@link XMLStreamWriter} that uses the given writer as its * output. * * XML Elements written to the writer must use the namespaces declared by * the constants in {@link EDINamespaces}. The sequence of elements is * critical and must align with the structure of the intended EDI output to * be written via the given EDI writer. * * @param writer * the writer used to generate EDI output using the XML writer * @return a new {@link XMLStreamWriter} */ public abstract XMLStreamWriter createXMLStreamWriter(EDIStreamWriter writer); /** * Retrieves the reporter that will be set on any EDIStreamWriter created by * this factory instance. * * @return the reporter that will be set on any EDIStreamWriter created by * this factory instance * * @since 1.9 */ public abstract EDIOutputErrorReporter getErrorReporter(); /** * The reporter that will be set on any EDIStreamWriter created by this * factory instance. * * NOTE: When using an EDIOutputErrorReporter, errors found in the data * stream that are reported to the reporter will not be throw as instances * of {@link EDIValidationException}. * * @param reporter * the resolver to use to report non fatal errors * * @since 1.9 */ public abstract void setErrorReporter(EDIOutputErrorReporter reporter); }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamConstants.java
src/main/java/io/xlate/edi/stream/EDIStreamConstants.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; /** * Collection of constant values identifying the several EDI standards and the * delimiters used in processing EDI data streams. */ public interface EDIStreamConstants { /** * Defines the constant values possibly returned by * {@link EDIStreamReader#getStandard()} and * {@link EDIStreamWriter#getStandard()}. */ public static class Standards { private Standards() { } /** * Constant name for the EDIFACT EDI Dialect */ public static final String EDIFACT = "EDIFACT"; /** * Constant name for the TRADACOMS EDI Dialect * @since 1.15 */ public static final String TRADACOMS = "TRADACOMS"; /** * Constant name for the X12 EDI Dialect */ public static final String X12 = "X12"; } /** * Defines the constant values of EDI delimiters present in the maps * returned by * {@link EDIStreamReader#getDelimiters()}/{@link EDIStreamWriter#getDelimiters()} * and accepted as properties for output via * {@link EDIOutputFactory#setProperty(String, Object)}. */ public static class Delimiters { private Delimiters() { } /** * Key for the delimiter used to terminate/end a segment. */ public static final String SEGMENT = "io.xlate.edi.stream.delim.segment"; /** * Key for the delimiter used to terminate/end a simple or composite * data element. */ public static final String DATA_ELEMENT = "io.xlate.edi.stream.delim.dataElement"; /** * Key for the delimiter used to terminate/end a component of a * composite element. */ public static final String COMPONENT_ELEMENT = "io.xlate.edi.stream.delim.componentElement"; /** * Key for the delimiter used to terminate/end a repeating data element. */ public static final String REPETITION = "io.xlate.edi.stream.delim.repetition"; /** * Key for the character used as the decimal point for non-integer * numeric element types. */ public static final String DECIMAL = "io.xlate.edi.stream.delim.decimal"; /** * Key for the character used as a release character, allowing the next * character in the EDI stream to be treated as data element text rather * than a delimiter. */ public static final String RELEASE = "io.xlate.edi.stream.delim.release"; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/stream/EDIStreamWriter.java
src/main/java/io/xlate/edi/stream/EDIStreamWriter.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.stream; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Map; import io.xlate.edi.schema.Schema; /** * The EDIStreamWriter interface specifies how to write EDI. Each method depends * on the internal state of the writer and a client application must ensure that * the methods are called in the proper sequence. For example, element data may * not be written prior to starting an interchange and a segment. */ public interface EDIStreamWriter extends AutoCloseable { /** * Get the value of a feature/property from the underlying implementation * * @param name * - The name of the property, may not be null * @return The value of the property * @throws IllegalArgumentException * if name is null */ Object getProperty(String name); /** * Close this writer and free any resources associated with the writer. This * must not close the underlying output stream. * * @throws EDIStreamException * if there are errors freeing associated resources */ @Override void close() throws EDIStreamException; /** * Write any cached data to the underlying output mechanism. * * @throws EDIStreamException * if there are errors flushing the cache */ void flush() throws EDIStreamException; /** * Returns the control schema currently set on the reader. If none has been * set, then null will be returned. * * @return the control schema current set on this reader, may be null * * @since 1.8 */ Schema getControlSchema(); /** * <p> * Sets the schema to be used for validation of the control structure for * this stream writer. This schema will be used to validate interchange, * group, and transaction/message envelopes. * <p> * Calls to this method are only valid before the interchange is started. * <p> * A built-in control schema may be obtained from * {@link io.xlate.edi.schema.SchemaFactory#getControlSchema(String, String[]) * SchemaFactory#getControlSchema} to pass to this method. * * @param controlSchema * the schema instance to use for validation of control * structures * @throws IllegalStateException * when the writer is not in its initial state * @see io.xlate.edi.schema.SchemaFactory#getControlSchema(String, String[]) * SchemaFactory#getControlSchema * @since 1.1 */ void setControlSchema(Schema controlSchema); /** * <p> * Sets the schema to be used for validation of the business transaction for * this stream writer. This schema will be used to validate only the * contents of a transaction/message, <em>not including</em> the begin/end * control structures. * <p> * This method may be called at any time. However, when non-null, the writer * will make use of the transaction schema for output validation. It is the * responsibility of the caller to set the transaction schema to null at the * end of the business transaction. * * @param transactionSchema * the schema instance to use for validation of business * transaction structures * * @since 1.1 */ void setTransactionSchema(Schema transactionSchema); /** * Return the current location of the writer. If the Location is unknown the * processor should return an implementation of Location that returns -1 for * the location values. The location information is only valid until the * next item is written to the output. * * @return current location of the writer * * @since 1.1 */ Location getLocation(); /** * Get the EDI standard name. Calls to this method are only valid when the * interchange type has been determined, after the full interchange header * segment has been written. * * @return the name of the EDI standard * @throws IllegalStateException * when the standard has not yet been determined, prior to the * start of an interchange header segment being fully written * * @since 1.7 */ String getStandard(); /** * Retrieve a read-only map of delimiters in use for the stream being * written. * * @return The value of the property * @throws IllegalStateException * when the standard has not yet been determined, prior to the * start of an interchange header segment being fully written * * @since 1.8 */ Map<String, Character> getDelimiters(); /** * Initialize this writer to begin writing an interchange. * * This method does not write any output to the underlying stream. * * @return this EDI stream writer * @throws EDIStreamException * is not thrown and will be removed in the next major version * of StAEDI. * @throws IllegalStateException * when the writer is in any state other than the initial state */ EDIStreamWriter startInterchange() throws EDIStreamException; /** * Completes an interchange and returns the writer to its initial state. Any * data pending output will be {@linkplain #flush() flushed}. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is in a state writing a segment, element, * composite */ EDIStreamWriter endInterchange() throws EDIStreamException; /** * Begin a new segment with the given name and write the tag to the * underlying output. * * @param name * name of the segment (i.e. the segment tag) * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state to begin a segment */ EDIStreamWriter writeStartSegment(String name) throws EDIStreamException; /** * Complete a segment by writing the segment terminator to the underlying * output. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state to end a segment */ EDIStreamWriter writeEndSegment() throws EDIStreamException; /** * Start a new element, composite or simple. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when a segment has not been started with * {@link #writeStartSegment(String)} */ EDIStreamWriter writeStartElement() throws EDIStreamException; /** * Start a new element for binary data. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the a segment has not been started with * {@link #writeStartSegment(String)} */ EDIStreamWriter writeStartElementBinary() throws EDIStreamException; /** * Complete an element. A delimiter will not be written immediately. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in the state of writing an element */ EDIStreamWriter endElement() throws EDIStreamException; /** * Write an element repeat delimiter/separator to the output stream. * Following this method being called, the writer will be in a state to * accept element data using {@link #writeElementData(CharSequence)} or * {@link #writeElementData(char[], int, int)}. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing element data. A * segment must have already been started. */ EDIStreamWriter writeRepeatElement() throws EDIStreamException; /** * Start a component of a composite element. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when an element has not been started with * {@link #writeStartElement()} */ EDIStreamWriter startComponent() throws EDIStreamException; /** * Complete a component of a composite element. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in the state of writing an component * element */ EDIStreamWriter endComponent() throws EDIStreamException; /** * Write an empty simple element. * <p> * Shorthand for calling {@link #writeStartElement()} immediately followed * by {@link #endElement()}. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing simple element * data */ EDIStreamWriter writeEmptyElement() throws EDIStreamException; /** * Begin an element, write text data from the given CharSequence to the * output, and end the element. * <p> * Shorthand for calling {@link #writeStartElement()}, * {@link #writeElementData(CharSequence)}, and {@link #endElement()}, in * that order. * * @param text * CharSequence containing element's full text data * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing simple element * data */ EDIStreamWriter writeElement(CharSequence text) throws EDIStreamException; /** * Begin an element, write text data from the given char array to the * output, and end the element. Data will be read from the offset given by * start (inclusive) to the offset given by end (exclusive). * <p> * Shorthand for calling {@link #writeStartElement()}, * {@link #writeElementData(char[], int, int)}, and {@link #endElement()}, * in that order. * * @param text * char array containing element's full text data * @param start * the start index, inclusive * @param end * the end index, exclusive * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing simple element * data */ EDIStreamWriter writeElement(char[] text, int start, int end) throws EDIStreamException; /** * Write an empty component * <p> * Shorthand for calling {@link #startComponent()} immediately followed by * {@link #endComponent()}. * * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing component * element data */ EDIStreamWriter writeEmptyComponent() throws EDIStreamException; /** * Begin a component element, write text data from the given CharSequence to * the output, and end the element. * <p> * Shorthand for calling {@link #startComponent()}, * {@link #writeElementData(CharSequence)}, and {@link #endComponent()}, in * that order. * * @param text * CharSequence containing component's full text data * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing component * element data */ EDIStreamWriter writeComponent(CharSequence text) throws EDIStreamException; /** * Begin a component element, write text data from the given char array to * the output, and end the element. Data will be read from the offset given * by start (inclusive) to the offset given by end (exclusive). * <p> * Shorthand for calling {@link #startComponent()}, * {@link #writeElementData(char[], int, int)}, and {@link #endComponent()}, * in that order. * * @param text * char array containing component's full text data * @param start * the start index, inclusive * @param end * the end index, exclusive * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing component * element data */ EDIStreamWriter writeComponent(char[] text, int start, int end) throws EDIStreamException; /** * Write text data from the given CharSequence to the output. * * @param text * CharSequence containing element text data * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing element data. * See {@linkplain #writeStartElement()} */ EDIStreamWriter writeElementData(CharSequence text) throws EDIStreamException; /** * Write text data from the given char array to the output. Data will be * read from the offset given by start (inclusive) to the offset given by * end (exclusive). * * @param text * char array containing element text data * @param start * the start index, inclusive * @param end * the end index, exclusive * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing element data. * See {@linkplain #writeStartElement()} */ EDIStreamWriter writeElementData(char[] text, int start, int end) throws EDIStreamException; /** * Write binary data from the given InputStream to the output. The stream * will be read fully, until the byte returned by * {@linkplain InputStream#read()} is {@code -1}. Any data pending output * will first be {@linkplain #flush() flushed}. * * @param stream * InputStream containing binary data to be consumed by the * reader and written to the underlying output * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing binary element * data. See {@linkplain #writeStartElementBinary()} */ EDIStreamWriter writeBinaryData(InputStream stream) throws EDIStreamException; /** * Write binary data from the given byte array to the output. Data will be * read from the offset given by start (inclusive) to the offset given by * end (exclusive). Any data pending output will first be * {@linkplain #flush() flushed}. * * @param binary * byte array containing binary data * @param start * the start index, inclusive * @param end * the end index, exclusive * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing binary element * data. See {@linkplain #writeStartElementBinary()} */ EDIStreamWriter writeBinaryData(byte[] binary, int start, int end) throws EDIStreamException; /** * Write binary data from the given buffer to the output. Any data pending * output will first be {@linkplain #flush() flushed}. * * @param buffer * data buffer containing binary data * @return this EDI stream writer * @throws EDIStreamException * if an error occurs * @throws IllegalStateException * when the writer is not in a state for writing binary element * data. See {@linkplain #writeStartElementBinary()} */ EDIStreamWriter writeBinaryData(ByteBuffer buffer) throws EDIStreamException; }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/ThrowingRunnable.java
src/main/java/io/xlate/edi/internal/ThrowingRunnable.java
package io.xlate.edi.internal; import java.util.function.Function; /** * A {@link Runnable} that can throw exceptions/errors. Internal use only. * * @param <T> * the type of exception that may be thrown * * @since 1.24 */ public interface ThrowingRunnable<T extends Exception> { /** * Run any code provided by an implementation, including code that may throw * an exception. * * @throws T * any exception thrown by the implementation of this method */ void run() throws T; /** * Execute the provided task and apply the given exceptionWrapper function * on any exception thrown by it. * * @param <T> * the type of exception that may be thrown * @param <E> * the type of exception that this method may throw, wrapping any * thrown by task * @param task * runnable to execute that may thrown an exception T * @param exceptionWrapper * wrapper function to wrap/convert an exception T to an * exception E * @throws E * exception thrown when task throws an exception T */ static <T extends Exception, E extends Exception> void run(ThrowingRunnable<T> task, Function<T, E> exceptionWrapper) throws E { try { task.run(); } catch (Exception e) { @SuppressWarnings("unchecked") T thrown = (T) e; throw exceptionWrapper.apply(thrown); } } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIStreamReader.java
src/main/java/io/xlate/edi/internal/stream/StaEDIStreamReader.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import java.io.IOException; import java.io.InputStream; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import io.xlate.edi.internal.ThrowingRunnable; import io.xlate.edi.internal.schema.SchemaUtils; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.Lexer; import io.xlate.edi.internal.stream.tokenization.ProxyEventHandler; import io.xlate.edi.internal.stream.validation.ValidatorConfig; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDISchemaException; import io.xlate.edi.schema.Schema; import io.xlate.edi.stream.EDIInputErrorReporter; import io.xlate.edi.stream.EDIInputFactory; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamReader; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.Location; public class StaEDIStreamReader implements EDIStreamReader, Configurable, ValidatorConfig { private static final Logger LOGGER = Logger.getLogger(StaEDIStreamReader.class.getName()); private static final CharBuffer GROUP_TEXT = CharBuffer.wrap(ProxyEventHandler.LOOP_CODE_GROUP); private static final CharBuffer TRANSACTION_TEXT = CharBuffer.wrap(ProxyEventHandler.LOOP_CODE_TRANSACTION); private Schema controlSchema; private final Map<String, Object> properties; private final EDIInputErrorReporter reporter; private final StaEDIStreamLocation location = new StaEDIStreamLocation(); private final ProxyEventHandler proxy; private final Lexer lexer; private boolean complete = false; private boolean closed = false; private boolean deprecationLogged = false; public StaEDIStreamReader( InputStream stream, Charset charset, Schema schema, Map<String, Object> properties, EDIInputErrorReporter reporter) { this.controlSchema = schema; this.properties = new HashMap<>(properties); this.reporter = reporter; this.proxy = new ProxyEventHandler(location, controlSchema, nestHierarchicalLoops(), this); this.lexer = new Lexer(stream, charset, proxy, location, ignoreExtraneousCharacters()); } private void ensureOpen() { if (closed) { throw new IllegalStateException("Reader is closed"); } } private void ensureIncomplete() { if (complete) { throw new NoSuchElementException("Reader is complete"); } } void ensureValueAvailable(Function<Dialect, Object> valueSupplier, String valueType) { if (lexer.getDialect() == null || valueSupplier.apply(lexer.getDialect()) == null) { throw new IllegalStateException(valueType + " not accessible"); } } void requireEvent(String message, EDIStreamEvent... events) { EDIStreamEvent current = proxy.getEvent(); for (EDIStreamEvent e : events) { if (current == e) { return; } } throw new IllegalStateException(message); } private void logDeprecation(EDIStreamEvent event) { if (!deprecationLogged) { deprecationLogged = true; LOGGER.warning(() -> "DEPRECATION - Retrieving text for event " + event + " will not be supported in a future release. " + "Use `getReferenceCode` or `getSchemaTypeReference` to retrieve additional information for non-textual event types."); } } private CharBuffer getBuffer() { checkTextState(); EDIStreamEvent event = getEventType(); switch (event) { case START_GROUP: case END_GROUP: logDeprecation(event); return GROUP_TEXT; case START_TRANSACTION: case END_TRANSACTION: logDeprecation(event); return TRANSACTION_TEXT; case START_LOOP: case END_LOOP: logDeprecation(event); return CharBuffer.wrap(proxy.getSchemaTypeReference().getReferencedType().getCode()); default: return proxy.getCharacters(); } } @Override public Object getProperty(String name) { if (name == null) { throw new IllegalArgumentException("Name must not be null"); } return properties.get(name); } @Override public Map<String, Character> getDelimiters() { Dialect dialect = lexer.getDialect(); if (dialect == null) { throw new IllegalStateException("getDelimiters must be called " + "within an interchange"); } Map<String, Character> delimiters = new HashMap<>(5); delimiters.put(Delimiters.SEGMENT, dialect.getSegmentTerminator()); delimiters.put(Delimiters.DATA_ELEMENT, dialect.getDataElementSeparator()); delimiters.put(Delimiters.COMPONENT_ELEMENT, dialect.getComponentElementSeparator()); if (dialect.getDecimalMark() != '\0') { delimiters.put(Delimiters.DECIMAL, dialect.getDecimalMark()); } if (dialect.getRepetitionSeparator() != '\0') { delimiters.put(Delimiters.REPETITION, dialect.getRepetitionSeparator()); } if (dialect.getReleaseIndicator() != '\0') { delimiters.put(Delimiters.RELEASE, dialect.getReleaseIndicator()); } return Collections.unmodifiableMap(delimiters); } void executeTask(ThrowingRunnable<Exception> task, String errorMessage) throws EDIStreamException { ThrowingRunnable.run(task, e -> { if (e instanceof EDIStreamException) { return (EDIStreamException) e; } Location where = getLocation(); return new EDIStreamException(errorMessage, where, e); }); } private EDIStreamEvent nextEvent() throws EDIStreamException { ensureOpen(); ensureIncomplete(); if (EDIStreamEvent.START_INTERCHANGE == proxy.getEvent() && useInternalControlSchema()) { try { LOGGER.finer(() -> "Setting control schema: " + getStandard() + ", " + getVersion()); setControlSchema(SchemaUtils.getControlSchema(getStandard(), getVersion())); LOGGER.finer(() -> "Done setting control schema: " + getStandard() + ", " + getVersion()); } catch (EDISchemaException e) { LOGGER.log(Level.WARNING, String.format("Exception loading controlSchema for standard %s, version %s: %s", getStandard(), Arrays.stream(getVersion()).map(Object::toString) .collect(Collectors.joining(", ")), e.getMessage()), e); } } if (!proxy.nextEvent()) { proxy.resetEvents(); do { executeTask(lexer::parse, "Error parsing input"); } while (proxy.additionalEventsRequired()); } final EDIStreamEvent event = proxy.getEvent(); LOGGER.finer(() -> "EDI event: " + event + (event.isError() ? "; error type: " + proxy.getErrorType(): "")); if (event == EDIStreamEvent.END_INTERCHANGE) { executeTask(() -> complete = !proxy.hasNext() && !lexer.hasRemaining(), "Error reading input"); } if (event == EDIStreamEvent.ELEMENT_DATA && proxy.isBinaryElementLength()) { try { this.setBinaryDataLength(Long.parseLong(getText())); } catch (NumberFormatException e) { lexer.invalidate(); throw new EDIStreamException("Failed to parse binary element length", location, e); } } return event; } @Override public EDIStreamEvent next() throws EDIStreamException { EDIStreamEvent event = null; boolean eventFound = false; do { event = nextEvent(); if (this.reporter != null && event.isError()) { reporter.report(getErrorType(), this); } else { eventFound = true; } } while (!complete && !eventFound); return event; } @Override public EDIStreamEvent nextTag() throws EDIStreamException { EDIStreamEvent event = null; boolean tagFound = false; do { event = next(); switch (event) { case START_GROUP: case START_TRANSACTION: case START_LOOP: case START_SEGMENT: tagFound = true; break; default: break; } } while (!complete && !tagFound); if (!tagFound) { throw new NoSuchElementException("No additional tags in stream"); } return event; } @Override public boolean hasNext() throws EDIStreamException { ensureOpen(); return !complete; } @Override public void close() throws IOException { this.closed = true; // Do not close the stream } @Override public EDIStreamEvent getEventType() { ensureOpen(); return proxy.getEvent(); } @Override public String getStandard() { if (lexer.getDialect() == null) { throw new IllegalStateException("standard not accessible"); } return lexer.getDialect().getStandard(); } @Override public String[] getVersion() { ensureValueAvailable(Dialect::getVersion, "version"); String[] version = lexer.getDialect().getVersion(); return Arrays.copyOf(version, version.length); } @Override public String[] getTransactionVersion() { ensureValueAvailable(Dialect::getTransactionVersion, "transaction version"); String[] version = lexer.getDialect().getTransactionVersion(); return Arrays.copyOf(version, version.length); } @Override public String getTransactionVersionString() { ensureValueAvailable(Dialect::getTransactionVersion, "transaction version"); return lexer.getDialect().getTransactionVersionString(); } @Override public String getTransactionType() { ensureValueAvailable(Dialect::getTransactionType, "transaction type"); return lexer.getDialect().getTransactionType(); } @Override public Schema getControlSchema() { return this.controlSchema; } @Override public void setControlSchema(Schema schema) { if (getEventType() != EDIStreamEvent.START_INTERCHANGE) { throw new IllegalStateException("control schema set after interchange start"); } if (this.controlSchema != null) { throw new IllegalStateException("control schema already set"); } this.controlSchema = schema; proxy.setControlSchema(schema); } @Override public Schema getTransactionSchema() { return proxy.getTransactionSchema(); } @Override public void setTransactionSchema(Schema schema) { if (proxy.isTransactionSchemaAllowed()) { proxy.setTransactionSchema(schema); } else { throw new IllegalStateException("Transaction schema can only be set during transaction start"); } } @Override public String getReferenceCode() { return proxy.getReferenceCode(); } @Override public EDIStreamValidationError getErrorType() { requireEvent("not a valid error state", EDIStreamEvent.ELEMENT_DATA_ERROR, EDIStreamEvent.ELEMENT_OCCURRENCE_ERROR, EDIStreamEvent.SEGMENT_ERROR); return proxy.getErrorType(); } private void checkTextState() { if (!hasText()) { throw new IllegalStateException("not a valid text state [" + getEventType() + ']'); } } @Override public boolean hasText() { EDIStreamEvent event = getEventType(); if (event == null) { return false; } switch (event) { case START_SEGMENT: case END_SEGMENT: case ELEMENT_DATA: case ELEMENT_DATA_ERROR: case ELEMENT_OCCURRENCE_ERROR: case SEGMENT_ERROR: return true; case START_GROUP: case START_TRANSACTION: case START_LOOP: case END_GROUP: case END_TRANSACTION: case END_LOOP: return enableLoopText(); default: return false; } } @Override public String getText() { final CharBuffer buffer = getBuffer(); return buffer.toString(); } @Override public char[] getTextCharacters() { final CharBuffer buffer = getBuffer(); return Arrays.copyOf(buffer.array(), buffer.length()); } @Override public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length) { if (target == null) { throw new NullPointerException("Null target array"); } if (targetStart < 0) { throw new IndexOutOfBoundsException("targetStart < 0"); } if (targetStart > target.length) { throw new IndexOutOfBoundsException("targetStart > target.length"); } if (length < 0) { throw new IndexOutOfBoundsException("length < 0"); } if (length > target.length) { throw new IndexOutOfBoundsException("length (" + length + ") > target.length (" + target.length + ")"); } final CharBuffer buffer = getBuffer(); final char[] contents = buffer.array(); final int count = buffer.remaining(); if (sourceStart < 0) { throw new IndexOutOfBoundsException("sourceStart < 0"); } if (sourceStart > count) { throw new IndexOutOfBoundsException("sourceStart > source length"); } int toCopy = Math.min(count - sourceStart, length); System.arraycopy(contents, sourceStart, target, targetStart, toCopy); return toCopy; } @Override public int getTextStart() { final CharBuffer buffer = getBuffer(); return buffer.position(); } @Override public int getTextLength() { final CharBuffer buffer = getBuffer(); return buffer.limit(); } @Override public Location getLocation() { ensureOpen(); return proxy.getLocation(); } @Override public void setBinaryDataLength(long length) throws EDIStreamException { ensureOpen(); requireEvent("invalid state for setting binary length", EDIStreamEvent.START_SEGMENT, EDIStreamEvent.ELEMENT_DATA, EDIStreamEvent.END_COMPOSITE); lexer.setBinaryLength(length); } @Override public InputStream getBinaryData() { ensureOpen(); requireEvent("not binary data element", EDIStreamEvent.ELEMENT_DATA_BINARY); return proxy.getBinary(); } @Override public EDIReference getSchemaTypeReference() { return proxy.getSchemaTypeReference(); } /**************************************************************************/ @Override public boolean validateControlCodeValues() { return getProperty(EDIInputFactory.EDI_VALIDATE_CONTROL_CODE_VALUES, Boolean::parseBoolean, true); } boolean useInternalControlSchema() { if (this.controlSchema != null) { return false; } return getProperty(EDIInputFactory.EDI_VALIDATE_CONTROL_STRUCTURE, Boolean::parseBoolean, true); } boolean ignoreExtraneousCharacters() { return getProperty(EDIInputFactory.EDI_IGNORE_EXTRANEOUS_CHARACTERS, Boolean::parseBoolean, false); } boolean nestHierarchicalLoops() { return getProperty(EDIInputFactory.EDI_NEST_HIERARCHICAL_LOOPS, Boolean::parseBoolean, true); } @SuppressWarnings("deprecation") boolean enableLoopText() { return getProperty(EDIInputFactory.EDI_ENABLE_LOOP_TEXT, Boolean::parseBoolean, true); } @Override public boolean trimDiscriminatorValues() { return getProperty(EDIInputFactory.EDI_TRIM_DISCRIMINATOR_VALUES, Boolean::parseBoolean, false); } @Override public boolean formatElements() { return false; } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/DocumentNamespaceContext.java
src/main/java/io/xlate/edi/internal/stream/DocumentNamespaceContext.java
package io.xlate.edi.internal.stream; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.namespace.NamespaceContext; import io.xlate.edi.stream.EDINamespaces; class DocumentNamespaceContext implements NamespaceContext { private final Map<String, String> namespaces; DocumentNamespaceContext() { List<String> names = EDINamespaces.all(); namespaces = new HashMap<>(names.size()); for (String namespace : names) { String prefix = StaEDIXMLStreamReader.prefixOf(namespace); namespaces.put(namespace, prefix); } } @Override public String getNamespaceURI(String prefix) { return namespaces.entrySet() .stream() .filter(e -> e.getValue().equals(prefix)) .map(Map.Entry::getKey) .findFirst() .orElse(null); } @Override public String getPrefix(String namespaceURI) { return namespaces.get(namespaceURI); } @Override public Iterator<String> getPrefixes(String namespaceURI) { return Collections.singletonList(namespaces.get(namespaceURI)).iterator(); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
false
xlate/staedi
https://github.com/xlate/staedi/blob/c23c1fd73e63f17e9b124a3e0c50959d5be83e46/src/main/java/io/xlate/edi/internal/stream/StaEDIStreamWriter.java
src/main/java/io/xlate/edi/internal/stream/StaEDIStreamWriter.java
/******************************************************************************* * Copyright 2017 xlate.io LLC, http://www.xlate.io * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package io.xlate.edi.internal.stream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Logger; import io.xlate.edi.internal.stream.tokenization.CharacterClass; import io.xlate.edi.internal.stream.tokenization.CharacterSet; import io.xlate.edi.internal.stream.tokenization.Dialect; import io.xlate.edi.internal.stream.tokenization.DialectFactory; import io.xlate.edi.internal.stream.tokenization.EDIException; import io.xlate.edi.internal.stream.tokenization.EDIFACTDialect; import io.xlate.edi.internal.stream.tokenization.ElementDataHandler; import io.xlate.edi.internal.stream.tokenization.State; import io.xlate.edi.internal.stream.tokenization.StreamEvent; import io.xlate.edi.internal.stream.tokenization.ValidationEventHandler; import io.xlate.edi.internal.stream.tokenization.X12Dialect; import io.xlate.edi.internal.stream.validation.UsageError; import io.xlate.edi.internal.stream.validation.Validator; import io.xlate.edi.internal.stream.validation.ValidatorConfig; import io.xlate.edi.schema.EDIReference; import io.xlate.edi.schema.EDIType; import io.xlate.edi.schema.Schema; import io.xlate.edi.stream.EDIOutputErrorReporter; import io.xlate.edi.stream.EDIOutputFactory; import io.xlate.edi.stream.EDIStreamConstants.Delimiters; import io.xlate.edi.stream.EDIStreamEvent; import io.xlate.edi.stream.EDIStreamException; import io.xlate.edi.stream.EDIStreamValidationError; import io.xlate.edi.stream.EDIStreamWriter; import io.xlate.edi.stream.EDIValidationException; import io.xlate.edi.stream.Location; public class StaEDIStreamWriter implements EDIStreamWriter, ElementDataHandler, ValidationEventHandler, ValidatorConfig { static final Logger LOGGER = Logger.getLogger(StaEDIStreamWriter.class.getName()); private static final int LEVEL_INITIAL = 0; private static final int LEVEL_INTERCHANGE = 1; private static final int LEVEL_SEGMENT = 2; private static final int LEVEL_ELEMENT = 3; private static final int LEVEL_COMPOSITE = 4; private static final int LEVEL_COMPONENT = 5; private int level; private State state = State.INITIAL; private CharacterSet characters = new CharacterSet(); private final OutputStream stream; private final OutputStreamWriter writer; private final Map<String, Object> properties; private final EDIOutputErrorReporter reporter; private Dialect dialect; CharBuffer unconfirmedBuffer = CharBuffer.allocate(500); private final StaEDIStreamLocation location; private Schema controlSchema; private Validator controlValidator; private boolean transactionSchemaAllowed = false; private boolean transaction = false; private Schema transactionSchema; private Validator transactionValidator; private CharArraySequence dataHolder = new CharArraySequence(); private boolean atomicElementWrite = false; private CharBuffer elementBuffer = CharBuffer.allocate(500); private final StringBuilder formattedElement = new StringBuilder(); private List<EDIValidationException> errors = new ArrayList<>(); private CharArraySequence elementHolder = new CharArraySequence(); private final StreamEvent currentEvent = new StreamEvent(); private final Deque<StreamEvent> currentEventQueue = new LinkedList<>(Arrays.asList(currentEvent)); private char segmentTerminator; private char segmentTagTerminator; private char dataElementSeparator; private char componentElementSeparator; private char repetitionSeparator; private char decimalMark; private char releaseIndicator; final boolean emptyElementTruncation; final boolean formatElements; private final boolean prettyPrint; private String prettyPrintString; private long elementLength = 0; private int emptyElements = 0; private boolean unterminatedElement = false; private int emptyComponents = 0; private boolean unterminatedComponent = false; public StaEDIStreamWriter(OutputStream stream, Charset charset, Map<String, Object> properties, EDIOutputErrorReporter reporter) { this.stream = stream; this.writer = new OutputStreamWriter(stream, charset); this.properties = new HashMap<>(properties); this.reporter = reporter; this.emptyElementTruncation = booleanValue(properties.get(EDIOutputFactory.TRUNCATE_EMPTY_ELEMENTS)); this.prettyPrint = booleanValue(properties.get(EDIOutputFactory.PRETTY_PRINT)); this.formatElements = booleanValue(properties.get(EDIOutputFactory.FORMAT_ELEMENTS)); this.location = new StaEDIStreamLocation(); } @Override public boolean formatElements() { return formatElements; } @Override public boolean trimDiscriminatorValues() { return false; } @Override public boolean validateControlCodeValues() { return true; } boolean booleanValue(Object value) { if (value instanceof Boolean) { return (Boolean) value; } if (value instanceof String) { return Boolean.valueOf(value.toString()); } if (value == null) { return false; } LOGGER.warning(() -> "Value [" + value + "] could not be converted to boolean"); return false; } private void setupDelimiters() { segmentTerminator = getDelimiter(properties, Delimiters.SEGMENT, dialect::getSegmentTerminator); segmentTagTerminator = dialect.getSegmentTagTerminator(); // Not configurable - TRADACOMS dataElementSeparator = getDelimiter(properties, Delimiters.DATA_ELEMENT, dialect::getDataElementSeparator); componentElementSeparator = getDelimiter(properties, Delimiters.COMPONENT_ELEMENT, dialect::getComponentElementSeparator); decimalMark = getDelimiter(properties, Delimiters.DECIMAL, dialect::getDecimalMark); releaseIndicator = getDelimiter(properties, Delimiters.RELEASE, dialect::getReleaseIndicator); repetitionSeparator = getDelimiter(properties, Delimiters.REPETITION, dialect::getRepetitionSeparator); String lineSeparator = System.getProperty("line.separator"); if (prettyPrint && lineSeparator.indexOf(segmentTerminator) < 0) { // Do not add the line separator after the segment terminator if they conflict. I.e., the separator contains the terminator prettyPrintString = lineSeparator; } else { prettyPrintString = ""; } } private boolean areDelimitersSpecified() { return Arrays.asList(Delimiters.SEGMENT, Delimiters.DATA_ELEMENT, Delimiters.COMPONENT_ELEMENT, Delimiters.REPETITION, Delimiters.DECIMAL, Delimiters.RELEASE) .stream() .anyMatch(properties::containsKey); } char getDelimiter(Map<String, Object> properties, String key, Supplier<Character> dialectSupplier) { if (properties.containsKey(key) && !dialect.isConfirmed()) { return (char) properties.get(key); } return dialectSupplier.get(); } static void putDelimiter(String key, char value, Map<String, Character> delimiters) { if (value != '\0') { delimiters.put(key, value); } } private static void ensureArgs(int arrayLength, int start, int end) { if (start < 0 || (start > 0 && start >= arrayLength) || end > arrayLength) { throw new IndexOutOfBoundsException(); } if (end < start) { throw new IllegalArgumentException(); } } private void ensureFalse(boolean illegalState) { if (illegalState) { throw new IllegalStateException(); } } private void ensureState(State s) { ensureFalse(this.state != s); } private void ensureLevel(int l) { ensureFalse(this.level != l); } private void ensureLevelAtLeast(int lvl) { ensureFalse(this.level < lvl); } private void ensureLevelBetween(int min, int max) { ensureFalse(this.level < min || this.level > max); // NOSONAR - ISE should be thrown when in an illegal state } @Override public Object getProperty(String name) { if (name == null) { throw new IllegalArgumentException("Name must not be null"); } return properties.get(name); } @Override public void close() throws EDIStreamException { flush(); // Do not close the stream } @Override public void flush() throws EDIStreamException { try { writer.flush(); stream.flush(); } catch (IOException e) { throw new EDIStreamException("Exception flushing output stream", location, e); } } @Override public Schema getControlSchema() { return this.controlSchema; } @Override public void setControlSchema(Schema controlSchema) { ensureLevel(LEVEL_INITIAL); this.controlSchema = controlSchema; controlValidator = Validator.forSchema(controlSchema, null, this); } @Override public void setTransactionSchema(Schema transactionSchema) { if (!Objects.equals(this.transactionSchema, transactionSchema)) { this.transactionSchema = transactionSchema; transactionValidator = Validator.forSchema(transactionSchema, controlSchema, this); } } @Override public Location getLocation() { return location; } @Override public String getStandard() { if (dialect == null) { throw new IllegalStateException("standard not accessible"); } return dialect.getStandard(); } @Override public Map<String, Character> getDelimiters() { if (dialect == null) { throw new IllegalStateException("standard not accessible"); } Map<String, Character> delimiters = new HashMap<>(6); putDelimiter(Delimiters.SEGMENT, segmentTerminator, delimiters); putDelimiter(Delimiters.DATA_ELEMENT, dataElementSeparator, delimiters); putDelimiter(Delimiters.COMPONENT_ELEMENT, componentElementSeparator, delimiters); putDelimiter(Delimiters.REPETITION, repetitionSeparator, delimiters); putDelimiter(Delimiters.DECIMAL, decimalMark, delimiters); putDelimiter(Delimiters.RELEASE, releaseIndicator, delimiters); return delimiters; } private Optional<Validator> validator() { Validator validator; // Do not use the transactionValidator in the period where it may be set/mutated by the user if (transaction && !transactionSchemaAllowed) { validator = transactionValidator; } else { validator = controlValidator; } return Optional.ofNullable(validator); } private void write(int output) throws EDIStreamException { write(output, false); } private void write(int output, boolean isPrettyPrint) throws EDIStreamException { CharacterClass clazz; clazz = characters.getClass(output); if (clazz == CharacterClass.INVALID) { throw new EDIStreamException(String.format("Invalid character: 0x%04X", output), location); } state = State.transition(state, dialect, clazz); switch (state) { case HEADER_X12_I: // I(SA) case HEADER_EDIFACT_U: // U(NA) or U(NB) case HEADER_TRADACOMS_S: // S(TX) unconfirmedBuffer.clear(); writeHeader((char) output, isPrettyPrint); break; case HEADER_X12_S: case HEADER_EDIFACT_N: case HEADER_TRADACOMS_T: case INTERCHANGE_CANDIDATE: case HEADER_DATA: case HEADER_ELEMENT_END: case HEADER_COMPONENT_END: case HEADER_SEGMENT_END: writeHeader((char) output, isPrettyPrint); break; case INVALID: throw new EDIException(String.format("Invalid state: %s; output 0x%04X", state, output)); default: writeOutput(output); break; } } void writeHeader(char output, boolean isPrettyPrint) throws EDIStreamException { if (!isPrettyPrint && !dialect.appendHeader(characters, output)) { throw new EDIStreamException(String.format("Failed writing %s header: %s", dialect.getStandard(), dialect.getRejectionMessage())); } unconfirmedBuffer.append(output); if (dialect.isConfirmed()) { // Set up the delimiters again once the dialect has confirmed them setupDelimiters(); // Switching to non-header states to proceed after dialect is confirmed switch (state) { case HEADER_DATA: state = State.TAG_SEARCH; break; case HEADER_ELEMENT_END: state = State.ELEMENT_END; break; case HEADER_SEGMENT_END: state = State.SEGMENT_END; break; default: throw new IllegalStateException("Confirmed at state " + state); } unconfirmedBuffer.flip(); if (EDIFACTDialect.UNA.equals(dialect.getHeaderTag())) { // Overlay the UNA segment repetition separator now that it has be confirmed unconfirmedBuffer.put(7, this.repetitionSeparator > 0 ? this.repetitionSeparator : ' '); } while (unconfirmedBuffer.hasRemaining()) { writeOutput(unconfirmedBuffer.get()); } } } void writeOutput(int output) throws EDIStreamException { try { location.incrementOffset(output); writer.write(output); } catch (IOException e) { throw new EDIStreamException("Exception to output stream", location, e); } } @Override public EDIStreamWriter startInterchange() { ensureLevel(LEVEL_INITIAL); ensureState(State.INITIAL); level = LEVEL_INTERCHANGE; if (controlSchema == null) { LOGGER.warning("Starting interchange without control structure validation. See EDIStreamWriter#setControlSchema"); } return this; } @Override public EDIStreamWriter endInterchange() throws EDIStreamException { ensureLevel(LEVEL_INTERCHANGE); level = LEVEL_INITIAL; flush(); return this; } @Override public EDIStreamWriter writeStartSegment(String name) throws EDIStreamException { ensureLevel(LEVEL_INTERCHANGE); location.incrementSegmentPosition(name); if (state == State.INITIAL) { dialect = DialectFactory.getDialect(name); setupDelimiters(); if (dialect instanceof EDIFACTDialect) { if (EDIFACTDialect.UNB.equals(name) && areDelimitersSpecified()) { /* * Writing the EDIFACT header when delimiters were given via properties requires that * a UNA is written first. */ dialect = DialectFactory.getDialect(EDIFACTDialect.UNA); writeServiceAdviceString(); segmentValidation(name); // Now write the UNB writeString(name); } else { if (EDIFACTDialect.UNA.equals(name)) { writeString(name); writeServiceAdviceCharacters(); } else { segmentValidation(name); writeString(name); } } } else { segmentValidation(name); writeString(name); } } else { segmentValidation(name); writeString(name); } countSegment(name); level = LEVEL_SEGMENT; emptyElements = 0; terminateSegmentTag(); return this; } void countSegment(String name) { if (controlValidator != null) { controlValidator.countSegment(name); } } void segmentValidation(String name) { validate(validator -> validator.validateSegment(this, name)); if (exitTransaction(name)) { transaction = false; validate(validator -> validator.validateSegment(this, name)); } } void terminateSegmentTag() throws EDIStreamException { if (this.segmentTagTerminator != '\0') { write(this.segmentTagTerminator); // TRADACOMS - Empty segments not supported due to fixed segment tag terminator requirement unterminatedElement = false; } else { // Treat the segment tag as an unterminated element that must be closed when element data is encountered unterminatedElement = true; } } void writeServiceAdviceString() throws EDIStreamException { writeString(EDIFACTDialect.UNA); writeServiceAdviceCharacters(); writeSegmentTerminator(); } void writeServiceAdviceCharacters() throws EDIStreamException { write(this.componentElementSeparator); write(this.dataElementSeparator); write(this.decimalMark); write(this.releaseIndicator); // This will be re-written once the dialect version is detected write(this.repetitionSeparator); } private void writeString(String value) throws EDIStreamException { for (int i = 0, m = value.length(); i < m; i++) { write(value.charAt(i)); } } void writeSegmentTerminator() throws EDIStreamException { write(this.segmentTerminator); if (prettyPrint) { for (int i = 0, m = prettyPrintString.length(); i < m; i++) { write(prettyPrintString.charAt(i), true); } } } boolean exitTransaction(CharSequence tag) { return transaction && !transactionSchemaAllowed && controlSchema != null && controlSchema.containsSegment(tag.toString()); } @Override public EDIStreamWriter writeEndSegment() throws EDIStreamException { ensureLevelAtLeast(LEVEL_SEGMENT); if (level > LEVEL_SEGMENT) { validateElement(this.elementBuffer::flip, this.elementBuffer); } level = LEVEL_SEGMENT; validate(validator -> { validator.clearImplementationCandidates(this); validator.validateSyntax(dialect, this, this, location, false); }); if (state == State.ELEMENT_DATA_BINARY) { state = State.ELEMENT_END_BINARY; } writeSegmentTerminator(); switch (state) { case SEGMENT_END: case HEADER_SEGMENT_END: case INITIAL: // Ending final segment of the interchange break; default: if (state.isHeaderState() && dialect instanceof X12Dialect) { throw new EDIStreamException("Invalid X12 ISA segment: too short or elements missing"); } break; } level = LEVEL_INTERCHANGE; location.clearSegmentLocations(true); transactionSchemaAllowed = false; return this; } @Override public EDIStreamWriter writeStartElement() throws EDIStreamException { ensureLevel(LEVEL_SEGMENT); level = LEVEL_ELEMENT; location.incrementElementPosition(); elementBuffer.clear(); elementLength = 0; emptyComponents = 0; unterminatedComponent = false; if (!emptyElementTruncation && unterminatedElement) { write(this.dataElementSeparator); } return this; } @Override public EDIStreamWriter writeStartElementBinary() throws EDIStreamException { writeStartElement(); state = State.ELEMENT_DATA_BINARY; return this; } @Override public EDIStreamWriter writeRepeatElement() throws EDIStreamException { ensureLevelAtLeast(LEVEL_SEGMENT); write(this.repetitionSeparator); // The repetition separator was used instead of the data element separator unterminatedElement = false; level = LEVEL_ELEMENT; location.incrementElementOccurrence(); elementLength = 0; emptyComponents = 0; unterminatedComponent = false; return this; } @Override public EDIStreamWriter endElement() throws EDIStreamException { ensureLevelAtLeast(LEVEL_ELEMENT); if (!atomicElementWrite) { if (level > LEVEL_ELEMENT) { validate(validator -> validator.validateSyntax(dialect, this, this, location, true)); } else { validateElement(this.elementBuffer::flip, this.elementBuffer); } } location.clearComponentPosition(); level = LEVEL_SEGMENT; if (elementLength > 0) { unterminatedElement = true; } else { emptyElements++; } if (state == State.ELEMENT_DATA_BINARY) { state = State.ELEMENT_END_BINARY; } return this; } @Override public EDIStreamWriter startComponent() throws EDIStreamException { ensureLevelBetween(LEVEL_ELEMENT, LEVEL_COMPOSITE); ensureFalse(state == State.ELEMENT_DATA_BINARY); if (LEVEL_ELEMENT == level) { // Level is LEVEL_ELEMENT only for the first component validateCompositeOccurrence(); } if (LEVEL_COMPOSITE == level && !emptyElementTruncation) { write(this.componentElementSeparator); } level = LEVEL_COMPONENT; location.incrementComponentPosition(); elementBuffer.clear(); elementLength = 0; return this; } @Override public EDIStreamWriter endComponent() throws EDIStreamException { ensureLevel(LEVEL_COMPONENT); if (!atomicElementWrite) { validateElement(this.elementBuffer::flip, this.elementBuffer); } if (elementLength > 0) { unterminatedComponent = true; } else { emptyComponents++; } level = LEVEL_COMPOSITE; return this; } @Override public EDIStreamWriter writeElement(CharSequence text) throws EDIStreamException { atomicElementWrite = true; writeStartElement(); CharSequence value = validateElement(() -> {}, text); writeElementData(value); endElement(); atomicElementWrite = false; return this; } @Override public EDIStreamWriter writeElement(char[] text, int start, int end) throws EDIStreamException { atomicElementWrite = true; writeStartElement(); CharSequence value = validateElement(() -> dataHolder.set(text, start, start + end), dataHolder); writeElementData(value); endElement(); atomicElementWrite = false; return this; } @Override public EDIStreamWriter writeEmptyElement() throws EDIStreamException { atomicElementWrite = true; writeStartElement(); // Ignore possibly-formatted value validateElement(dataHolder::clear, dataHolder); endElement(); atomicElementWrite = false; return this; } @Override public EDIStreamWriter writeComponent(CharSequence text) throws EDIStreamException { atomicElementWrite = true; startComponent(); CharSequence value = validateElement(() -> {}, text); writeElementData(value); endComponent(); atomicElementWrite = false; return this; } @Override public EDIStreamWriter writeComponent(char[] text, int start, int end) throws EDIStreamException { atomicElementWrite = true; startComponent(); CharSequence value = validateElement(() -> dataHolder.set(text, start, start + end), dataHolder); writeElementData(value); endComponent(); atomicElementWrite = false; return this; } @Override public EDIStreamWriter writeEmptyComponent() throws EDIStreamException { atomicElementWrite = true; startComponent(); // Ignore possibly-formatted value validateElement(dataHolder::clear, dataHolder); endComponent(); atomicElementWrite = false; return this; } void writeRequiredSeparators(int dataLength) throws EDIStreamException { if (dataLength < 1 || !emptyElementTruncation) { return; } writeRequiredSeparator(emptyElements, unterminatedElement, this.dataElementSeparator); emptyElements = 0; unterminatedElement = false; if (level == LEVEL_COMPONENT) { writeRequiredSeparator(emptyComponents, unterminatedComponent, this.componentElementSeparator); emptyComponents = 0; unterminatedComponent = false; } } void writeRequiredSeparator(int emptyCount, boolean unterminated, char separator) throws EDIStreamException { for (int i = 0; i < emptyCount; i++) { write(separator); } if (unterminated) { write(separator); } } @Override public EDIStreamWriter writeElementData(CharSequence text) throws EDIStreamException { ensureLevelAtLeast(LEVEL_ELEMENT); writeRequiredSeparators(text.length()); for (int i = 0, m = text.length(); i < m; i++) { char curr = text.charAt(i); if (characters.isDelimiter(curr)) { if (releaseIndicator > 0) { write(releaseIndicator); } else { throw new IllegalArgumentException("Value contains separator: " + curr); } } write(curr); elementBuffer.put(curr); elementLength++; } return this; } @Override public EDIStreamWriter writeElementData(char[] text, int start, int end) throws EDIStreamException { ensureLevelAtLeast(LEVEL_ELEMENT); ensureArgs(text.length, start, end); writeRequiredSeparators(end - start); for (int i = start, m = end; i < m; i++) { char curr = text[i]; if (characters.isDelimiter(curr)) { throw new IllegalArgumentException("Value contains separator"); } write(curr); elementBuffer.put(curr); elementLength++; } return this; } @Override public EDIStreamWriter writeBinaryData(InputStream binaryStream) throws EDIStreamException { ensureLevel(LEVEL_ELEMENT); ensureState(State.ELEMENT_DATA_BINARY); int output; try { writeRequiredSeparators(binaryStream.available()); flush(); // Write `Writer` buffers to stream before writing binary while ((output = binaryStream.read()) != -1) { writeBinary(output); } } catch (IOException e) { throw new EDIStreamException("Exception reading binary data source for output", location, e); } return this; } @Override public EDIStreamWriter writeBinaryData(byte[] binary, int start, int end) throws EDIStreamException { ensureLevel(LEVEL_ELEMENT); ensureState(State.ELEMENT_DATA_BINARY); ensureArgs(binary.length, start, end); writeRequiredSeparators(end - start); flush(); // Write `Writer` buffers to stream before writing binary for (int i = start; i < end; i++) { writeBinary(binary[i]); } return this; } @Override public EDIStreamWriter writeBinaryData(ByteBuffer binary) throws EDIStreamException { ensureLevel(LEVEL_ELEMENT); ensureState(State.ELEMENT_DATA_BINARY); writeRequiredSeparators(binary.remaining()); flush(); // Write `Writer` buffers to stream before writing binary while (binary.hasRemaining()) { writeBinary(binary.get()); } return this; } private void writeBinary(int output) throws EDIStreamException { location.incrementOffset(output); try { stream.write(output); } catch (IOException e) { throw new EDIStreamException("Exception writing binary element data", location, e); } elementLength++; } @Override public boolean binaryData(InputStream binary) { // No operation return true; } @Override public boolean elementData(CharSequence text, boolean fromStream) { if (level > LEVEL_ELEMENT) { location.incrementComponentPosition(); } else { location.incrementElementPosition(); } dialect.elementData(elementHolder, location); validator().ifPresent(validator -> { if (!validator.validateElement(dialect, location, elementHolder, derivedComposite(validator), null)) { reportElementErrors(validator, elementHolder); } }); return true; } @Override public void loopBegin(EDIReference typeReference) { final String loopCode = typeReference.getReferencedType().getCode(); if (EDIType.Type.TRANSACTION.toString().equals(loopCode)) { transaction = true; transactionSchemaAllowed = true; if (transactionValidator != null) { transactionValidator.reset(); } } } @Override public void loopEnd(EDIReference typeReference) { final String loopCode = typeReference.getReferencedType().getCode(); if (EDIType.Type.TRANSACTION.toString().equals(loopCode)) { transaction = false; dialect.transactionEnd(); } else if (EDIType.Type.GROUP.toString().equals(loopCode)) { dialect.groupEnd(); } } @Override public void elementError(EDIStreamEvent event, EDIStreamValidationError error, EDIReference typeReference, CharSequence data, int element, int component, int repetition) { StaEDIStreamLocation copy = location.copy(); copy.setElementPosition(element); copy.setElementOccurrence(repetition); copy.setComponentPosition(component); if (this.reporter != null) { this.reporter.report(error, this, copy, data, typeReference); } else { errors.add(new EDIValidationException(event, error, copy, data)); } } @Override public void segmentError(CharSequence token, EDIReference typeReference, EDIStreamValidationError error) { if (this.reporter != null) { this.reporter.report(error, this, this.getLocation(), token, typeReference); } else { errors.add(new EDIValidationException(EDIStreamEvent.SEGMENT_ERROR, error, location, token)); } }
java
Apache-2.0
c23c1fd73e63f17e9b124a3e0c50959d5be83e46
2026-01-05T02:37:40.525758Z
true