RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-254647

Alex's questions

Martin Hope
Alex
Asked: 2022-06-06 18:43:01 +0000 UTC

Mockito 不模拟方法(需要但未调用)

  • 0

大家好。有这个类:

public class Class_A {


public String method1(String str1){
    try {

        return Class_B.calc(str1);

    } catch (Exception e) {
        // вот здесь  e.getMessage() = "Ошибка сервиса"
        throw new MyException(e.getMessage(), e);
    }

}


public boolean method2(String str1, String str2){

    return method1(str1).equals(str2);
}


public void throwMyExceptionIfNoUser(String str1, String str2) throw MyException {
    if (!method2(st1, str2)) {
        throw new MyException(String.format("Отсутвует пользователь %s", str1));
    }
}

}

有这个测试:

    @ExtendWith(MockitoExtension.class)

@RunWith(JUnitPlatform.class) //@MockitoSettings(strictness = Strictness.LENIENT)

类 Class_ATest {

@org.junit.jupiter.api.BeforeEach
void setUp() {
}

@org.junit.jupiter.api.AfterEach
void tearDown() {
}


/**
 * этот тест возвращает вот это
 *
 * java.lang.NullPointerException
 * at ua.avk.junit.Class_A.method1(Class_A.java:9)
 *
 */
@org.junit.jupiter.api.Test
void throwMyExceptionIfNoUser_v1() {
    String str1 = "str1";
    String str2 = "str2";

    Class_A  classA = Mockito.spy(new Class_A());

    Assertions.assertNotNull(classA);

    Mockito.when(classA.method2(str1, str2)).thenReturn(false);
    //Mockito.doReturn(false).when(classA).method2(str1, str2);

    MyException myException = Assertions.assertThrows(
            MyException.class,
            () -> { throw new MyException(String.format("Отсутвует пользователь %s", str2)); }
    );

    //Mockito.verify(classA).hasRole(str1, str2);

    //String exp = String.format("Ошибка сервиса Отсутвует пользователь %s", str2);
    String exp = String.format("Отсутвует пользователь %s", str2);
    String act = myException.getMessage();

    Assertions.assertEquals(exp, act);
}



/**
 * этот тест возвращает вот это
 *
 *
 * Wanted but not invoked:
 * classA.method2(
 * "str1",
 * "str2"
 * );
 * -> at ua.avk.junit.Class_ATest.throwMyExceptionIfNoUser_v2(Class_ATest.java:73)
 * Actually, there were zero interactions with this mock.
 *
 * Но если убрать проверку Mockito.verify то он возвращвет  "Ошибка сервисa Отсутвует пользователь %s", str2"
 * Получается что он не мокает method2
 */
@org.junit.jupiter.api.Test
void throwMyExceptionIfNoUser_v2() {
    String str1 = "str1";
    String str2 = "str2";

    Class_A  classA = Mockito.mock(Class_A.class);

    Assertions.assertNotNull(classA);

    Mockito.when(classA.method2(str1, str2)).thenReturn(false);

    MyException myException = Assertions.assertThrows(
            MyException.class,
            () -> { throw new MyException(String.format("Отсутвует пользователь %s", str2)); }
    );

    Mockito.verify(classA).hasRole(str1, str2);

    //String exp = String.format("Ошибка сервисa Отсутвует пользователь %s", str2);
    String exp = String.format("Отсутвует пользователь %s", str2);
    String act = myException.getMessage();

    Assertions.assertEquals(exp, act);

}

}

