How to put path in variable without getting null exception - java

Im trying to do the quick following:
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/" + items.get(seed).getImage())));
however I am getting Null Pointer exception in the above line.
The program is running fine when I am using it in following manner.
lblNewLabel.setIcon(new ImageIcon(ItemDialog.class.getResource("/items/item10312344.jpeg")));
it works.
EDIT: seed is the index number (1 in this case). items.get(1).getImage() holds the value of item10312344.jpeg but as above I get a null exception. but if manually input it, it works
what do I need to do to make this not get a null exception by getting it from the item list?

Try to validate the object before calling "getImage"
//FIRST OF ALL: Make sure "items" is not null
if(items != null && items.get(seed) != null){
ItemDialog itemDialog = ItemDialog.class.getResource("/items/" + items.get(seed).getImage())
if(itemDialog != null)
lblNewLabel.setIcon(new ImageIcon(itemDialog));
}
/*I am not sure about of which type is the object items is carrying, but a more
decent approach would be*/
if(items != null){
"ObjectThatItemsIsCarrying" obj = items.get(seed);
//Checking if you got the image name
if(obj != null)
ItemDialog itemDialog = ItemDialog.class.getResource("/items/" + obj.getImage());
//Cheking if you got the image
if(itemDialog != null)
lblNewLabel.setIcon(new ImageIcon(itemDialog));
}

Put the path in a string and use the string in the getResource method.
String path = "/items/" + item.get(seed).getImage();

Related

Discord JDA check OnlineStatus of a Bot

I'm trying to create a Status Command which, among other things, queries whether a particular Discord bot is online. However, I get a null pointer exception when I execute the command.
Member jutils_bot = Objects.requireNonNull(event.getGuild()).getMemberById("937273424852705342");
assert jutils_bot != null;
embed.setDescription("Auth System\n" + (code == 200 ? ":white_check_mark:" : ":x:")
+ "\nWebsite\n" + websiteFile
+ "\nJUtils Bot\n" + (jutils_bot.getOnlineStatus() == OnlineStatus.ONLINE ? ":white_check_mark:" : ":x:"));
I have already checked my intents, however they are enabled.

ComboAnalyzer - AttributeImpl not found in AttributeSource

The analyzer OpenNLPAnalyzer based on OpenNLPTokenizer in the opennlp package that ships with Lucene in this blog post works as promised. I am now trying to use it inside an ComboAnalyzer (a part of an ES-plugin to combine multiple analyzers; see link below) in the following way:
ComboAnalyzer analyzer = new ComboAnalyzer(new EnglishAnalyzer(), new OpenNLPAnalyzer());
TokenStream stream = analyzer.tokenStream("fieldname", new StringReader(text));
stream is a ComboTokenStream. On calling stream.incrementToken(), I get the following exception at line 105 here:
Exception in thread "main": State contains AttributeImpl of type org.apache.lucene.analysis.tokenattributes.OffsetAttributeImpl that is not in in this AttributeSource
Here is what the called method restoreState does.
public final void restoreState(State state) {
if (state == null) return;
do {
AttributeImpl targetImpl = attributeImpls.get(state.attribute.getClass());
if (targetImpl == null) {
throw new IllegalArgumentException("State contains AttributeImpl of type " +
state.attribute.getClass().getName() + " that is not in in this AttributeSource");
}
state.attribute.copyTo(targetImpl);
state = state.next;
} while (state != null);
}
This hints that one of the TokenStreams has an OffsetAttribute but the other does not. Is there a clean way to fix this?
I tried to add the line addAttribute(OffsetAttribute.class) in the same file here. I still get the same exception.
The problem was here:
Tokenizer source = new OpenNLPTokenizer(
AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY, sentenceDetectorOp, tokenizerOp);
The fix is to pass in TokenStream.DEFAULT_TOKEN_ATTRIBUTE_FACTORY instead of AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY. The former uses PackedTokenAttributeImpl for implementing OffsetAttribute (and many other attributes) and the latter picks OffsetAttributeImpl.

Erro NULL CHECK SonarQube

