Java

99K

Solutions

33K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

I have encountered the following error when compiling the java code. Any idea ?

MyStack.java:76: error: non-static variable this cannot be referenced from a static context
        ArrayStack stack = new ArrayStack();MyStack.java
0
hi am having this error
doc
0
Hello,
I want to find the largest prime of a given number.
This is my solution.
I don't like my solution because I change the variable i in the for loop.
Is there an better solution?


public class LargestPrime {

    public static int getLargestPrime(int number){
        if(number<=1){
            return -1;
        }
        int lpn=number;
        for(int i=2;i<=number;i++){
            if(number%i==0){
                lpn=i;
                number/=i;
                i=i-1;
            }
        }
        return lpn;
    }

    public static void main(String[] args) {
       System.out.println(getLargestPrime(16));
    }
}

Open in new window

0
Experts,
There is a need to add a small method to an existing class inside a JAR file. When I rename the JAR file to zip, I am able to see the Java Class into which I need to add the new method. I do not have a project for this jar as the developer who programmed it is not with the company anymore, and for various reasons the project he developed is not available in the repository. Considering we very rarely need any modification on that jar file, was wondering if it is possible for me to do the required modifications directly within the JAVA file in the JAR, recompile just the CLASS file, re-zip it and rename it to JAR. Since this is an immediate requirement, I felt constructing the project might take more time.

Any inputs/suggestions greatly appreciated :)
0
Hi
Is Taylor Swift a ruthless legal vulture with Indiana Jones - Temple of Doom fiery-ruby eyes?

just kidding :)

In my phone game, I'd like to have pics/icons of everyday objects (sketches) in scenes for a points collection aspect. (and for level advancements)

If I do my own black and white sketches from images I find of Taylor Swift, or Metallica or Jimi Hendrix, or even an elephant, television, car, or an outline of Bolivia, cobweb..

What legal nightmares might I be heading into? Are original outlines of copyrighted images, or close interpretations (my own outlines) of them a path to the guillotine?
Is there a good way in photoshop to generate an amazingly creative approximation of a picture?

For an elephant, I might want icons something like this :

elephant icon
or of Jimi

Jimi Hendrix icon
or Taylor

taylor.jpg
Thanks
0
hi am having error in my spring boot
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
663 [main] INFO ncs.app.co.za.NcsApp - Starting NcsApp on Desmand-PC with PID 17780 (C:\projects\NcsApp\bin started by user in C:\projects\NcsApp)
663 [main] INFO ncs.app.co.za.NcsApp - No active profile set, falling back to default profiles: default
2072 [main] INFO ncs.app.co.za.NcsApp - Started NcsApp in 1.948 seconds (JVM running for 2.427)
2074 [main] INFO org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener -

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2182 [main] ERROR org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter -

***************************
APPLICATION FAILED TO START
***************************

Description:

A component required a bean named 'NocIigJDBCTemplate' that could not be found.


Action:

Consider defining a bean named 'NocIigJDBCTemplate' in your configuration.

package ncs.app.co.za;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import 

Open in new window

0
Dear Gurus,
I am new to Java and trying to write a code where need to match a number 'y' from an array list x[].
If teh number matches, it should give the index value else return the value '-1'
I have written the code and it works...except that when the value doesn't match, it returns '-1' multiple times.
Is there a way that it returns '-1' only once.? Thankyou !

import java.io.*;
public class findLast {
    public static void main(String[] args) {
        try {
            boolean matchFound = false;
            int[] x = {7, 8, 9, 10, 11, 12};
            int y = 4;

            for (int i = x.length - 1; i >= 0 && matchFound == false; i--) {
                if (x[i] == y) {
                    System.out.println("Index is " + i);
                    matchFound = true;
                }
                else if (matchFound == false){
                    System.out.println(-1);
                }
            }

        }
        catch (NullPointerException e) {
            System.out.print("NullPointerException Caught");
        }
    }
}

Open in new window


Output:
C:\MS\src>java findLast
-1
-1
-1
-1
-1
-1
0
HI Team,

i am executing below code its working fine when i change the date then check particular row check box  then submit. but it's not working when i clicked on check box first then change the date and submit . please tell me the solution of my problem thanx a ton in advance i m new in java script and jquery so please tell me particular solution on my code .


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet"
	href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
  