我使用这些依赖项:

        <jupiter.version>5.7.0</jupiter.version>
    <junit-platform.version>1.7.2</junit-platform.version>
    <mockito.jupiter.version>3.7.7</mockito.jupiter.version>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${jupiter.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>${jupiter.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${jupiter.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>${junit-platform.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-core</artifactId>
        <version>${mockito.jupiter.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-junit-jupiter</artifactId>
        <version>${mockito.jupiter.version}</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>

测试结果在测试的注释中给出。 事实证明,mockito 没有模拟任何东西!?为什么???或者,也许,我没有正确理解模拟如何工作的技术???

请帮我解决模拟问题,我已经铲了一堆码头(在stackOverflow上->也是),但是,不幸的是,我没有找到一个可理解的答案......提前谢谢你的回答。

junit
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-06-06 12:30:49 +0000 UTC

Rider 在启动时出错,同时同步模板

  • 0

我使用 Windows 7x64 Ultimate。我想尝试 Jet Brains Rider,但在启动时出现持续错误、持续冻结以及在 Rider 2017-2018 的所有版本上如何禁用此同步并克服启动时的错误,以及查看日志实例,它是空的...

同步

启动时出错

c#
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-05-22 05:14:09 +0000 UTC

使用 Win 服务读取文件

  • 0

大家好。

在 C# 中创建了一个服务(我并不特别......),它应该一路读取 *.xml 并执行任务。

启动服务崩溃时出现问题 - 我认为这是由于读取 xml。没有它,服务将正常启动并运行。这是一个示例代码:

    namespace Backup1cSrvInstaller
    {
        public class WinServiceInstaller2 : ServiceBase
        {
            private static Logger logger = LogManager.GetCurrentClassLogger();

            const string MyServiceName = "Backup1C";

            public WinServiceInstaller2()
            {               
                InitializeComponent();
            }


            private void InitializeComponent()
            {
                this.ServiceName = MyServiceName;
            }

            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
            }

            protected override void OnStart(string[] args)
            {
                logger.Trace("[WinService] -> service onSTART");
                Task.Run(() => Foo(10));
            }

            protected override void OnStop()
            {
                logger.Trace("[WinService] -> service onSTOP");

            }

            async void Foo(int taskCount) {
                int delay = 10000;
                //AppService appSrv = new AppService();
                DataService dataSrv = new DataService();

                while (true) {
                    logger.Info("[WinServiceInstaller] -> TASK START [***** Starting new block *****]");

                    List<Data> datas = dataSrv.readXml();

                    /*
                    DateTime dt = new DateTime();
                    foreach(Data data in datas){
                        logger.Info("[WinServiceInstaller] -> For-1");
                        Schedule sc = data.ScheduleObj;
                        for(int i=0; i<sc.Days.Count; i++){
                            logger.Info("[WinServiceInstaller] -> For-2");
                            if(dt.DayOfWeek.Equals(sc.Days[i])){
                                logger.Info("[WinServiceInstaller] -> IF-1");
                                for(int j=0; j<sc.Times.Count; j++){
                                    logger.Info("[WinServiceInstaller] -> For-3");
                                    //DateTime dt2 = DateTime.Parse(sc.Times[j].);
                                    if(dt < sc.Times[j]){
                                        logger.Info("[WinServiceInstaller] -> IF-2");
                                        logger.Info("[TASK] -> TASK START -> ID: " + data.Id + ", Name: " + data.ShortName);
                                    }
                                }
                            }
                        }
                    }
                    */

                    /*
                    for (int i = 0; i < taskCount; i++) {
                        int index = i;
                        await Run(delay, index);
                    }
                   */  
                }
            }
            async Task Run(int delay, int taskIndex) {
                //Console.WriteLine("Do some operation, index is: {0}", taskIndex);
                logger.Info("Do some operation, index is: " + taskIndex);
                await Task.Delay(delay);
            }




        }

一般来说,这就是问题所在。一般来说,xml 是可读的,也许。它被另一个程序的主界面读取。他想提交一个带有任务的服务......

但我确定这与 xml 读取方法有关...

我是这样读的(这可能是问题所在)

        ...
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load(fileName);
        XmlElement xRoot = xDoc.DocumentElement;

        foreach (XmlElement xnode in xRoot) {
         ...

那你怎么读呢?

c#
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-03-04 23:15:41 +0000 UTC

通过网络传输android文件

  • 0

大家好。我没有使用android的经验,所以我遇到了这个问题,我无法以任何方式解决。

问题是无法从 android 发送 115MB 的视频文件。

它是如何表达的:

更准确地说,在 115Mb 中,有 52Mb 进入服务器,传输停止在那里。服务器返回 code = 200 并写入它已收到一个 52MB 的文件。虽然从应用程序发送了一个 60MB 的文件 - 没问题!

下面是使用的代码示例。

    private class UploadImageTask extends AsyncTask<String, Void, List<File>> {
    protected List<File> doInBackground(String... args) {
        runOnUiThread(new Runnable() {
            public void run() {
                resultTextView.append("\nuploading started.....");
            }
        });

        for (File file : fileList){
            uploadFile(file);
        }

        return null; //loadImageFromNetwork(urls[0]);
    }

    protected void onPostExecute(List<File> list) {
        resultTextView.append("\nUPLOAD -> STATE: " + MultipartUtility.status);
        resultTextView.append("\nUPLOAD -> END");
        Toast.makeText(getApplicationContext(), "UPLOAD: -> END", Toast.LENGTH_LONG).show();
    }
}




public int uploadFile(File sourceFile) {


    final String fileName = sourceFile.getName();

    HttpsURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable;//, bufferSize;
    byte[] buffer;
    int maxBufferSize = 4 * 1024 * 1024;
    long fileSize = sourceFile.length();

    if (!sourceFile.isFile()) {

        Log.e("uploadFile", "Source File not exist :"
                //+ uploadFilePath + "" + uploadFileName);
                + sourceFile.getName()
        );

        runOnUiThread(new Runnable() {
            public void run() {
                resultTextView.append("Source File not exist :"
                        //+uploadFilePath + "" + uploadFileName);
                        + fileName
                );
            }
        });

        return 0;

    }
    else
    {
        try {

            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpsURLConnection) url.openConnection();
            conn.setConnectTimeout(360000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "bearer " + token.getAccess());
            conn.setRequestProperty("Connection", "Keep-Alive" );
            conn.setRequestProperty("ENCTYPE", "multipart/form-data" );
            conn.setRequestProperty("Transfer-Encoding","chunked" );
            conn.setChunkedStreamingMode(1024);
            //conn.setRequestProperty("file", sourceFile.getPath());
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                            + fileName + "\"" + lineEnd
            );

                    dos.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                sendBytes = sendBytes + bytesRead;

                runOnUiThread(new Runnable() {
                    public void run() {
                        sizeTextView.setText("BUFFER-SIZE: " + bufferSize + "\nNAME: " + fileName + "\nSIZE: " + sendBytes);
                    }
                });
            }


            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){

                runOnUiThread(new Runnable() {
                    public void run() {

                        resultTextView.append("\nUPLOAD-CODE: " + serverResponseCode);
                        String msg = "\nFile Upload Completed.\n\n See uploaded file here : \n\n"
                                + fileName;

                        resultTextView.append(msg);
                        Toast.makeText(UploadActivity.this, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    resultTextView.append("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadActivity.this, "MalformedURLException",
                            Toast.LENGTH_SHORT).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    resultTextView.append("Got Exception : see logcat ");
                    Toast.makeText(UploadActivity.this, "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload-Exception", "Exception : "
                    + e.getMessage(), e);
        }
        return serverResponseCode;

    } // End else block
}

AndroidManifest

        android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

测试服务器时,没有发现任何问题!相同的文件传输方法在带有 -Xmx10M 的普通控制台模式(机器人)下效果很好;

服务器:

@PostMapping("/{id}/file")
public void uploadFile(@PathVariable("id") Request request, @RequestParam("file") MultipartFile[] files){
    log.info("==========================================");
    log.info("===uploadFile2:start:" + request.getId());

    if (files.length<1) {
        throw new StorageException("No Files");
    }

    try {

        FileUpload.saveUploadedFiles(Arrays.asList(files), "/request/1266123/");

    } catch (IOException e) {
        throw new StorageException("File upload error", e);
    }

    log.info("Successfully uploaded - " + files.length);

}

提前感谢您的回复。

PS / 感觉好像只从原始流中读取了52MB,然后发送。

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-02-10 06:13:13 +0000 UTC

Gradle从网络上下载很多

  • 0

大家好。

面对 Gradle,我也遇到了一个问题——它下载(乱扔)一个螺丝给我,因为它下载了 20GB 到本地萝卜。虽然它只需要几个库。

这是代码:

buildscript {
        repositories {
            mavenCentral()
            maven { url "https://repo.spring.io/snapshot" }
            maven { url "https://repo.spring.io/milestone" }
            maven { url "https://repo.spring.io/libs-milestone" }
        }
    }

    dependencies {
        compile('org.springframework.boot:spring-boot-starter-data-jpa')
        compile('org.springframework.boot:spring-boot-starter-data-solr')
        compile('org.springframework.security:spring-security-core')
        compile('org.apache.commons:commons-lang3')
        compile('com.google.guava:guava:24.0-jre')

        testCompile('org.springframework.boot:spring-boot-starter-test')
    }

    dependencyManagement {
        imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") }
    }

他为什么抽这么多?(虽然这不是限制,我只是停止下载)。事实上,在repositories部分,我们必须指出在哪里寻找我们需要的库,在这种情况下它在mavenCentral

或者可能是因为依赖项没有指定版本?

我只是一直与 Maven 合作,但在网上我没有找到任何关于我的问题的信息......

谢谢你。

gradle
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-01-15 01:17:53 +0000 UTC

SPRING - 数据源(SQL 错误:1054,SQLState:42S22)

  • 0

大家好。有一个标准的 Java 栈,SpringBoot-2.0.0,MySQL。并且在尝试访问数据库时,出现了表单问题(表中的未知列)但不要急于写答案:

2019-01-14 18:33:33.617  WARN 9388 --- [nio-5000-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1054, SQLState: 42S22
2019-01-14 18:33:33.617 ERROR 9388 --- [nio-5000-exec-5] o.h.engine.jdbc.spi.SqlExceptionHelper   : Unknown column 'user0_.createdAt' in 'field list'
2019-01-14 18:33:33.626 ERROR 9388 --- [nio-5000-exec-5] c.e.p.s.JwtAuthenticationEntryPoint      : Responding with unauthorized error. Message - could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

实际上,这个“未知字段”在被调用实体的父类中。接下来我会发布代码...

由于我开始在类中配置 DataSource 和其他设置,因此出现了这个问题。请解释一下,最好举个例子,我做错了什么......

例如,我发布源代码:

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(
        value = {"createdAt", "updatedAt"},
        allowGetters = true
)
public abstract class DateAudit implements Serializable {

    @CreatedDate
    @Column(name = "createdAt")
    private Instant createdAt;

    @LastModifiedDate
    @Column(name = "updatedAt")
    private Instant updatedAt;

    public Instant getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Instant createdAt) {
        this.createdAt = createdAt;
    }

    public Instant getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Instant updatedAt) {
        this.updatedAt = updatedAt;
    }

}

这是继承这个类的实体,当它被调用时,就会出现问题

@Entity
@Table(name = "users", uniqueConstraints = {
        @UniqueConstraint(columnNames = {
            "username"
        }),
        @UniqueConstraint(columnNames = {
            "email"
        })
})
public class User extends DateAudit {
    private static final long serialVersionUID = 1000000000000111L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @NotBlank
    @Size(max = 40)
    @Column(name = "name")
    private String name;

    @NotBlank
    @Size(max = 15)
    @Column(name = "username")
    private String username;

    @NaturalId
    @NotBlank
    @Size(max = 40)
    @Email
    @Column(name = "email")
    private String email;

    @NotBlank
    @Size(max = 100)
    @Column(name = "password")
    private String password;


    public User() {

    }

    public User(String name, String username, String email, String password) {
        this.name = name;
        this.username = username;
        this.email = email;
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

这是带有配置的命运多舛的班级

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", basePackages = {"com.repo"} )
public class FooDbConfig {

    @Autowired
    private Environment env;

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driverClassName"));
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));

        return dataSource;
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {
        HashMap<String, Object> properties = new HashMap<>();
        properties.put(" hibernate.ddl-auto", "update");
                //env.getProperty(""));
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
                //env.getProperty("org.hibernate.dialect.MySQL5InnoDBDialect"));

        return builder.dataSource(dataSource)
                .packages("com.model")
                .persistenceUnit("test")
                .properties(properties)
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

}

结果是这样的——如果我从 conf.xml 中删除这个类。 那么一切都很好!

提前感谢您的回复!PS/不要关注@Primary,我需要它。有多个数据库...

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-07-18 00:52:52 +0000 UTC

JavaScript 发送带照片的缓冲区

  • 0

为了将照片发送到 node-js,我使用以下代码:

    ...

    request.post({
    url: 'https://host.net',
    data: {
        note: 'Photo',
        file: fs.createReadStream('path/to/b101.jpg'),
        filename: 't100.jpg',
    },
}, function(error, response, body) {
    console.log("BODY: " + body);
    console.log("RESPONSE: " + JSON.stringify(response) );
});

...

但是我经常发生照片在缓冲区中,没有本地存储,例如:

var photoBuffer = Buffer.from([255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,254,0,59,67,82,69,65,84 ...]);

如何转换 Buffer-to-Stream 并将这个流或只是一个缓冲区发送到服务器?

目前,我什至在心轴之前得到一个空流或一个错误。在空流的情况下,我看到 msj 可能会到达服务器。在响应代码= 200。

也许服务器端也有一些限制?

javascript
  • 2 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-05-04 21:57:45 +0000 UTC

列表到 Json 序列化

  • 1

大家好。并立即问题:如何将 List 转换为 Json

如果我将一个Car 对象转换为 Json-obj,那么一切都很好

Car cars = carSrv.getById(1);
 Gson gson = new GsonBuilder().create();
 String jse = gson.toJson(cars);

尝试使用列表执行此操作时(Json 中的列表)

 List<Car> cars = carSrv.getAll();
 Gson gson = new GsonBuilder().create();
 String jse = gson.toJson(cars);

执行崩溃:

    java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
    at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:76)
    at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:69)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ArrayTypeAdapter.write(ArrayTypeAdapter.java:93)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
    at com.google.gson.Gson.toJson(Gson.java:661)
    at com.google.gson.Gson.toJson(Gson.java:640)
    at com.google.gson.Gson.toJson(Gson.java:595)
    at com.google.gson.Gson.toJson(Gson.java:575)
...

我正在使用 Gson 库:

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.6.2</version>
        </dependency>

在网上的某个地方,我找到了一个带有类型指示的解决方案:

 List<Car> cars = carSrv.getAll();
 Gson gson = new GsonBuilder().create();
 Type listType = new TypeToken<List<Car>>() {}.getType();
String jse = gson.toJson(cars, listType);

没有帮助!相同的ekzepshn

我在这里找到了另一个解决方案和很多重复项:) 不过,我认为这里的问题不在于休眠,而在于序列化

 List<Car> cars = carSrv.getAll();
 Gson gson = new GsonBuilder()
            .registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY)
            .create();
 String jse = gson.toJson(cars);

我从示例中获取了 HibernateProxyTypeAdapter 类。

public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {

public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
    @Override
    @SuppressWarnings("unchecked")
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        return (HibernateProxy.class.isAssignableFrom(type.getRawType()) ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(gson) : null);
    }
};
private final Gson context;

private HibernateProxyTypeAdapter(Gson context) {
    this.context = context;
}

@Override
public HibernateProxy read(JsonReader in) throws IOException {
    throw new UnsupportedOperationException("Not supported");
}

@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void write(JsonWriter out, HibernateProxy value) throws IOException {
    if (value == null) {
        out.nullValue();
        return;
    }
    // Retrieve the original (not proxy) class
    Class<?> baseType = Hibernate.getClass(value);
    // Get the TypeAdapter of the original class, to delegate the serialization
    TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
    // Get a filled instance of the original class
    Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer()
            .getImplementation();
    // Serialize the value
    delegate.write(out, unproxiedValue);
}

}

没有帮助!查看例外:

2018-мая-04 16:33:00.829 ERROR [http-nio-8080-exec-8] o.s.b.w.s.ErrorPageFilter - Forwarding to error page from request [/aes/by/id] due to exception [null]
java.lang.StackOverflowError: null
    at com.google.gson.internal.bind.TypeAdapters$11.write(TypeAdapters.java:317)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
    at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:97)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:61)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
    at ua.avk.carwash.adapter.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:54)
    at ua.avk.carwash.adapter.HibernateProxyTypeAdapter.write(HibernateProxyTypeAdapter.java:19)
    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:112)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:239)
    at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:968)