I have an error in the SonarQube of Nullcheck of call when assigning a value to a stored procedure.
call.setBigDecimal(ONE, bank != null ? bank : BigDecimal.ZERO);
Exactly in this excerpt above. He makes the same mistake if he removes the ternary. I did an IF before the function and the same error occurred.
enter image description here
public CarrierReturnDTO getMobileCarriers(BigDecimal bank) throws SQLException {
CarrierReturnDTO carrierReturnListDTO = new CarrierReturnDTO();
List<CarrierDTO> mobileCarrierList = new ArrayList<CarrierDTO>();
DataSource dataSource = jdbcTemplate.getDataSource();
if (dataSource != null) {
try (Connection connection = dataSource.getConnection()) {
if (connection != null) {
try (CallableStatement call = connection.prepareCall(Constants.COMBO_OPERCEL)) {
call.setBigDecimal(ONE, bank != null ? bank : BigDecimal.ZERO);
call.registerOutParameter(TWO, OracleTypes.CURSOR);
call.execute();
ResultSet rs = (ResultSet) call.getObject(TWO);
while (rs.next()) {
CarrierDTO mobileCarrier = new CarrierDTO();
mobileCarrier.setMobileCarrierCode(rs.getBigDecimal(Constants.COD_EMP_OPER));
mobileCarrier.setMobileCarrier(rs.getString(Constants.NOM_EMP_OPER));
mobileCarrier.setAmountDigitChecked(rs.getBigDecimal(Constants.QTD_DIG_VERIFIC));
mobileCarrier.setFlagDoubleDigit(rs.getString(Constants.FLG_DUP_DIGIT));
mobileCarrier.setBankCode(rs.getString(Constants.BCO_CNV_ALTAIR));
mobileCarrier.setBranchCode(rs.getString(Constants.AGE_CNV_ALTAIR));
mobileCarrier.setAccountCode(rs.getString(Constants.CTA_CNV_ALTAIR));
mobileCarrierList.add(mobileCarrier);
}
rs.close();
}
}
}
}
carrierReturnListDTO.setCarriers(mobileCarrierList);
return carrierReturnListDTO;
}
You have SonarQube's NullCheck enabled. This will give you an error for using a null check in places where a variable cannot be null. Following documentation, this would mean that you are never passing a null into getMobileCarriers(). For robustness of your code, having that null check is a good idea (as you might be using that method from elsewhere, or even externally at some point). Therefore, I would recommend looking into SonarQube's setup and either turning this check off or modifying it such that it won't perform this analysis cross-method calls.

ExceptionConverter com.itextpdf.text.pdf.parser.InlineImageUtils$InlineImageParseException: Could not find image data or EI 420

I am using iText to extract Text from PDF, however, I had the following exception, and it cannot be caught by try/catch(Exception e), I have attached the file here, actually I don't care very much whether I can extract text from it, I just want to know how to catch the exception.
Exception:
ExceptionConverter: com.itextpdf.text.pdf.parser.InlineImageUtils$InlineImageParseException: Could not find image data or EI
420
at com.itextpdf.text.pdf.parser.InlineImageUtils.parseInlineImageSamples(InlineImageUtils.java:386)
at com.itextpdf.text.pdf.parser.InlineImageUtils.parseInlineImage(InlineImageUtils.java:156)
at com.itextpdf.text.pdf.parser.PdfContentStreamProcessor.processContent(PdfContentStreamProcessor.java:427)
at com.itextpdf.text.pdf.parser.PdfReaderContentParser.processContent(PdfReaderContentParser.java:80)
at com.itextpdf.text.pdf.parser.PdfTextExtractor.getTextFromPage(PdfTextExtractor.java:74)
File: https://www.dropbox.com/s/4l4ioqzpcca05vc/Understanding%20the%20High%20Photocatalytic%20Activity%20of%20%28B%2C%20Ag%29-Codopeda312205c_si_001.pdf?dl=0
The problematic inline Image is
q 12 0 0 1.5 598.5 2905.5 cm
BI
/CS/RGB
/W 8
/H 1
/BPC 8
/F[/A85
/Fl]
/DP[null
<</Predictor 15
/Columns 8
/Colors 3>>]
ID
Gar9F/1Xl3A2+09nF?)T!(_,53r~>
EI Q
on page 5. The null unfortunately is parsed as PdfLiteral with value "null", not as PdfNull instance. Thus, PdfReader.decodeBytes() throws an exception in
PdfObject dpEntry = getPdfObject(dp.get(j));
if (dpEntry instanceof PdfDictionary){
decodeParams = (PdfDictionary)dpEntry;
} else if (dpEntry == null || dpEntry instanceof PdfNull) {
decodeParams = null;
} else {
throw new UnsupportedPdfException(MessageLocalization.getComposedMessage("the.decode.parameter.type.1.is.not.supported", dpEntry.getClass().toString()));
}
Replacing
} else if (dpEntry == null || dpEntry instanceof PdfNull) {
by
} else if (dpEntry == null || dpEntry instanceof PdfNull || (dpEntry instanceof PdfLiteral && Arrays.equals("null".getBytes(), ((PdfLiteral)dpEntry).getBytes()))) {
makes the code work for the OP's PDF.

Object doesn't support this method or property error

Hi I created a jni jar and i call the jar using applet in java script. I use the following applet tag to create a object to call jar functions through java script. when i call the function i got the following error Object doesn't support this method or property.
Here is my code.
document.write('<applet code="BiomAPI.Legend.class" width="0" height="0" archive="BiomAPI.jar" id="Obj"></applet>');
function GetTemplateAccurate (sUserID,iFingerID)
{
document.getElementsByName("Enroll")[0].value = "";
document.getElementsByName("Image")[0].value = "";
var lsFeature = null;
var lsImage = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SaveImage(1);
Obj.SessionID("abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde");
Obj.GetFeatureAccrual(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null && lsImage != null )
{
document.getElementsByName("Enroll")[0].value = lsFeature;
document.getElementsByName("Image")[0].value = lsImage;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
function GetTemplate(sUserID,iFingerID)
{
document.getElementsByName("Verify")[0].value = "";
var lsFeature = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SessionID("abcde");
Obj.SaveImage(1);
Obj.GetFeature(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null)
{
document.getElementsByName("Verify")[0].value = lsFeature;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
as exception itself is describing:
Object doesn't support this method or property error
the property or method you are trying to access with an object is not supported by that object. Please debug or see on error console the object throwing exception and find whether it support that property you are trying to access.

Categories