$(document).ready(function() {

	$(".date").datepicker({dateFormat:'dd/mm/yy'});
	$('.chkValues').on('click', function() {
		//get values of dates
		var array = [];
		var parent = $(this).closest('tr');
	    
	    // Now find all the child <inpu> elements with class "date"
	    var last = 0;
	    $('.date', parent).each(function(i,e) {
	      var dt = new Date(e.value.split("/").reverse().join("-"));
	      alert(dt);
	      console.log(dt.getTime());
	      if (dt.getTime() <= last) {
	        alert('Error: ' + e.id + ' has an invalid value');
	      }
	      last = dt.getTime();
	    });
		$row = $(this).data('row'); //row1, row2, row3 etc
		$('input.' + 

Open in new window

0
I am seeking advice and suggestions concerning creating PDF documents. I researched many sites but thought I would ask you folks about it.
I will be extracting data from MS SQL Server - 2014 database from many tables to create/populate the PDF document which will be on our web server.
Basically, the user will click a button and code will generate the PDF file.
I can find my way around Java but client doesn't not want to use C or Net.
I use localhost - Win 10 - and mainly PHP - v5.6.25 (client version - no plans to upgrade - their web server is Linux) with Wampserver and Apache 2.4.23.
I have looked at Apache PDFBox - got confused about it. I also took a long peek at iText. I did request a quote but they have never responded to me.
The creation of the PDF document must be created programmatically.
Any thoughts - suggestions - advice would be appreciated.
thank you.
0
I have a question related with log4j.
I had put log4j.properties file under src folder,  I am using PropertyConfigurator.configure("log4j.properties") to lad the file before calling the logger.
But it can't pick up the file "log4j.properties".
How can i load the file?
there is a spring-servlet.xml under WEB-INF folder, which defined the datasource. Can I add  the property file there?
or can I add a context for this?


Here is an example bean that defined in spring-servlet.xml:
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
          <property name="configLocation" value="/WEB-INF/ehcache.xml"/>
          <property name="shared" value="true"/>
    </bean>      

should I do something samiliar like this?      


Any inputs are welcome.
0
hi am having error running my nodejs








PS C:\Angular3\mean-course> node server.js
C:\Angular3\mean-course\server.js:47
app.set("port", port);
    ^

TypeError: app.set is not a function
    at Object.<anonymous> (C:\Angular3\mean-course\server.js:47:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
PS C:\Angular3\mean-course> npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2
0
Do Bullrun and Edgehill, along with some of the inbuilt shortcomings of SSL/TLS itself, mean that encryption amounts to not much more than a myth ?
0
hold.tarI have failing call to update a table of salesforce. It returns this message:

update Opportunity set NextStep='Contact John Smith' where ID = '0066g00000fjfOqAAI'[ { "message" : "unexpected token: update", "errorCode" : "MALFORMED_QUERY" } ]


Here is my source code

public class SFEngine {
        public static final String clientId="3MVG9LBJLApeX_PDRFsRBGTuqsN.m3Vd1bIwEF5_FNoEUKGVX0gBqUM1YdL52614KXSW9O6pL6abWun9soVyw";

        public static final String clientSecret="8F418A0BCE45412081ED5D3057A20B178C203A05EC368BFC67D82FF5C4BFBD92";
        public static final String redirectUrl="https://na174.salesforce.com/services/oauth2/callback";
        public static  String tokenUrl="https://login.salesforce.com/services/oauth2/token";
        public static final String environment="https://login.salesforce.com";
        public static final String username="xxxxxxxxxxx";
        public static final String password="xxxxxxxxxxx";                

        public static  String accessToken="";
        public static  String instanceUrl="";
        public HttpClient httpclient;
        public  HttpResponse queryResponse ;
        public  JsonNode queryResults;
        public  HttpGet get;
        public  URIBuilder builder;

private static final String TOKEN_URL =  "https://login.salesforce.com/services/oauth2/token";
public static String  OpenRest(String ID, String Field, String Value) {

        String consumerKey = clientId;
        …
0
Hey i want to use datatables for the first time but it is not working:
THis code is in my header:
        <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css/">

        <script type="text/javascript" src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>

Open in new window

And this is the table:
    <table id = "myTable">
        <thead>
            <th>Username</th>
            <th>Result</th>
            <th>Quiz name</th>
            <th>Category</th>
            <th>Date</th>
        </thead>
        <tbody>
            {% for res in result_sql %}
            <tr>
                <td>{{res.username}}</td>
                <td>{{res.result}}</td>
                <td>{{res.quiz_name}}</td>
                <td>{{res.category}}</td>
                <td>{{res.date}}</td>
            </tr>
            {% endfor %}

        </tbody>


    </table>
<script>
$(document).ready( function () {
    $('#myTable').DataTable();
} );
</script>

Open in new window


Can anyone find the problem?
0
is it better to represent as String and Object or will there be any issue in the future ?
Thanks Experts sir.

@Override
      public void buildObjectMap() {
            super.buildObjectMap();
            Map<String, Object> objectMap =  getObjectMap();
            objectMap.put("id", id);
            objectMap.put("status", this.getStatus());
            objectMap.put("scheduledDate", this.getScheduledDate());
            objectMap.put("visitationPoint", visitationPoint.toJsonizedMap());
            objectMap.put("teamId", this.getTeam().getId());
            objectMap.put("teamName", this.getTeam().getTeamname());
            
            objectMap.put("locationId", this.getVisitationPoint().getLocation().getId());
            objectMap.put("locationName", this.getVisitationPoint().getLocation().getName());
            objectMap.put("locationType", this.getVisitationPoint().getLocation().getLocationType().getName());
      }
1
why data format is being set like this below on createdDate ? IS this correct expert ?
@Override
      public void buildObjectMap() {
            super.buildObjectMap();
            Map<String, Object> objectMap =  getObjectMap();
            
            objectMap.put("user_id", worker.getUsername());
            objectMap.put("session_id", session_id);
            objectMap.put("imei1", imei1);
            objectMap.put("imei2", imei2);
            objectMap.put("macId", macId);
            objectMap.put("session_id", session_id);
            // Date format is defined but it is used in the created_Date format which has been specified here
          DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");  
       // String strDate = dateFormat.format(super.getCreated());  
            objectMap.put("created_Date",createdDate);
      }
0
Hi everyone,

I just did a dependency check in my code and I get:
https://nvd.nist.gov/view/vuln/search-results?adv_search=true&cves=on&cpe_version=cpe%3A%2Fa%3Anetty%3Anetty%3A3.10.5

I've searched in my dependencies (POM.xml and the whole project too) but I could not find netty.
For this reason I think that it is some child dependency.
So I did a maven dependency tree but also searching there didn't get any netty hit.

What am I missing?

Thanks for your help.
0
Hi Experts,

//Path Traversal Issue
				
String configuration = path +File.separator+"data"+File.separator+temp+File.separator+id+type+"."+frmt;
File newFilePath = new File(configuration);

Open in new window


please suggest how to change the above to resolve path traversal issue.
0
Hi Experts,

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cp " +sourceFile+" "+destFile);

Open in new window


is there any specic reason using the above code or it is legacy code.
can i use alternative approach as below or any better approach is there for file copying

Files.copy(source.toPath(), dest.toPath());

Open in new window

1
private void submitCallablesWithExecutor()
				throws InterruptedException, ExecutionException, TimeoutException {

			ExecutorService executorService = null;

			try {
				executorService = Executors.newCachedThreadPool();

				Future<String> task1Future = executorService.submit(new Callable<String>() {

					public String call() {
						try {
							processExportRequest(xmlPutRequest_, customizedRequest_, response_);
							return "Success";
						} catch (Exception ex) {
							return ex.getMessage();
						}
					}
				});

			} finally {
				executorService.shutdown();

				try {
					if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
						executorService.shutdownNow();
					}
				} catch (InterruptedException e) {
					executorService.shutdownNow();
				}
			}
		}

Open in new window


within processExportRequest I am calling upload to S3.  I have tried both S3Client and S3AsyncClient.  In both cases, I am getting following error:

Failed to upload to S3: java.lang.IllegalStateException: Interrupted waiting to refresh the value.

I don't see anywhere in my code that's calling Thread.interrupt(), and everything else seems to work fine, just not S3 upload.  Maybe the multithreaded nature of Java Future is not compatible with AWS SDK?  Thanks.
0
Java issue with determining whether a folder is a file or a directory. The following is an excerpt of code that demonstrates the problem:
public static boolean needsNewTable(String version, String schemas, String spreadsheets)  {
            xsdVersion = version;
            System.out.println(schemas);
            System.out.println(spreadsheets);
                  
            File xlsFolder = new File(spreadsheets);
            System.out.println(xlsFolder.isDirectory());
            System.out.println(xlsFolder.isFile());
            
And the output is:
C:\Users\ZW5FB\Documents\ZW5FB\NewSpreadsheet\Schemas
C:\Users\ZW5FB\Documents\ZW5FB\NewSpteadsheet\Spreadsheets
false
false

Can someone tell me why I get false for both the isDirectory method and the isFile method (the same holds true for the xsdFolder = new File(schemas) ? Additionally, if I specify an exact schema file and an exact spreadsheet I get false for both methods as well.
0
Hello Experts,
Am trying to modify an excel file having multiple rows using Apache POI 3.17 (i.e. remove the rows). When I tried to remove the rows in the first while loop, I used to receive the error concurrentmodificationexception. I tried moving all the rows into a list and then delete it in a separate loop as suggested in one of the forums. I now receive XmlValueDisconnectedException. Can anyone please suggest what might be going wrong here?

public static void removeFalseRows(String readFilePath, String writeFilePath, String sheetName) throws IOException, InvalidFormatException {
		List<Row> toRemove = new ArrayList<Row>();
		FileInputStream fsIP = new FileInputStream(new File(readFilePath));
		Workbook wb = WorkbookFactory.create(fsIP);
		Sheet sheet = wb.getSheet(sheetName);
		Iterator<Row> rowIterator = sheet.iterator();
		while (rowIterator.hasNext()) {
			Row row = rowIterator.next();

			if (row.getCell(5).toString().equals("false")) {
				toRemove.add(row);
			}
		}

		for(Row R : toRemove) {
			sheet.removeRow(R);
		}

		for(Row R : toRemove) {
			int rowIndex = R.getRowNum();
			int lastRowNum = sheet.getLastRowNum();
			if (rowIndex >= 0 && rowIndex < lastRowNum)
			{
				sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
			}
		}

Open in new window

0
Sir,

I have issue with the code base can some body help me, i am working on JPA but issue is how to pass the value in the findByOrgUnits
which is not correct. The value need to pass is a List value to the other screen. The content is List value which need to be pass to the
 the JPa Below, but the issue is which passing orgUnitTypes i am getting variable is not set correct in the input itself.

public AdminDTO getAllLookupData(int pageNo, int pageSize, String sortType, List<String> sortFields, String locale)
throws CmsDaoException {
             
            OrgUnitsLang orgUnitsLang;
            Long orgUnitId = orgunit.getOrgunitId();
            Set<OrgTransactionTypes> orgTransactionTypes;
            Languages languages = languagesRepository.findByLocale(locale);
            OrgUnits orgUnit = orgUnitRepo.findByOrgunitId(orgUnitId);
            OrgUnitTypes[] orgUnitsLang;
                  
            List<OrgUnitsLang> orgUnitlang = orgTransactionTypesRepo.findByOrgUnits(orgUnitTypes);
            
            
            The code below
            
      
@Repository
    public interface OrgTransactionTypesRepository extends JpaRepository<OrgTransactionTypes, Long>, JpaSpecificationExecutor{

	
	//to retrieve transaction type ids 
	List<OrgTransactionTypes> findByOrgUnits(OrgUnits orgUnits);
	
	OrgTransactionTypes findByOrgUnitsAndTransactionTypes(OrgUnits orgUnits,
			LookupTransactionTypes transactionTypes);

	@Query("SELECT orgTransactionTypes from OrgTransactionTypes orgTransactionTypes where orgTransactionTypes.orgUnits in :unitList")
	public List<OrgTransactionTypes> 

Open in new window

0
I want to upload a file to S3 bucket, but my company want to use IAM role as opposed to access keys.  This is AWS documentation on how to upload to S3 asynchronously:

S3AsyncClient client = S3AsyncClient.create();
		CompletableFuture<PutObjectResponse> future = client.putObject(
				PutObjectRequest.builder().bucket(BUCKET)
						.key(fileName)
						.build(),
				AsyncRequestBody
						.fromFile(fromFile.toPath()));
		future.whenComplete((resp, err) -> {
			try {
				if (resp != null) {
					System.out.println("my response: " + resp);
				} else {
					// Handle error
					err.printStackTrace();
				}
			} finally {
				// Lets the application shut down. Only close the client when
				// you are completely done with it.
				client.close();
				
			}
		});

		future.join();
	}

Open in new window


I don't see anywhere to put in IAM role info.  I tried to put it in ~/.aws/credentials in this form:

[useraccount]
aws_access_key_id=<key>
aws_secret_access_key=<secret>

[somerole]
role_arn=<the ARN of the role you want to assume>
source_profile=useraccount

but so far haven't gotten it to work.  I read somewhere you need to use STSAssumeRoleSessionCredentialsProvider but didn't see any good examples.  My main question is do I even need to do anything if I already assigned the IAM role to an ECS instance.  Can someone help me?   Thanks.
0
I have a utility class TransactionType

The
public  setOrgTransMap(List<OrgTransactionTypes> list,long count, List<LookupConfigValues>  lookupConfigValues, List<Languages> languageList,String locale) {

Open in new window

I am calling setOrgTransMap in another in the dao class called Xnr( Just to keep secret)

public orgTransactionTypesUtility.setOrgTransMap(newOrgTrasnTypesList, COUNT,configValues, languageList,locale);

Open in new window


But i am giving all the input values but i am getting "configValues cannot be resolved to a variable"
By the way configValues  is not coming in the current DAO class, is it issue with my code or I am lost the java class.
0

Java

99K

Solutions

33K

Contributors

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.