这是 Car 类本身,以防万一:

    @JsonInclude(JsonInclude.Include.NON_NULL)
@Entity
@Table(name = "Car")
public class Car implements Serializable, Storable {
    private static final long serialVersionUID = 1000000000000111L;
    public static final String GET_BY_NAME = "select e from Car e where e.name = ?1";
    public static final String GET_BY_TYPE = "select e from Car e where e.carType = ?1";
    public static final String GET_BY_NUMBER = "select e from Car e where e.number = ?1";
    public static final String GET_BY_CLIENT = "select e from Car e where e.client = ?1";

    private Long id;
    private String name;
    private String number;
    private CarType carType;
    private Client client;
    private List<Order> orderList = new ArrayList<>();

    @JsonView(Views.User.class)
    @JsonProperty("id")
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "car_id", nullable = false)
    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @JsonProperty("name")
    @JsonView(Views.User.class)
    @Size(max = 50, message = "{size.field}")
    @Column(name = "name", nullable = true, insertable = true, updatable = true, length = 50)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonProperty("number")
    @JsonView(Views.User.class)
    @Size(max = 8, message = "The car number must be {min} to {max} characters in length.")
    @Column(name = "number", nullable = true, insertable = true, updatable = true, length = 8)
    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @JsonProperty("cartype")
    @JsonView(Views.User.class)
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "type_id", nullable = true, insertable = true, updatable = true)
    public CarType getCarType() {
        return carType;
    }

    public void setCarType(CarType carType) {
        this.carType = carType;
    }

    @JsonProperty("client")
    @JsonView(Views.User.class)
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "client_id", nullable = true, insertable = true, updatable = true)
    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    //@Transient
    @JsonProperty("orders")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonView(Views.Admin.class)
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "car")
    //@Column(name = "order_id")
    public List<Order> getOrderList() {
        return orderList;
    }

    public void setOrderList(List<Order> orderList) {
        this.orderList = orderList;
    }

    @Override
    public String toString() {
        return String.format("%d, %s, %s, %s, %s;", id, name, number, carType, client);
    }

    /**
     * The method Copy the object of the car
     *
     * @param u - the object of the car
     */
    public void copy(Car u) {
        this.setClient(u.getClient());
        this.setOrderList(u.getOrderList());
        this.setName(u.getName());
        this.setNumber(u.getNumber());
        this.setCarType(u.getCarType());
    }

    /**
     * Override hashCode for correct work equals
     *
     * @return hashCode
     */
    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(this.client)
                .append(this.name)
                .append(this.number)
                .append(this.carType)
                .toHashCode();
    }

    /**
     * Compares of the car
     *
     * @param obj for compare
     * @return true if equals
     */
    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Car))
            return false;
        if (obj == this)
            return true;

        Car u = (Car) obj;
        return new EqualsBuilder()
                .append(this.client, u.client)
                .append(this.name, u.name)
                .append(this.number, u.number)
                .append(this.carType, u.carType)
                .isEquals();
    }

}

问题:在这种情况下如何将 List 转换为 Json

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-03-28 23:12:15 +0000 UTC

Java 日志记录

  • 0

日志问题。一般来说,如果我把它放在 JAR 旁边,我的 log4j.xml 配置不会被选中。

System.setProperty("log4j.configuration", String.valueOf((new File(PATH, LOG_FILE).toURL())))

像这样写:

ERROR StatusLogger No log4j2 configuration file found. Using default configurat

如果我将它打包到一个 JAR 中,或者在编译后“强制”添加它,那么一切都会自然而然地工作。

日志版本:

        <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.10.0</version>
    </dependency>

这里描述的也没有帮助。提前感谢您的回复。

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-03-14 05:22:15 +0000 UTC

Win-service 停止超时

  • 2

对于测试,我需要一个停止 10-15 分钟的服务。

我创建了我最简单的 Win 服务:

using System;
using System.Diagnostics;
using System.ServiceProcess;

namespace LongService
{   
    public class LongService : ServiceBase
    {
        private EventLog eventLog1;
        public const string MyServiceName = "LongService";
        public const string logName = "LongServiceLog";

        public LongService()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.ServiceName = MyServiceName;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }

        protected override void OnStart(string[] args)
        {
            AddLog("start");
        }

        protected override void OnStop()
        {
            AddLog("stop");
            Process.GetCurrentProcess().WaitForExit(600000);

        }

        public void AddLog(string log)
        {
          try
          {
            if (!EventLog.SourceExists(MyServiceName))
            {
              EventLog.CreateEventSource(MyServiceName, logName);
            }

            eventLog1 = new System.Diagnostics.EventLog();
            eventLog1.Source = MyServiceName;
            eventLog1.Log = logName;            
            eventLog1.WriteEntry(log);
          }
          catch{}
        }


    }
}

问题:如何在服务本身超时的情况下正确推迟(延迟)服务的停止

Process.GetCurrentProcess().WaitForExit(600000);

或者如何在注册表中增加 Windows 的超时时间。因为 在 Windows 中等待服务停止不超过 2 分钟。2 分钟后 Windows 抛出错误

  1. 该服务没有及时响应请求。
c#
  • 2 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-02-09 03:15:50 +0000 UTC

CURL 到 URL 的转换

  • 0

大家好。如何正确地将请求从 curl 传输到 HttpClient 或 URL,更准确地说,我需要登录(获取令牌)

curl trusted-app:secret@localhost:8080/oauth/token -d "grant_type=password&username=user&password=password"

通过 CUrl - 一切正常,我在响应中得到一个令牌,通过 HttpClient 我在响应中得到它

{"timestamp":1518116152990,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/oauth/token"}

我按照这里的描述试过了,但可能搞砸了。

    HttpClient httpClient = HttpClients.createDefault();
    HttpUriRequest request1 = RequestBuilder.get("http://localhost:8080/oauth/token")
                    .addHeader("trusted-app", "secret")
            .setEntity(new UrlEncodedFormEntity(Arrays.asList(
                    new BasicNameValuePair("grant_type", "password"),
                    new BasicNameValuePair("username", "user"),
                    new BasicNameValuePair("password", "password")
            )))
            .build();
    HttpResponse response1 = httpClient.execute(request1);
    Assert.assertEquals(HttpStatus.OK, response1.getStatusLine().getStatusCode());

提前感谢您的回复!

java
  • 2 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-12-25 18:59:18 +0000 UTC

VMware中的vmpath参数

  • 0

如何在 VMware 中找到用于克隆操作的 vmpath 参数? https://code.vmware.com/samples/1067/vmclone?h=vmpath

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-09-27 03:25:38 +0000 UTC

REST 服务 - 并非 JSON 响应中原始对象的所有字段

  • 0

大家好。出现了一个对我来说并不完全清楚的情况:有一个本质

@Entity
@Table(name = "trCompany")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TransportCompany implements Serializable, Storable {
    private static final long serialVersionUID = 1000000005645644L;

    @JsonProperty("id")
    @JsonView(Views.User.class)
    @Id
    @GeneratedValue(generator = "increment")
    @GenericGenerator(name = "increment", strategy = "increment")
    @Column(name = "id", nullable = false)
    private Long id;

    @JsonProperty("name")
    @JsonView(Views.User.class)
    @Column(name = "name", nullable = true, length = 150)
    private String name;

    @JsonProperty("phone")
    @JsonView(Views.User.class)
    @Column(name = "phone", nullable = true)
    private String phone;

    ...

    @Transient
    @JsonView(Views.User.class)
    private Collection<Orders> orderCollection;

    @Override
    public String toString() {
       return String.format("%d, %s, %s, %s;",
            id, name, phone, orderCollection);
    }

    ...

}

有一个dao和services,还有一个view controller

@RestController
public class TransportCompanyController {
.....
    @JsonView(Views.User.class)
    @PreAuthorize(value = "hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
    @RequestMapping(value = "/t/all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity getAll(){

        List<TransportCompany> transportCompanyList = transportCompanyService.getAll();

        System.out.println("TR-COMP: " + transportCompanyList.get(0).toString());

        return ResponseEntity.status(HttpStatus.OK).body(transportCompanyList);
    }
...
}

这一切都包裹在弹簧靴中。一般来说,问题出在收到的 JSON 响应中,它看起来像:

[{"name":"Новая почта","phone":"+380671111111"},{...},{...}] 

我,嗯,非常,非常需要答案看起来像这样,带有ID:

 [{"id":"1","name":"Новая почта","phone":"+380671111111"},{...},{...}] 

一般来说,JSON 表示存在问题,尽管使用类似描述的其他对象的实体,但类似的实体,对象及其控制器分别工作正常,即 回复带有 ID - 正如预期的那样......提前感谢您的回复! PS/以防万一。控制器内部有 System.out,那里一切正常。ID 存在。

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-09-07 03:47:21 +0000 UTC

Angular ng-repeat 连续显示值

  • 0

大家好。面临连续显示一个对象数组的值的问题。这是一个示例代码:

<div id="catBlock">
    <div ng-style="catBlock" ng-repeat="cat in list | orderBy: 'id' ">
                <img width="120px" height="150px" src='{{cat.imgPath}}' title="{{cat.name}}"/>
            </div>
    </div>
</div>

$scope.catBlock = {
    "display": "inline",
    "clear": "both",
    "border": "1px solid #666666",
    "background": "#555555",
    "width": "165px",
    "height": "210px"
};

输出在列中是标准的 在此处输入图像描述

需要做什么才能使列表显示在一行中,而不是在一列中?提前感谢您的回复。


PS/有一个假设,这是不能用常规 CSS 解决的,你可能不得不用 repeat 和 if 来变态。

css
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-09-02 05:19:37 +0000 UTC

Tomcat - 在页面上显示上传的文件

  • 0

大家好。application on Tomcat, SpringBoot, Angular(windows 测试机) 任务标准上传到服务器,保存,显示。有一个用于将照片上传到服务器的页面。照片正常加载到带有凹槽“E://path//to//files//img.jpg”的文件系统中。
问题是:我怎样才能让它们脱离这个凹槽“E://path//to//files//img.jpg”并将它们显示在页面上。获取并渲染来自“资源”的静态内容

在一些资源上,我在这里和这里找到了 tomcat 的解决方案,但它不起作用(或者我不明白)

<Context docBase="Е://path//to//files" path="/files" />

然后它不会出现。

<img src="/files/img.jpg">

提前感谢您的回复!

java
  • 1 个回答
  • 10 Views
Martin Hope
Alex
Asked: 2020-07-22 14:24:27 +0000 UTC

如何在 Android-2.3 上安装 Viber 或 WhatsApp

  • 0

大家好。 鉴赏家 - 注意问题!

  1. 如何在 Android 2.3.4 上安装 Viber 或 WhatsApp。Viber - 官方已经放弃了对旧版本的支持(最小 OS-4.0),WhatsApp-2.16(OS 2.3-4.0)也有一些难以理解的问题,安装后看不到网络和日期问题设置(我试图更改日期),并且可能未安装 WhatsApp-2.17。仅支持 Android-4.0。

  2. 我无法在手机上刷入 Android-4.0,因为。手机上没有足够的空间 (ROM)。

可用,旧款: Fly IQ270 CPU:MTK-6573 RAM:256 ROM:512 + microCD 屏幕:3.75",传感器,480x320

PS/试图作弊。我注册了版本 4.4.2 和 API 19 - 一切都已安装,但煎饼不起作用。虽然我改了API之后,另一个软件就不能用了,一般来说,你需要彻底刷机,虽然手机好像没问题。

android
  • 2 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5